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
apache-2.0
6c734952bdc489ba7ca6017be6584717cdc4a00d
0
Jonss/vraptor4,rpeleias/vraptor4,michelmedeiros/vraptor4,khajavi/vraptor4,nykolaslima/vraptor4,felipeweb/vraptor4,Philippe2201/vraptor4,clebersonpp/vraptor4,tempbottle/vraptor4,Jonss/vraptor4,Philippe2201/vraptor4,danilomunoz/vraptor4,rpeleias/vraptor4,nykolaslima/vraptor4,Philippe2201/vraptor4,garcia-jj/vraptor4-fork,nykolaslima/vraptor4,Jonss/vraptor4,danilomunoz/vraptor4,Philippe2201/vraptor4,clebersonpp/vraptor4,rpeleias/vraptor4,danilomunoz/vraptor4,caelum/vraptor4,tempbottle/vraptor4,tempbottle/vraptor4,felipeweb/vraptor4,Philippe2201/vraptor4,rpeleias/vraptor4,clebersonpp/vraptor4,Jonss/vraptor4,felipeweb/vraptor4,caelum/vraptor4,Knoobie/vraptor4,caelum/vraptor4,caelum/vraptor4,nykolaslima/vraptor4,khajavi/vraptor4,danilomunoz/vraptor4,felipeweb/vraptor4,clebersonpp/vraptor4,rpeleias/vraptor4,Knoobie/vraptor4,michelmedeiros/vraptor4,khajavi/vraptor4,garcia-jj/vraptor4-fork,caelum/vraptor4,felipeweb/vraptor4,Knoobie/vraptor4,clebersonpp/vraptor4,tempbottle/vraptor4,khajavi/vraptor4,michelmedeiros/vraptor4,nykolaslima/vraptor4,Jonss/vraptor4,michelmedeiros/vraptor4,garcia-jj/vraptor4-fork,garcia-jj/vraptor4-fork,Knoobie/vraptor4,danilomunoz/vraptor4,tempbottle/vraptor4,Knoobie/vraptor4,michelmedeiros/vraptor4,garcia-jj/vraptor4-fork,khajavi/vraptor4
/*** * Copyright (c) 2009 Caelum - www.caelum.com.br/opensource * 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 br.com.caelum.vraptor.core; import java.lang.annotation.Annotation; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import javax.enterprise.util.AnnotationLiteral; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import br.com.caelum.vraptor.Controller; import br.com.caelum.vraptor.Convert; import br.com.caelum.vraptor.Intercepts; import br.com.caelum.vraptor.deserialization.Deserializer; import br.com.caelum.vraptor.deserialization.Deserializes; import br.com.caelum.vraptor.deserialization.DeserializesHandler; import br.com.caelum.vraptor.deserialization.XMLDeserializer; import br.com.caelum.vraptor.ioc.ControllerHandler; import br.com.caelum.vraptor.ioc.ConverterHandler; import br.com.caelum.vraptor.ioc.InterceptorStereotypeHandler; /** * List of base components to vraptor.<br/> * Those components should be available with any chosen ioc implementation. * * @author guilherme silveira */ public class BaseComponents { static final Logger logger = LoggerFactory.getLogger(BaseComponents.class); private static final HashMap<Class<? extends Annotation>, StereotypeInfo> STEREOTYPES_INFO = new HashMap<Class<? extends Annotation>,StereotypeInfo>(); static { STEREOTYPES_INFO.put(Controller.class,new StereotypeInfo(Controller.class,ControllerHandler.class,new AnnotationLiteral<ControllerQualifier>() {})); STEREOTYPES_INFO.put(Convert.class,new StereotypeInfo(Convert.class,ConverterHandler.class,new AnnotationLiteral<ConvertQualifier>() {})); STEREOTYPES_INFO.put(Deserializes.class,new StereotypeInfo(Deserializes.class,DeserializesHandler.class,new AnnotationLiteral<DeserializesQualifier>() {})); STEREOTYPES_INFO.put(Intercepts.class,new StereotypeInfo(Intercepts.class,InterceptorStereotypeHandler.class,new AnnotationLiteral<InterceptsQualifier>() {})); } private static final Set<Class<? extends Deserializer>> DESERIALIZERS = Collections.<Class<? extends Deserializer>>singleton(XMLDeserializer.class); public static Set<Class<? extends Deserializer>> getDeserializers() { return DESERIALIZERS; } public static Set<StereotypeInfo> getStereotypesInfo() { return new HashSet<StereotypeInfo>(STEREOTYPES_INFO.values()); } public static Set<Class<? extends Annotation>> getStereotypes() { Set<StereotypeInfo> stereotypesInfo = getStereotypesInfo(); HashSet<Class<? extends Annotation>> stereotypes = new HashSet<Class<? extends Annotation>>(); for (StereotypeInfo stereotypeInfo : stereotypesInfo) { stereotypes.add(stereotypeInfo.getStereotype()); } return stereotypes; } public static Map<Class<? extends Annotation>,StereotypeInfo> getStereotypesInfoMap() { return STEREOTYPES_INFO; } }
vraptor-core/src/main/java/br/com/caelum/vraptor/core/BaseComponents.java
/*** * Copyright (c) 2009 Caelum - www.caelum.com.br/opensource * 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 br.com.caelum.vraptor.core; import java.lang.annotation.Annotation; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; import javax.enterprise.util.AnnotationLiteral; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import br.com.caelum.vraptor.Controller; import br.com.caelum.vraptor.Convert; import br.com.caelum.vraptor.Intercepts; import br.com.caelum.vraptor.deserialization.Deserializer; import br.com.caelum.vraptor.deserialization.Deserializes; import br.com.caelum.vraptor.deserialization.DeserializesHandler; import br.com.caelum.vraptor.deserialization.XMLDeserializer; import br.com.caelum.vraptor.ioc.ControllerHandler; import br.com.caelum.vraptor.ioc.ConverterHandler; import br.com.caelum.vraptor.ioc.InterceptorStereotypeHandler; /** * List of base components to vraptor.<br/> * Those components should be available with any chosen ioc implementation. * * @author guilherme silveira */ public class BaseComponents { static final Logger logger = LoggerFactory.getLogger(BaseComponents.class); private static final HashMap<Class<? extends Annotation>, StereotypeInfo> STEREOTYPES_INFO = new HashMap<Class<? extends Annotation>,StereotypeInfo>(); static { STEREOTYPES_INFO.put(Controller.class,new StereotypeInfo(Controller.class,ControllerHandler.class,new AnnotationLiteral<ControllerQualifier>() {})); STEREOTYPES_INFO.put(Convert.class,new StereotypeInfo(Convert.class,ConverterHandler.class,new AnnotationLiteral<ConvertQualifier>() {})); STEREOTYPES_INFO.put(Deserializes.class,new StereotypeInfo(Deserializes.class,DeserializesHandler.class,new AnnotationLiteral<DeserializesQualifier>() {})); STEREOTYPES_INFO.put(Intercepts.class,new StereotypeInfo(Intercepts.class,InterceptorStereotypeHandler.class,new AnnotationLiteral<InterceptsQualifier>() {})); } private static final Set<Class<? extends Deserializer>> DESERIALIZERS = Collections.<Class<? extends Deserializer>>singleton(XMLDeserializer.class); public static Set<Class<? extends Deserializer>> getDeserializers() { return DESERIALIZERS; } public static Set<StereotypeInfo> getStereotypesInfo() { return new HashSet<StereotypeInfo>(STEREOTYPES_INFO.values()); } public static Set<Class<? extends Annotation>> getStereotypes() { Set<StereotypeInfo> stereotypesInfo = getStereotypesInfo(); HashSet<Class<? extends Annotation>> stereotypes = new HashSet<Class<? extends Annotation>>(); for (StereotypeInfo stereotypeInfo : stereotypesInfo) { stereotypes.add(stereotypeInfo.getStereotype()); } return stereotypes; } public static Map<Class<? extends Annotation>,StereotypeInfo> getStereotypesInfoMap() { return STEREOTYPES_INFO; } private static Map<Class<?>, Class<?>> classMap(Class<?>... items) { HashMap<Class<?>, Class<?>> map = new HashMap<Class<?>, Class<?>>(); Iterator<Class<?>> it = Arrays.asList(items).iterator(); while (it.hasNext()) { Class<?> key = it.next(); Class<?> value = it.next(); if (value == null) { throw new IllegalArgumentException("The number of items should be even."); } map.put(key, value); } return map; } }
removing unused stuff
vraptor-core/src/main/java/br/com/caelum/vraptor/core/BaseComponents.java
removing unused stuff
Java
apache-2.0
182ba4a01e8ba3aea95e19be6868269ee0211937
0
BrynCooke/incubator-tinkerpop,mike-tr-adamson/incubator-tinkerpop,krlohnes/tinkerpop,jorgebay/tinkerpop,apache/tinkerpop,krlohnes/tinkerpop,mike-tr-adamson/incubator-tinkerpop,mpollmeier/tinkerpop3,robertdale/tinkerpop,BrynCooke/incubator-tinkerpop,pluradj/incubator-tinkerpop,velo/incubator-tinkerpop,krlohnes/tinkerpop,apache/tinkerpop,RedSeal-co/incubator-tinkerpop,Lab41/tinkerpop3,rmagen/incubator-tinkerpop,rmagen/incubator-tinkerpop,mpollmeier/tinkerpop3,RedSeal-co/incubator-tinkerpop,PommeVerte/incubator-tinkerpop,dalaro/incubator-tinkerpop,PommeVerte/incubator-tinkerpop,edgarRd/incubator-tinkerpop,apache/incubator-tinkerpop,edgarRd/incubator-tinkerpop,velo/incubator-tinkerpop,jorgebay/tinkerpop,RussellSpitzer/incubator-tinkerpop,pluradj/incubator-tinkerpop,vtslab/incubator-tinkerpop,apache/incubator-tinkerpop,BrynCooke/incubator-tinkerpop,vtslab/incubator-tinkerpop,samiunn/incubator-tinkerpop,dalaro/incubator-tinkerpop,jorgebay/tinkerpop,apache/tinkerpop,rmagen/incubator-tinkerpop,robertdale/tinkerpop,apache/tinkerpop,velo/incubator-tinkerpop,jorgebay/tinkerpop,gdelafosse/incubator-tinkerpop,artem-aliev/tinkerpop,robertdale/tinkerpop,apache/tinkerpop,Lab41/tinkerpop3,samiunn/incubator-tinkerpop,apache/incubator-tinkerpop,robertdale/tinkerpop,artem-aliev/tinkerpop,newkek/incubator-tinkerpop,newkek/incubator-tinkerpop,robertdale/tinkerpop,edgarRd/incubator-tinkerpop,apache/tinkerpop,krlohnes/tinkerpop,n-tran/incubator-tinkerpop,samiunn/incubator-tinkerpop,newkek/incubator-tinkerpop,n-tran/incubator-tinkerpop,vtslab/incubator-tinkerpop,n-tran/incubator-tinkerpop,RussellSpitzer/incubator-tinkerpop,gdelafosse/incubator-tinkerpop,artem-aliev/tinkerpop,artem-aliev/tinkerpop,gdelafosse/incubator-tinkerpop,PommeVerte/incubator-tinkerpop,krlohnes/tinkerpop,mike-tr-adamson/incubator-tinkerpop,pluradj/incubator-tinkerpop,dalaro/incubator-tinkerpop,artem-aliev/tinkerpop,apache/tinkerpop,RedSeal-co/incubator-tinkerpop,RussellSpitzer/incubator-tinkerpop
package com.tinkerpop.blueprints; import com.tinkerpop.blueprints.computer.GraphMemory; import com.tinkerpop.blueprints.computer.Messenger; import com.tinkerpop.blueprints.computer.VertexProgram; import org.junit.Test; import org.junit.experimental.runners.Enclosed; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import java.util.Arrays; import java.util.Map; import java.util.concurrent.Future; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import static com.tinkerpop.blueprints.Graph.Features.PropertyFeatures.FEATURE_PROPERTIES; import static com.tinkerpop.blueprints.Graph.Features.GraphFeatures.FEATURE_COMPUTER; /** * Ensure that exception handling is consistent within Blueprints. * * @author Stephen Mallette (http://stephen.genoprime.com) */ @RunWith(Enclosed.class) public class ExceptionConsistencyTest { /** * Checks that properties added to an {@link Element} are validated in a consistent way when they are added at * {@link Vertex} or {@link Edge} construction by throwing an appropriate exception. */ @RunWith(Parameterized.class) public static class PropertyValidationOnAddTest extends AbstractBlueprintsTest { @Parameterized.Parameters(name = "{index}: expect - {1}") public static Iterable<Object[]> data() { return Arrays.asList(new Object[][]{ { new Object[] {"odd", "number", "arguments"},Element.Exceptions.providedKeyValuesMustBeAMultipleOfTwo()}, { new Object[] {"odd"}, Element.Exceptions.providedKeyValuesMustBeAMultipleOfTwo()}, { new Object[] {"odd", "number", 123, "test"}, Element.Exceptions.providedKeyValuesMustHaveALegalKeyOnEvenIndices()}, { new Object[] {"odd", null}, Property.Exceptions.propertyValueCanNotBeNull()}, { new Object[] {null, "val"}, Element.Exceptions.providedKeyValuesMustHaveALegalKeyOnEvenIndices()}, { new Object[] {"", "val"}, Property.Exceptions.propertyKeyCanNotBeEmpty()}}); }; @Parameterized.Parameter(value = 0) public Object[] arguments; @Parameterized.Parameter(value = 1) public Exception expectedException; @Test @FeatureRequirement(featureClass = Graph.Features.VertexPropertyFeatures.class, feature = FEATURE_PROPERTIES) public void testGraphAddVertex() throws Exception { try { this.g.addVertex(arguments); fail(String.format("Call to addVertex should have thrown an exception with these arguments [%s]", arguments)); } catch (Exception ex) { assertEquals(expectedException.getClass(), ex.getClass()); assertEquals(expectedException.getMessage(), ex.getMessage()); } } @Test @FeatureRequirement(featureClass = Graph.Features.EdgePropertyFeatures.class, feature = FEATURE_PROPERTIES) public void testGraphAddEdge() throws Exception { try { final Vertex v = this.g.addVertex(); v.addEdge("label", v, arguments); fail(String.format("Call to addVertex should have thrown an exception with these arguments [%s]", arguments)); } catch (Exception ex) { assertEquals(expectedException.getClass(), ex.getClass()); assertEquals(expectedException.getMessage(), ex.getMessage()); } } } /** * Checks that properties added to an {@link Element} are validated in a consistent way when they are set after * {@link Vertex} or {@link Edge} construction by throwing an appropriate exception. */ @RunWith(Parameterized.class) public static class PropertyValidationOnSetTest extends AbstractBlueprintsTest { @Parameterized.Parameters(name = "{index}: expect - {2}") public static Iterable<Object[]> data() { return Arrays.asList(new Object[][]{ { "k", null, Property.Exceptions.propertyValueCanNotBeNull()}, { null, "v", Property.Exceptions.propertyKeyCanNotBeNull()}, { Property.Key.ID, "v", Property.Exceptions.propertyKeyIdIsReserved()}, { Property.Key.LABEL, "v", Property.Exceptions.propertyKeyLabelIsReserved()}, { "", "v", Property.Exceptions.propertyKeyCanNotBeEmpty()}}); }; @Parameterized.Parameter(value = 0) public String key; @Parameterized.Parameter(value = 1) public String val; @Parameterized.Parameter(value = 2) public Exception expectedException; @Test @FeatureRequirement(featureClass = Graph.Features.VertexPropertyFeatures.class, feature = FEATURE_PROPERTIES) public void testGraphVertexSetPropertyStandard() throws Exception { try { final Vertex v = this.g.addVertex(); v.setProperty(key, val); fail(String.format("Call to Vertex.setProperty should have thrown an exception with these arguments [%s, %s]", key, val)); } catch (Exception ex) { assertEquals(expectedException.getClass(), ex.getClass()); assertEquals(expectedException.getMessage(), ex.getMessage()); } } @Test @FeatureRequirement(featureClass = Graph.Features.EdgePropertyFeatures.class, feature = FEATURE_PROPERTIES) public void testGraphEdgeSetPropertyStandard() throws Exception { try { final Vertex v = this.g.addVertex(); v.addEdge("label", v).setProperty(key, val); fail(String.format("Call to Edge.setProperty should have thrown an exception with these arguments [%s, %s]", key, val)); } catch (Exception ex) { assertEquals(expectedException.getClass(), ex.getClass()); assertEquals(expectedException.getMessage(), ex.getMessage()); } } @Test @FeatureRequirement(featureClass = Graph.Features.VertexPropertyFeatures.class, feature = FEATURE_PROPERTIES) @FeatureRequirement(featureClass = Graph.Features.GraphFeatures.class, feature = FEATURE_COMPUTER) public void testGraphVertexSetPropertyGraphComputer() throws Exception { try { this.g.addVertex(); final Future future = g.compute().program(new MockVertexProgramForVertex(key, val)).submit(); future.get(); fail(String.format("Call to Vertex.setProperty should have thrown an exception with these arguments [%s, %s]", key, val)); } catch (Exception ex) { final Throwable inner = ex.getCause(); assertEquals(expectedException.getClass(), inner.getClass()); assertEquals(expectedException.getMessage(), inner.getMessage()); } } @Test @FeatureRequirement(featureClass = Graph.Features.EdgePropertyFeatures.class, feature = FEATURE_PROPERTIES) @FeatureRequirement(featureClass = Graph.Features.GraphFeatures.class, feature = FEATURE_COMPUTER) public void testGraphEdgeSetPropertyGraphComputer() throws Exception { try { final Vertex v = this.g.addVertex(); v.addEdge("label", v); final Future future = g.compute().program(new MockVertexProgramForEdge(key, val)).submit(); future.get(); fail(String.format("Call to Edge.setProperty should have thrown an exception with these arguments [%s, %s]", key, val)); } catch (Exception ex) { final Throwable inner = ex.getCause(); assertEquals(expectedException.getClass(), inner.getClass()); assertEquals(expectedException.getMessage(), inner.getMessage()); } } /** * Mock {@link VertexProgram} that just dummies up a way to set a property on a {@link Vertex}. */ public static class MockVertexProgramForVertex implements VertexProgram { private final String key; private final String val; public MockVertexProgramForVertex(final String key, final String val) { this.key = key; this.val = val; } @Override public void setup(final GraphMemory graphMemory) { } @Override public void execute(final Vertex vertex, final Messenger messenger, final GraphMemory graphMemory) { vertex.setProperty(this.key, this.val); } @Override public boolean terminate(GraphMemory graphMemory) { return false; } @Override public Map<String, KeyType> getComputeKeys() { return null; } } /** * Mock {@link VertexProgram} that just dummies up a way to set a property on an {@link Edge}. */ public static class MockVertexProgramForEdge implements VertexProgram { private final String key; private final String val; public MockVertexProgramForEdge(final String key, final String val) { this.key = key; this.val = val; } @Override public void setup(final GraphMemory graphMemory) { } @Override public void execute(final Vertex vertex, final Messenger messenger, final GraphMemory graphMemory) { vertex.query().edges().forEach(e->e.setProperty(this.key, this.val)); } @Override public boolean terminate(GraphMemory graphMemory) { return false; } @Override public Map<String, KeyType> getComputeKeys() { return null; } } } }
blueprints/blueprints-test/src/main/java/com/tinkerpop/blueprints/ExceptionConsistencyTest.java
package com.tinkerpop.blueprints; import com.tinkerpop.blueprints.computer.GraphMemory; import com.tinkerpop.blueprints.computer.Messenger; import com.tinkerpop.blueprints.computer.VertexProgram; import org.junit.Test; import org.junit.experimental.runners.Enclosed; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import java.util.Arrays; import java.util.Map; import java.util.concurrent.Future; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import static com.tinkerpop.blueprints.Graph.Features.PropertyFeatures.FEATURE_PROPERTIES; import static com.tinkerpop.blueprints.Graph.Features.GraphFeatures.FEATURE_COMPUTER; /** * Ensure that exception handling is consistent within Blueprints. * * @author Stephen Mallette (http://stephen.genoprime.com) */ @RunWith(Enclosed.class) public class ExceptionConsistencyTest { /** * Checks that properties added to an {@link Element} are validated in a consistent way when they are added at * {@link Vertex} or {@link Edge} construction by throwing an appropriate exception. */ @RunWith(Parameterized.class) public static class PropertyValidationOnAddTest extends AbstractBlueprintsTest { @Parameterized.Parameters(name = "{index}: expect - {1}") public static Iterable<Object[]> data() { return Arrays.asList(new Object[][]{ { new Object[] {"odd", "number", "arguments"},Element.Exceptions.providedKeyValuesMustBeAMultipleOfTwo()}, { new Object[] {"odd"}, Element.Exceptions.providedKeyValuesMustBeAMultipleOfTwo()}, { new Object[] {"odd", "number", 123, "test"}, Element.Exceptions.providedKeyValuesMustHaveALegalKeyOnEvenIndices()}, { new Object[] {"odd", null}, Property.Exceptions.propertyValueCanNotBeNull()}, { new Object[] {null, "val"}, Element.Exceptions.providedKeyValuesMustHaveALegalKeyOnEvenIndices()}, { new Object[] {"", "val"}, Property.Exceptions.propertyKeyCanNotBeEmpty()}}); }; @Parameterized.Parameter(value = 0) public Object[] arguments; @Parameterized.Parameter(value = 1) public Exception expectedException; @Test @FeatureRequirement(featureClass = Graph.Features.VertexPropertyFeatures.class, feature = FEATURE_PROPERTIES) public void testGraphAddVertex() throws Exception { try { this.g.addVertex(arguments); fail(String.format("Call to addVertex should have thrown an exception with these arguments [%s]", arguments)); } catch (Exception ex) { assertEquals(expectedException.getClass(), ex.getClass()); assertEquals(expectedException.getMessage(), ex.getMessage()); } } @Test @FeatureRequirement(featureClass = Graph.Features.EdgePropertyFeatures.class, feature = FEATURE_PROPERTIES) public void testGraphAddEdge() throws Exception { try { final Vertex v = this.g.addVertex(); v.addEdge("label", v, arguments); fail(String.format("Call to addVertex should have thrown an exception with these arguments [%s]", arguments)); } catch (Exception ex) { assertEquals(expectedException.getClass(), ex.getClass()); assertEquals(expectedException.getMessage(), ex.getMessage()); } } } /** * Checks that properties added to an {@link Element} are validated in a consistent way when they are set after * {@link Vertex} or {@link Edge} construction by throwing an appropriate exception. */ @RunWith(Parameterized.class) public static class PropertyValidationOnSetTest extends AbstractBlueprintsTest { @Parameterized.Parameters(name = "{index}: expect - {2}") public static Iterable<Object[]> data() { return Arrays.asList(new Object[][]{ { "k", null, Property.Exceptions.propertyValueCanNotBeNull()}, { null, "v", Property.Exceptions.propertyKeyCanNotBeNull()}, { Property.Key.ID, "v", Property.Exceptions.propertyKeyIdIsReserved()}, { Property.Key.LABEL, "v", Property.Exceptions.propertyKeyLabelIsReserved()}, { "", "v", Property.Exceptions.propertyKeyCanNotBeEmpty()}}); }; @Parameterized.Parameter(value = 0) public String key; @Parameterized.Parameter(value = 1) public String val; @Parameterized.Parameter(value = 2) public Exception expectedException; @Test @FeatureRequirement(featureClass = Graph.Features.VertexPropertyFeatures.class, feature = FEATURE_PROPERTIES) public void testGraphVertexSetPropertyStandard() throws Exception { try { final Vertex v = this.g.addVertex(); v.setProperty(key, val); fail(String.format("Call to Vertex.setProperty should have thrown an exception with these arguments [%s, %s]", key, val)); } catch (Exception ex) { assertEquals(expectedException.getClass(), ex.getClass()); assertEquals(expectedException.getMessage(), ex.getMessage()); } } @Test @FeatureRequirement(featureClass = Graph.Features.EdgePropertyFeatures.class, feature = FEATURE_PROPERTIES) public void testGraphEdgeSetPropertyStandard() throws Exception { try { final Vertex v = this.g.addVertex(); v.addEdge("label", v).setProperty(key, val); fail(String.format("Call to Edge.setProperty should have thrown an exception with these arguments [%s, %s]", key, val)); } catch (Exception ex) { assertEquals(expectedException.getClass(), ex.getClass()); assertEquals(expectedException.getMessage(), ex.getMessage()); } } @Test @FeatureRequirement(featureClass = Graph.Features.VertexPropertyFeatures.class, feature = FEATURE_PROPERTIES) @FeatureRequirement(featureClass = Graph.Features.GraphFeatures.class, feature = FEATURE_COMPUTER) public void testGraphVertexSetPropertyGraphComputer() throws Exception { try { this.g.addVertex(); final Future future = g.compute().program(new MockVertexProgramForVertex(key, val)).submit(); future.get(); fail(String.format("Call to Vertex.setProperty should have thrown an exception with these arguments [%s, %s]", key, val)); } catch (Exception ex) { final Throwable inner = ex.getCause(); assertEquals(expectedException.getClass(), inner.getClass()); assertEquals(expectedException.getMessage(), inner.getMessage()); } } /* @Test @FeatureRequirement(featureClass = Graph.Features.EdgePropertyFeatures.class, feature = FEATURE_PROPERTIES) @FeatureRequirement(featureClass = Graph.Features.GraphFeatures.class, feature = FEATURE_COMPUTER) public void testGraphEdgeSetPropertyGraphComputer() throws Exception { try { final Vertex v = this.g.addVertex(); v.addEdge("label", v).setProperty(key, val); fail(String.format("Call to Edge.setProperty should have thrown an exception with these arguments [%s, %s]", key, val)); } catch (Exception ex) { assertEquals(expectedException.getClass(), ex.getClass()); assertEquals(expectedException.getMessage(), ex.getMessage()); } } */ /** * Mock {@link VertexProgram} that just dummies up a way to set a property on an {@link Vertex}. */ public static class MockVertexProgramForVertex implements VertexProgram { private final String key; private final String val; public MockVertexProgramForVertex(final String key, final String val) { this.key = key; this.val = val; } @Override public void setup(final GraphMemory graphMemory) { } @Override public void execute(final Vertex vertex, final Messenger messenger, final GraphMemory graphMemory) { vertex.setProperty(this.key, this.val); } @Override public boolean terminate(GraphMemory graphMemory) { return false; } @Override public Map<String, KeyType> getComputeKeys() { return null; } } } }
Exception consistency on GraphComputer setProperty on Edge.
blueprints/blueprints-test/src/main/java/com/tinkerpop/blueprints/ExceptionConsistencyTest.java
Exception consistency on GraphComputer setProperty on Edge.
Java
apache-2.0
b07b0b6a203d33f56351d88d118eeeaea95a1065
0
ehcache/ehcache3-samples,henri-tremblay/ehcache3-samples,henri-tremblay/ehcache3-samples,henri-tremblay/ehcache3-samples,ehcache/ehcache3-samples,ehcache/ehcache3-samples,henri-tremblay/ehcache3-samples,ehcache/ehcache3-samples,ehcache/ehcache3-samples
package org.terracotta.demo.config; import org.ehcache.clustered.client.config.ClusteredStoreConfiguration; import org.ehcache.clustered.client.config.builders.ClusteredResourcePoolBuilder; import org.ehcache.clustered.client.config.builders.ClusteringServiceConfigurationBuilder; import org.ehcache.clustered.client.config.builders.ServerSideConfigurationBuilder; import org.ehcache.clustered.common.Consistency; import org.ehcache.config.builders.CacheConfigurationBuilder; import org.ehcache.config.builders.ResourcePoolsBuilder; import org.ehcache.config.units.MemoryUnit; import org.ehcache.core.config.DefaultConfiguration; import org.ehcache.expiry.Expirations; import org.ehcache.jsr107.EhcacheCachingProvider; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.autoconfigure.AutoConfigureBefore; import org.springframework.cache.annotation.CachingConfigurerSupport; import org.springframework.cache.annotation.EnableCaching; import org.springframework.cache.jcache.JCacheCacheManager; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.env.Environment; import org.terracotta.demo.domain.Actor; import org.terracotta.demo.domain.Authority; import org.terracotta.demo.domain.PersistentAuditEvent; import org.terracotta.demo.domain.PersistentToken; import org.terracotta.demo.domain.User; import java.net.URI; import java.util.HashMap; import java.util.Map; import java.util.concurrent.TimeUnit; import javax.annotation.PreDestroy; import javax.cache.CacheManager; import javax.cache.Caching; import javax.inject.Inject; @SuppressWarnings("unused") @Configuration @EnableCaching @AutoConfigureBefore(value = { MetricsConfiguration.class, DatabaseConfiguration.class }) public class CacheConfiguration extends CachingConfigurerSupport { private final Logger log = LoggerFactory.getLogger(CacheConfiguration.class); @Inject private Environment env; @Inject private JHipsterProperties properties; private CacheManager cacheManager; @Bean @Override public org.springframework.cache.CacheManager cacheManager() { cacheManager = env.acceptsProfiles(Constants.SPRING_PROFILE_PRODUCTION) ? createClusteredCacheManager() : createInMemoryCacheManager(); return new JCacheCacheManager(cacheManager); } @PreDestroy public void destroy() { log.info("Close Cache Manager"); cacheManager.close(); } private CacheManager createInMemoryCacheManager() { long cacheSize = properties.getCache().getEhcache().getSize(); long ttl = properties.getCache().getEhcache().getTimeToLiveSeconds(); org.ehcache.config.CacheConfiguration<Object, Object> cacheConfiguration = CacheConfigurationBuilder .newCacheConfigurationBuilder(Object.class, Object.class, ResourcePoolsBuilder .newResourcePoolsBuilder() .heap(cacheSize)) .withExpiry(Expirations.timeToLiveExpiration(new org.ehcache.expiry.Duration(ttl, TimeUnit.SECONDS))) .build(); Map<String, org.ehcache.config.CacheConfiguration<?, ?>> caches = createCacheConfigurations(cacheConfiguration); EhcacheCachingProvider provider = getCachingProvider(); DefaultConfiguration configuration = new DefaultConfiguration(caches, provider.getDefaultClassLoader()); return provider.getCacheManager(provider.getDefaultURI(), configuration); } private CacheManager createClusteredCacheManager() { JHipsterProperties.Cache.Ehcache.Cluster clusterProperties = properties.getCache().getEhcache().getCluster(); URI clusterUri = clusterProperties.getUri(); boolean autoCreate = clusterProperties.isAutoCreate(); long clusteredCacheSize = clusterProperties.getSizeInMb(); Consistency consistency = clusterProperties.getConsistency(); long heapCacheSize = properties.getCache().getEhcache().getSize(); long ttl = properties.getCache().getEhcache().getTimeToLiveSeconds(); ClusteringServiceConfigurationBuilder clusteringServiceConfigurationBuilder = ClusteringServiceConfigurationBuilder.cluster(clusterUri); ServerSideConfigurationBuilder serverSideConfigurationBuilder = (autoCreate ? clusteringServiceConfigurationBuilder.autoCreate() : clusteringServiceConfigurationBuilder.expecting()) .defaultServerResource("primary-server-resource"); org.ehcache.config.CacheConfiguration<Object, Object> cacheConfiguration = CacheConfigurationBuilder .newCacheConfigurationBuilder(Object.class, Object.class, ResourcePoolsBuilder .newResourcePoolsBuilder() .heap(heapCacheSize) .with(ClusteredResourcePoolBuilder.clusteredDedicated(clusteredCacheSize, MemoryUnit.MB))) .withExpiry(Expirations.timeToLiveExpiration(new org.ehcache.expiry.Duration(ttl, TimeUnit.SECONDS))) .add(new ClusteredStoreConfiguration(consistency)).build(); Map<String, org.ehcache.config.CacheConfiguration<?, ?>> caches = createCacheConfigurations(cacheConfiguration); EhcacheCachingProvider provider = getCachingProvider(); DefaultConfiguration configuration = new DefaultConfiguration(caches, provider.getDefaultClassLoader(), serverSideConfigurationBuilder.build()); return provider.getCacheManager(provider.getDefaultURI(), configuration); } private Map<String, org.ehcache.config.CacheConfiguration<?, ?>> createCacheConfigurations(org.ehcache.config.CacheConfiguration<Object, Object> cacheConfiguration) { Map<String, org.ehcache.config.CacheConfiguration<?, ?>> caches = new HashMap<>(); caches.put(User.class.getName(), cacheConfiguration); caches.put(Authority.class.getName(), cacheConfiguration); caches.put(User.class.getName() + ".authorities", cacheConfiguration); caches.put(PersistentToken.class.getName(), cacheConfiguration); caches.put(User.class.getName() + ".persistentTokens", cacheConfiguration); caches.put(PersistentAuditEvent.class.getName(), cacheConfiguration); caches.put(Actor.class.getName(), cacheConfiguration); caches.put("weatherReports", cacheConfiguration); return caches; } private EhcacheCachingProvider getCachingProvider() { return (EhcacheCachingProvider) Caching.getCachingProvider(); } }
fullstack/src/main/java/org/terracotta/demo/config/CacheConfiguration.java
package org.terracotta.demo.config; import org.ehcache.clustered.client.config.ClusteredStoreConfiguration; import org.ehcache.clustered.client.config.builders.ClusteredResourcePoolBuilder; import org.ehcache.clustered.client.config.builders.ClusteringServiceConfigurationBuilder; import org.ehcache.clustered.client.config.builders.ServerSideConfigurationBuilder; import org.ehcache.clustered.common.Consistency; import org.ehcache.config.builders.CacheConfigurationBuilder; import org.ehcache.config.builders.ResourcePoolsBuilder; import org.ehcache.config.units.MemoryUnit; import org.ehcache.core.config.DefaultConfiguration; import org.ehcache.expiry.Expirations; import org.ehcache.jsr107.EhcacheCachingProvider; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.autoconfigure.AutoConfigureBefore; import org.springframework.cache.annotation.CachingConfigurerSupport; import org.springframework.cache.annotation.EnableCaching; import org.springframework.cache.jcache.JCacheCacheManager; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.env.Environment; import org.terracotta.demo.domain.Actor; import org.terracotta.demo.domain.Authority; import org.terracotta.demo.domain.PersistentAuditEvent; import org.terracotta.demo.domain.PersistentToken; import org.terracotta.demo.domain.User; import java.net.URI; import java.util.HashMap; import java.util.Map; import java.util.concurrent.TimeUnit; import javax.annotation.PreDestroy; import javax.cache.CacheManager; import javax.cache.Caching; import javax.inject.Inject; @SuppressWarnings("unused") @Configuration @EnableCaching @AutoConfigureBefore(value = { MetricsConfiguration.class, DatabaseConfiguration.class }) public class CacheConfiguration extends CachingConfigurerSupport { private final Logger log = LoggerFactory.getLogger(CacheConfiguration.class); @Inject private Environment env; @Inject private JHipsterProperties properties; private CacheManager cacheManager; @Bean @Override public org.springframework.cache.CacheManager cacheManager() { cacheManager = env.acceptsProfiles(Constants.SPRING_PROFILE_PRODUCTION) ? createClusteredCacheManager() : createInMemoryCacheManager(); return new JCacheCacheManager(cacheManager) { @Override protected org.springframework.cache.Cache getMissingCache(String name) { org.springframework.cache.Cache cache = super.getMissingCache(name); // All caches should be configured. So I throw an exception when one is not found if(cache == null) { throw new IllegalArgumentException("Unknown cache: " + name); } return cache; } }; } @PreDestroy public void destroy() { log.info("Close Cache Manager"); cacheManager.close(); } private CacheManager createInMemoryCacheManager() { long cacheSize = properties.getCache().getEhcache().getSize(); long ttl = properties.getCache().getEhcache().getTimeToLiveSeconds(); org.ehcache.config.CacheConfiguration<Object, Object> cacheConfiguration = CacheConfigurationBuilder .newCacheConfigurationBuilder(Object.class, Object.class, ResourcePoolsBuilder .newResourcePoolsBuilder() .heap(cacheSize)) .withExpiry(Expirations.timeToLiveExpiration(new org.ehcache.expiry.Duration(ttl, TimeUnit.SECONDS))) .build(); Map<String, org.ehcache.config.CacheConfiguration<?, ?>> caches = createCacheConfigurations(cacheConfiguration); EhcacheCachingProvider provider = getCachingProvider(); DefaultConfiguration configuration = new DefaultConfiguration(caches, provider.getDefaultClassLoader()); return provider.getCacheManager(provider.getDefaultURI(), configuration); } private CacheManager createClusteredCacheManager() { JHipsterProperties.Cache.Ehcache.Cluster clusterProperties = properties.getCache().getEhcache().getCluster(); URI clusterUri = clusterProperties.getUri(); boolean autoCreate = clusterProperties.isAutoCreate(); long clusteredCacheSize = clusterProperties.getSizeInMb(); Consistency consistency = clusterProperties.getConsistency(); long heapCacheSize = properties.getCache().getEhcache().getSize(); long ttl = properties.getCache().getEhcache().getTimeToLiveSeconds(); ClusteringServiceConfigurationBuilder clusteringServiceConfigurationBuilder = ClusteringServiceConfigurationBuilder.cluster(clusterUri); ServerSideConfigurationBuilder serverSideConfigurationBuilder = (autoCreate ? clusteringServiceConfigurationBuilder.autoCreate() : clusteringServiceConfigurationBuilder.expecting()) .defaultServerResource("primary-server-resource"); org.ehcache.config.CacheConfiguration<Object, Object> cacheConfiguration = CacheConfigurationBuilder .newCacheConfigurationBuilder(Object.class, Object.class, ResourcePoolsBuilder .newResourcePoolsBuilder() .heap(heapCacheSize) .with(ClusteredResourcePoolBuilder.clusteredDedicated(clusteredCacheSize, MemoryUnit.MB))) .withExpiry(Expirations.timeToLiveExpiration(new org.ehcache.expiry.Duration(ttl, TimeUnit.SECONDS))) .add(new ClusteredStoreConfiguration(consistency)).build(); Map<String, org.ehcache.config.CacheConfiguration<?, ?>> caches = createCacheConfigurations(cacheConfiguration); EhcacheCachingProvider provider = getCachingProvider(); DefaultConfiguration configuration = new DefaultConfiguration(caches, provider.getDefaultClassLoader(), serverSideConfigurationBuilder.build()); return provider.getCacheManager(provider.getDefaultURI(), configuration); } private Map<String, org.ehcache.config.CacheConfiguration<?, ?>> createCacheConfigurations(org.ehcache.config.CacheConfiguration<Object, Object> cacheConfiguration) { Map<String, org.ehcache.config.CacheConfiguration<?, ?>> caches = new HashMap<>(); caches.put(User.class.getName(), cacheConfiguration); caches.put(Authority.class.getName(), cacheConfiguration); caches.put(User.class.getName() + ".authorities", cacheConfiguration); caches.put(PersistentToken.class.getName(), cacheConfiguration); caches.put(User.class.getName() + ".persistentTokens", cacheConfiguration); caches.put(PersistentAuditEvent.class.getName(), cacheConfiguration); caches.put(Actor.class.getName(), cacheConfiguration); caches.put("weatherReports", cacheConfiguration); return caches; } private EhcacheCachingProvider getCachingProvider() { return (EhcacheCachingProvider) Caching.getCachingProvider(); } }
No need to override getMissingCache. An exception is correctly thrown at higher level
fullstack/src/main/java/org/terracotta/demo/config/CacheConfiguration.java
No need to override getMissingCache. An exception is correctly thrown at higher level
Java
apache-2.0
d7c8f78457ea85380377d826f5aa31dba1dcda24
0
cyenyxe/eva-pipeline,jmmut/eva-pipeline,cyenyxe/eva-pipeline,jmmut/eva-pipeline,jmmut/eva-pipeline,cyenyxe/eva-pipeline,EBIvariation/eva-pipeline,EBIvariation/eva-pipeline
/* * Copyright 2017 EMBL - European Bioinformatics Institute * * 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 uk.ac.ebi.eva.utils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import uk.ac.ebi.eva.pipeline.listeners.StepProgressListener; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.Scanner; import java.util.zip.GZIPInputStream; /** * Estimate the number of lines in a VCF file. * <p> * Given that the VCF file could be VERY big then we estimate the number of lines using the following steps: * 1) retrieve the size in bytes of the whole zipped VCF (vcfFileSize) * 2) retrieve the size in bytes of the head of the VCF in a zipped file (vcfHeadFileSize) * 3) retrieve the size in bytes of the first 100 lines of the VCF in a zipped file and divide the value by 100 to * obtain the size of a single line (singleVcfLineSize) * 4) calculate the (vcfFileSize - vcfHeadFileSize) / singleVcfLineSize to estimate the total number of line in the VCF. * <p> * Why 100 in point 3? * Tested on a VCF with 157049 lines, 100 is the best and minimum number of lines to compress. This should generate an * estimated total number of lines similar to the real one. * <p> * In case of small VCF the NUMBER_OF_LINES will be 0 and no % will be printed in {@link StepProgressListener#afterChunk} */ public class VcfNumberOfLinesEstimator { private static final Logger logger = LoggerFactory.getLogger(VcfNumberOfLinesEstimator.class); private static final int NUMBER_OF_LINES = 100; public int estimateVcfNumberOfLines(String vcfFilePath) { logger.debug("Estimating the number of lines in the VCF file {}", vcfFilePath); int estimatedTotalNumberOfLines = 0; String vcfHead; String vcfSection; try { vcfHead = retrieveVcfHead(vcfFilePath); vcfSection = retrieveVcfSection(vcfFilePath); } catch (IOException e) { throw new RuntimeException("Error reading VCF " + vcfFilePath, e); } if (!vcfSection.isEmpty()) { File vcfHeadFile; File vcfSectionFile; try { vcfHeadFile = FileUtils.newGzipFile(vcfHead, "vcfHeadFile"); vcfSectionFile = FileUtils.newGzipFile(vcfSection, "vcfSectionFile"); } catch (IOException e) { throw new RuntimeException("Error while creating zip file", e); } int vcfFileSize = (int) new File(vcfFilePath).length(); int singleVcfLineSize = (int) (vcfSectionFile.length() / NUMBER_OF_LINES); int vcfHeadFileSize = (int) vcfHeadFile.length(); estimatedTotalNumberOfLines = ((vcfFileSize - vcfHeadFileSize) / singleVcfLineSize); } logger.info("Estimated number of lines in VCF file: {}", estimatedTotalNumberOfLines); return estimatedTotalNumberOfLines; } /** * @param vcfFilePath location of the VCF to parse * @return the head of the VCF * @throws IOException */ private String retrieveVcfHead(String vcfFilePath) throws IOException { String vcfHead = ""; Scanner scanner = new Scanner(new GZIPInputStream(new FileInputStream(vcfFilePath))); while (scanner.hasNextLine()) { String line = scanner.nextLine(); if (line.startsWith("#")) { vcfHead += line + "\n"; }else { break; } } scanner.close(); return vcfHead; } /** * @param vcfFilePath location of the VCF to parse * @return first NUMBER_OF_LINES of VCF, empty sting in case of VCF smaller than NUMBER_OF_LINES * @throws IOException */ private String retrieveVcfSection(String vcfFilePath) throws IOException { String vcfSection = ""; int lineCount = NUMBER_OF_LINES; Scanner scanner = new Scanner(new GZIPInputStream(new FileInputStream(vcfFilePath))); while (scanner.hasNextLine()) { String line = scanner.nextLine(); if (!line.startsWith("#")) { lineCount--; vcfSection += line + "\n"; if (lineCount == 0) { break; } } } scanner.close(); //in case of small VCF if (lineCount > 0) { return ""; } return vcfSection; } }
src/main/java/uk/ac/ebi/eva/utils/VcfNumberOfLinesEstimator.java
/* * Copyright 2017 EMBL - European Bioinformatics Institute * * 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 uk.ac.ebi.eva.utils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import uk.ac.ebi.eva.pipeline.listeners.StepProgressListener; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.Scanner; import java.util.zip.GZIPInputStream; /** * Estimate the number of lines in a VCF file. * <p> * Given that the VCF file could be VERY big then we estimate the number of lines using the following steps: * 1) retrieve the size in bytes of the whole zipped VCF (vcfFileSize) * 2) retrieve the size in bytes of the head of the VCF in a zipped file (vcfHeadFileSize) * 3) retrieve the size in bytes of the first 100 lines of the VCF in a zipped file and divide the value by 100 to * obtain the size of a single line (singleVcfLineSize) * 4) calculate the (vcfFileSize - vcfHeadFileSize) / singleVcfLineSize to estimate the total number of line in the VCF. * <p> * Why 100 in point 3? * Tested on a VCF with 157049 lines, 100 is the best and minimum number of lines to compress. This should generate an * estimated total number of lines similar to the real one. * <p> * In case of small VCF the NUMBER_OF_LINES will be 0 and no % will be printed in {@link StepProgressListener#afterChunk} */ public class VcfNumberOfLinesEstimator { private static final Logger logger = LoggerFactory.getLogger(VcfNumberOfLinesEstimator.class); private static final int NUMBER_OF_LINES = 100; public int estimateVcfNumberOfLines(String vcfFilePath) { logger.debug("Estimating the number of lines in the VCF file {}", vcfFilePath); int estimatedTotalNumberOfLines = 0; String vcfHead; String vcfSection; try { vcfHead = retrieveVcfHead(vcfFilePath); vcfSection = retrieveVcfSection(vcfFilePath); } catch (IOException e) { throw new RuntimeException("Error reading VCF " + vcfFilePath, e); } if (!vcfSection.isEmpty()) { File vcfHeadFile; File vcfSectionFile; try { vcfHeadFile = FileUtils.newGzipFile(vcfHead, "vcfHeadFile"); vcfSectionFile = FileUtils.newGzipFile(vcfSection, "vcfSectionFile"); } catch (IOException e) { throw new RuntimeException("Error while creating zip file", e); } double vcfFileSize = new File(vcfFilePath).length(); double singleVcfLineSize = (vcfSectionFile != null ? vcfSectionFile.length() : 0) / NUMBER_OF_LINES; double vcfHeadFileSize = vcfHeadFile != null ? vcfHeadFile.length() : 0; estimatedTotalNumberOfLines = (int) ((vcfFileSize - vcfHeadFileSize) / singleVcfLineSize); } logger.info("Estimated number of lines in VCF file: {}", estimatedTotalNumberOfLines); return estimatedTotalNumberOfLines; } /** * @param vcfFilePath location of the VCF to parse * @return the head of the VCF * @throws IOException */ private String retrieveVcfHead(String vcfFilePath) throws IOException { String vcfHead = ""; Scanner scanner = new Scanner(new GZIPInputStream(new FileInputStream(vcfFilePath))); while (scanner.hasNextLine()) { String line = scanner.nextLine(); if (line.startsWith("#")) { vcfHead += line + "\n"; } } scanner.close(); return vcfHead; } /** * @param vcfFilePath location of the VCF to parse * @return first NUMBER_OF_LINES of VCF, empty sting in case of VCF smaller than NUMBER_OF_LINES * @throws IOException */ private String retrieveVcfSection(String vcfFilePath) throws IOException { String vcfSection = ""; int lineCount = NUMBER_OF_LINES; Scanner scanner = new Scanner(new GZIPInputStream(new FileInputStream(vcfFilePath))); while (scanner.hasNextLine()) { String line = scanner.nextLine(); if (!line.startsWith("#")) { lineCount--; vcfSection += line + "\n"; if (lineCount == 0) { break; } } } scanner.close(); //in case of small VCF if (lineCount > 0) { return ""; } return vcfSection; } }
Using integer to store file size. Added break while retrieving the head to avoid the parsing of the all file.
src/main/java/uk/ac/ebi/eva/utils/VcfNumberOfLinesEstimator.java
Using integer to store file size. Added break while retrieving the head to avoid the parsing of the all file.
Java
apache-2.0
b23e623e689559837e81f0c4ab22bc02d1586374
0
jenetics/jenetics,jenetics/jenetics,jenetics/jenetics,jenetics/jenetics,jenetics/jenetics,jenetics/jenetics,jenetics/jenetics
/* * Java Genetic Algorithm Library (@__identifier__@). * Copyright (c) @__year__@ Franz Wilhelmstötter * * 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. * * Author: * Franz Wilhelmstötter ([email protected]) */ package org.jenetics.example; import org.jenetics.BitChromosome; import org.jenetics.Chromosome; import org.jenetics.DoubleChromosome; import org.jenetics.Genotype; import org.jenetics.IntegerChromosome; import org.jenetics.Phenotype; import org.jenetics.engine.Engine; import org.jenetics.engine.EvolutionResult; @SuppressWarnings({"rawtypes", "unchecked"}) public class MixedGenotype { private static final Genotype ENCODING = Genotype.of( (Chromosome)DoubleChromosome.of(0, 4, 5), (Chromosome)BitChromosome.of(70), (Chromosome)IntegerChromosome.of(0, 10, 3) ); private static double fitness(final Genotype gt) { final DoubleChromosome dc = (DoubleChromosome)gt.getChromosome(0); final BitChromosome bc = (BitChromosome)gt.getChromosome(1); final IntegerChromosome ic = (IntegerChromosome)gt.getChromosome(2); return dc.doubleValue() + bc.bitCount() + ic.doubleValue(); } public static void main(final String[] args) { final Engine engine = Engine .builder(MixedGenotype::fitness, ENCODING) .build(); final Phenotype best = (Phenotype)engine.stream() .limit(10) .collect(EvolutionResult.toBestPhenotype()); System.out.println(best); } }
org.jenetics.example/src/main/java/org/jenetics/example/MixedGenotype.java
/* * Java Genetic Algorithm Library (@__identifier__@). * Copyright (c) @__year__@ Franz Wilhelmstötter * * 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. * * Author: * Franz Wilhelmstötter ([email protected]) */ package org.jenetics.example; import java.util.function.Function; import org.jenetics.BitChromosome; import org.jenetics.Chromosome; import org.jenetics.DoubleChromosome; import org.jenetics.Genotype; import org.jenetics.IntegerChromosome; import org.jenetics.Phenotype; import org.jenetics.engine.Engine; import org.jenetics.engine.EvolutionResult; @SuppressWarnings({"rawtypes", "unchecked"}) public class MixedGenotype { private static final Genotype ENCODING = Genotype.of( (Chromosome)DoubleChromosome.of(0, 4, 5), (Chromosome)BitChromosome.of(70), (Chromosome)IntegerChromosome.of(0, 10, 3) ); private static double fitness(final Genotype gt) { final DoubleChromosome dc = (DoubleChromosome)gt.getChromosome(0); final BitChromosome bc = (BitChromosome)gt.getChromosome(1); final IntegerChromosome ic = (IntegerChromosome)gt.getChromosome(2); return dc.doubleValue() + bc.bitCount() + ic.doubleValue(); } public static void main(final String[] args) { final Engine engine = Engine .builder((Function<Genotype, Double>)MixedGenotype::fitness, ENCODING) .build(); final Phenotype best = (Phenotype)engine.stream() .limit(10) .collect(EvolutionResult.toBestPhenotype()); System.out.println(best); } }
Remove unnecessary cast.
org.jenetics.example/src/main/java/org/jenetics/example/MixedGenotype.java
Remove unnecessary cast.
Java
bsd-2-clause
b4dd3649b44a2e2c7f5a30737fa6691a20bbb4e1
0
siteadmin/CCDA-Score-CARD,monikadrajer/CCDA-Score-CARD,monikadrajer/CCDA-Score-CARD,siteadmin/CCDA-Score-CARD,siteadmin/CCDA-Score-CARD,monikadrajer/CCDA-Score-CARD
package org.sitenv.service.ccda.smartscorecard.controller; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.OutputStream; import java.net.URI; import java.net.URISyntaxException; import java.nio.charset.Charset; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.List; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletResponse; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.apache.commons.io.IOUtils; import org.jsoup.Jsoup; import org.sitenv.ccdaparsing.model.CCDAXmlSnippet; import org.sitenv.service.ccda.smartscorecard.cofiguration.ApplicationConfiguration; import org.sitenv.service.ccda.smartscorecard.model.CCDAScoreCardRubrics; import org.sitenv.service.ccda.smartscorecard.model.Category; import org.sitenv.service.ccda.smartscorecard.model.ReferenceError; import org.sitenv.service.ccda.smartscorecard.model.ReferenceResult; import org.sitenv.service.ccda.smartscorecard.model.ReferenceTypes.ReferenceInstanceType; import org.sitenv.service.ccda.smartscorecard.model.ResponseTO; import org.sitenv.service.ccda.smartscorecard.model.Results; import org.sitenv.service.ccda.smartscorecard.processor.ScorecardProcessor; import org.sitenv.service.ccda.smartscorecard.util.ApplicationConstants; import org.sitenv.service.ccda.smartscorecard.util.ApplicationUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.FileSystemResource; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.http.converter.FormHttpMessageConverter; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.util.LinkedMultiValueMap; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; import org.springframework.web.multipart.MultipartFile; import org.w3c.dom.Document; import org.xhtmlrenderer.pdf.ITextRenderer; import org.xml.sax.SAXException; import com.fasterxml.jackson.databind.ObjectMapper; import com.lowagie.text.DocumentException; @RestController public class SaveReportController { @Autowired private ScorecardProcessor scorecardProcessor; public static final String SAVE_REPORT_CHARSET_NAME = "UTF8"; private static final int CONFORMANCE_ERROR_INDEX = 0; private static final int CERTIFICATION_FEEDBACK_INDEX = 1; private static final boolean LOG_HTML = true; /** * Converts received JSON to a ResponseTO POJO (via method signature * automagically), converts the ResponseTO to a cleaned (parsable) HTML * report including relevant data, converts the HTML to a PDF report, and, * finally, streams the data for consumption. * This is intended to be called from a frontend which has already collected the JSON results. * * @param jsonReportData * JSON which resembles ResponseTO * @param response * used to stream the PDF */ @RequestMapping(value = "/savescorecardservice", method = RequestMethod.POST) public void savescorecardservice(@RequestBody ResponseTO jsonReportData, HttpServletResponse response) { convertHTMLToPDFAndStreamToOutput( ensureLogicalParseTreeInHTML(convertReportToHTML(jsonReportData, SaveReportType.MATCH_UI)), response); } /** * A single service to handle a pure back-end implementation of the * scorecard which streams back a PDF report. * This does not require the completed JSON up-front, it creates it from the file sent. * * @param ccdaFile * The C-CDA XML file intended to be scored */ @RequestMapping(value = "/savescorecardservicebackend", method = RequestMethod.POST) public void savescorecardservicebackend( @RequestParam("ccdaFile") MultipartFile ccdaFile, HttpServletResponse response) { handlePureBackendCall(ccdaFile, response, SaveReportType.MATCH_UI, scorecardProcessor); } /** * A single service to handle a pure back-end implementation of the * scorecard which streams back a PDF report. * This does not require the completed JSON up-front, it creates it from the file sent. * This differs from the savescorecardservicebackend in that it has its own specific format of the results * (dynamic and static table with 'call outs', no filename, more overview type content, etc.) * and is intended to be used when a Direct Message is received with a C-CDA document. * * @param ccdaFile * The C-CDA XML file intended to be scored * @param sender * The email address of the sender to be logged in the report */ @RequestMapping(value = "/savescorecardservicebackendsummary", method = RequestMethod.POST) public void savescorecardservicebackendsummary( @RequestParam("ccdaFile") MultipartFile ccdaFile, @RequestParam("sender") String sender, HttpServletResponse response) { if(ApplicationUtil.isEmpty(sender)) { sender = "Unknown Sender"; } handlePureBackendCall(ccdaFile, response, SaveReportType.SUMMARY, scorecardProcessor, sender); } private static void handlePureBackendCall(MultipartFile ccdaFile, HttpServletResponse response, SaveReportType reportType, ScorecardProcessor scorecardProcessor) { handlePureBackendCall(ccdaFile, response, reportType, scorecardProcessor, "savescorecardservicebackend"); } private static void handlePureBackendCall(MultipartFile ccdaFile, HttpServletResponse response, SaveReportType reportType, ScorecardProcessor scorecardProcessor, String sender) { ResponseTO pojoResponse = callCcdascorecardserviceInternally(ccdaFile, scorecardProcessor, sender, reportType); if (pojoResponse == null) { pojoResponse = new ResponseTO(); pojoResponse.setResults(null); pojoResponse.setSuccess(false); pojoResponse .setErrorMessage(ApplicationConstants.ErrorMessages.NULL_RESULT_ON_SAVESCORECARDSERVICEBACKEND_CALL); } else { if (!ApplicationUtil.isEmpty(ccdaFile.getOriginalFilename()) && ccdaFile.getOriginalFilename().contains(".")) { pojoResponse.setFilename(ccdaFile.getOriginalFilename()); } else if (!ApplicationUtil.isEmpty(ccdaFile.getName()) && ccdaFile.getName().contains(".")) { pojoResponse.setFilename(ccdaFile.getName()); } if(ApplicationUtil.isEmpty(pojoResponse.getFilename())) { pojoResponse.setFilename("Unknown"); } // otherwise it uses the name given by ccdascorecardservice } if(reportType == SaveReportType.SUMMARY) { pojoResponse.setFilename(sender); } convertHTMLToPDFAndStreamToOutput( ensureLogicalParseTreeInHTML(convertReportToHTML(pojoResponse, reportType)), response); }; protected static ResponseTO callCcdascorecardserviceInternally(MultipartFile ccdaFile, ScorecardProcessor scorecardProcessor, String sender, SaveReportType reportType) { return scorecardProcessor.processCCDAFile(ccdaFile, reportType == SaveReportType.SUMMARY, sender); } public static ResponseTO callCcdascorecardserviceExternally(MultipartFile ccdaFile) { String endpoint = ApplicationConfiguration.CCDASCORECARDSERVICE_URL; return callServiceExternally(endpoint, ccdaFile, null); } public static ResponseTO callSavescorecardservicebackendExternally(MultipartFile ccdaFile) { String endpoint = ApplicationConfiguration.SAVESCORECARDSERVICEBACKEND_URL; return callServiceExternally(endpoint, ccdaFile, null); } public static ResponseTO callSavescorecardservicebackendsummaryExternally(MultipartFile ccdaFile, String senderValue) { String endpoint = ApplicationConfiguration.SAVESCORECARDSERVICEBACKENDSUMMARY_URL; return callServiceExternally(endpoint, ccdaFile, senderValue); } private static ResponseTO callServiceExternally(String endpoint, MultipartFile ccdaFile, String senderValue) { ResponseTO pojoResponse = null; LinkedMultiValueMap<String, Object> requestMap = new LinkedMultiValueMap<>(); FileOutputStream out = null; File tempFile = null; try { final String tempCcdaFileName = "ccdaFile"; tempFile = File.createTempFile(tempCcdaFileName, "xml"); out = new FileOutputStream(tempFile); IOUtils.copy(ccdaFile.getInputStream(), out); requestMap.add(tempCcdaFileName, new FileSystemResource(tempFile)); if(senderValue != null) { String senderKey = "sender"; requestMap.add(senderKey, senderValue); } HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.MULTIPART_FORM_DATA); HttpEntity<LinkedMultiValueMap<String, Object>> requestEntity = new HttpEntity<>( requestMap, headers); FormHttpMessageConverter formConverter = new FormHttpMessageConverter(); formConverter.setCharset(Charset.forName(SAVE_REPORT_CHARSET_NAME)); RestTemplate restTemplate = new RestTemplate(); restTemplate.getMessageConverters().add(formConverter); restTemplate.getMessageConverters().add( new MappingJackson2HttpMessageConverter()); pojoResponse = restTemplate.postForObject(endpoint, requestEntity, ResponseTO.class); } catch (Exception e) { e.printStackTrace(); } finally { if (out != null) { try { out.flush(); out.close(); } catch (IOException ioe) { ioe.printStackTrace(); } } if (tempFile != null && tempFile.isFile()) { tempFile.delete(); } } return pojoResponse; } /** * Parses (POJO ResponseTO converted) JSON and builds the results into an * HTML report * * @param report * the ResponseTO report intended to be converted to HTML * @return the converted HTML report as a String */ protected static String convertReportToHTML(ResponseTO report, SaveReportType reportType) { StringBuffer sb = new StringBuffer(); appendOpeningHtml(sb); if (report == null) { report = new ResponseTO(); report.setResults(null); report.setSuccess(false); report.setErrorMessage(ApplicationConstants.ErrorMessages.GENERIC_WITH_CONTACT); appendErrorMessageFromReport(sb, report, ApplicationConstants.ErrorMessages.RESULTS_ARE_NULL); } else { // report != null if (report.getResults() != null) { if (report.isSuccess()) { Results results = report.getResults(); List<Category> categories = results.getCategoryList(); List<ReferenceResult> referenceResults = report .getReferenceResults(); appendHeader(sb, report, results, reportType); appendHorizontalRuleWithBreaks(sb); if(reportType == SaveReportType.SUMMARY) { appendPreTopLevelResultsContent(sb); } appendTopLevelResults(sb, results, categories, referenceResults, reportType, report.getCcdaDocumentType()); if(reportType == SaveReportType.MATCH_UI) { appendHorizontalRuleWithBreaks(sb); appendHeatmap(sb, results, categories, referenceResults); } sb.append("<br />"); appendHorizontalRuleWithBreaks(sb); if(reportType == SaveReportType.MATCH_UI) { if(!ApplicationUtil.isEmpty(report.getReferenceResults()) || results.getNumberOfIssues() > 0) { appendDetailedResults(sb, categories, referenceResults); } } if(reportType == SaveReportType.SUMMARY) { /* appendPictorialGuide(sb, categories, referenceResults); appendPictorialGuideKey(sb); */ } } } else { // report.getResults() == null if (!report.isSuccess()) { appendErrorMessageFromReport(sb, report, null); } else { appendErrorMessageFromReport(sb, report); } } } appendClosingHtml(sb); return sb.toString(); } private static void appendOpeningHtml(StringBuffer sb) { sb.append("<!DOCTYPE html>"); sb.append("<html lang='en' xml:lang='en'>"); sb.append(" <head>"); sb.append(" <title>SITE C-CDA Scorecard Report</title>"); sb.append(" <meta name='author' content='ONC SITE'>"); sb.append(" <meta name='subject' content='ONC Scorecard'>"); sb.append(" <meta name='keywords' content='Scorecard, C-CDA, ONC, R1.1, R2.1, CDA, Report, SITE, " + "Validation, Validator, Standards, HL7, Structured Documents, Healthcare, HIT, HIE, Interoperability'>"); sb.append(" <meta name='language' content='en'>"); appendStyleSheet(sb); sb.append(" </head>"); sb.append("<body style='font-family: \"Helvetica Neue\",Helvetica,Arial,sans-serif;'>"); } private static void appendStyleSheet(StringBuffer sb) { sb.append("<style>" + " .site-header { background: url('https://sitenv.org/assets/images/site/bg-header-1920x170.png') repeat-x center top #1fdbfe; } " + " .site-logo { text-decoration: none; } " + " table { font-family: arial, sans-serif; border-collapse: separate; width: 100%; } " + " td, th { border: 1px solid #dddddd; text-align: left; padding: 8px; } " + " #dynamicTable tr:nth-child(even) { background-color: #dddddd; } " + " #staticTable { font-size: 11px; } " + " .popOuts { font-size: 11px; background-color: ghostwhite !important; } " + " .removeBorder { border: none; background-color: white; } " + " #notScoredRowPopOutLink { border-top: 6px double MAGENTA; border-bottom: none; border-left: none; border-right: none; } " + " #perfectRowPopOutLink { border-top: 6px double MEDIUMPURPLE; border-bottom: none; border-left: none; border-right: none; } " + " #gradePopOutLink { border-left: 6px solid MEDIUMSEAGREEN; border-right: none; border-bottom: none; border-top: none; } " + " #issuePopOutLink { border-left: 6px double orange; border-right: none; border-bottom: none; border-top: none; } " + " #errorPopOutLink { border-right: none; border-left: 6px solid red; border-bottom: none; border-top: none; } " + " #feedbackPopOutLink { border-right: none; border-left: 6px double DEEPSKYBLUE; border-bottom: none; border-top: none; } " + " #notScoredRowPopOut { border: 6px double MAGENTA; border-radius: 0px 25px 25px 25px; } " + " #perfectRowPopOut { border: 6px double MEDIUMPURPLE; border-radius: 25px 0px 25px 25px; } " + " #gradePopOut { border: 6px solid MEDIUMSEAGREEN; border-radius: 25px 25px 25px 25px; } " + " #issuePopOut { border: 6px double orange; border-radius: 25px 25px 25px 0px; } " + " #errorPopOut { border: 6px solid red; border-radius: 25px 25px 25px 0px; } " + " #feedbackPopOut { border: 6px double DEEPSKYBLUE; border-radius: 25px 25px 25px 0px; } " + " #perfectRowLeftHeader { border-left: 6px double MEDIUMPURPLE; border-top: 6px double MEDIUMPURPLE; border-bottom: 6px double MEDIUMPURPLE; } " + " #perfectRowRightHeader { border-right: 6px double MEDIUMPURPLE; border-top: 6px double MEDIUMPURPLE; border-bottom: 6px double MEDIUMPURPLE; } " + " .perfectRowMiddleHeader { border-top: 6px double MEDIUMPURPLE; border-bottom: 6px double MEDIUMPURPLE; } " + " #notScoredRowLeftHeader { border-left: 6px double MAGENTA; border-top: 6px double MAGENTA; border-bottom: 6px double MAGENTA; } " + " #notScoredRowRightHeader { border-right: 6px double MAGENTA; border-top: 6px double MAGENTA; border-bottom: 6px double MAGENTA; } " + " .notScoredRowMiddleHeader { border-top: 6px double MAGENTA; border-bottom: 6px double MAGENTA; } " + " #gradeHeader { border: 6px solid MEDIUMSEAGREEN; } " + " #issueHeader { border: 6px double orange; } " + " #errorHeader { border: 6px solid red; } " + " #feedbackHeader { border: 6px double DEEPSKYBLUE; } " + " #keyGradeHeader { color: MEDIUMSEAGREEN; font-weight: bold; } " + " #keyIssueHeader { color: orange; font-weight: bold; } " + " #keyErrorHeader { color: red; font-weight: bold; } " + " #keyFeedbackHeader { color: DEEPSKYBLUE; font-weight: bold; } " + " </style> "); } private static void appendHeader(StringBuffer sb, ResponseTO report, Results results, SaveReportType reportType) { sb.append("<header id='topOfScorecard'>"); sb.append("<center>"); sb.append("<div class=\"site-header\">") .append(" <a class=\"site-logo\" href=\"https://www.healthit.gov/\"") .append(" rel=\"external\" title=\"HealthIT.gov\"> <img alt=\"HealthIT.gov\"") .append(" src=\"https://sitenv.org/assets/images/site/healthit.gov.logo.png\" width='40%'>") .append(" </a>") .append("</div>"); sb.append("<br />"); appendHorizontalRuleWithBreaks(sb); sb.append("<h1>" + "C-CDA "); if(reportType == SaveReportType.SUMMARY) { sb.append("Scorecard For " + (report.getCcdaDocumentType() != null ? report .getCcdaDocumentType() : "document") + "</h1>"); sb.append("<h5>"); sb.append("<span style='float: left'>" + "Submitted By: " + (!ApplicationUtil.isEmpty(report.getFilename()) ? report.getFilename() : "Unknown") + "</span>"); DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss"); sb.append("<span style='float: right'>" + "Submission Time: " + dateFormat.format(new Date()) + "</span>"); sb.append("</h5>"); sb.append("<div style='clear: both'></div>"); appendBasicResults(sb, results); } else { sb.append(results.getCcdaVersion() + " " + (report.getCcdaDocumentType() != null ? report .getCcdaDocumentType() : "document") + " Scorecard For:" + "</h1>"); sb.append("<h2>" + report.getFilename() + "</h2>"); } sb.append("</center>"); sb.append("</header>"); } private static void appendPreTopLevelResultsContent(StringBuffer sb) { /* sb.append("<p>") .append(" The C-CDA Scorecard enables providers, implementers, and health") .append(" IT professionals with a tool that compares how artifacts (transition") .append(" of care documents, care plans etc) created by your organization") .append(" stack up against the HL7 C-CDA implementation guide and HL7 best") .append(" practices. The C-CDA Scorecard promotes best practices in C-CDA") .append(" implementation by assessing key aspects of the structured data found") .append(" in individual documents. The Scorecard tool provides a rough") .append(" quantitative assessment and highlights areas of improvement which") .append(" can be made today to move the needle forward in interoperability of") .append(" C-CDA documents. The ") .append(" <a href=\"http://www.hl7.org/documentcenter/public/wg/structure/C-CDA%20Scorecard%20Rubrics%203.pptx\">" + "best practices and quantitative scoring criteria" + "</a>") .append(" have been developed by HL7 through the HL7-ONC Cooperative agreement") .append(" to improve the implementation of health care standards. We hope that") .append(" providers and health IT developers will use the tool to identify and") .append(" resolve issues around C-CDA document interoperability in their") .append(" health IT systems.") .append("</p>") */ sb.append("<p>If you are not satisfied with your results:</p>"); sb.append("<ul>"); sb.append("<li>"); sb.append("Please ask your vendor to submit the document to the SITE C-CDA Scorecard website " + " at " + "<a href=\"https://healthit.gov/scorecard/\">" + "www.healthit.gov/scorecard" + "</a>" + " for more detailed information"); sb.append("</li>"); sb.append("<li>"); sb.append("Using the results provided by the online tool, " + "your vendor can update or provide insight on how to update your document to meet the latest HL7 best-practices"); sb.append("</li>"); sb.append("<li>"); sb.append("Once updated, " + "resubmitting your document to the ONC One Click Scorecard will produce a report with a higher score " + "and/or less or no conformance errors or less or no certification feedback results"); sb.append("</li>"); sb.append("</ul>"); sb.append("<p>") .append("This page contains a summary of the C-CDA Scorecard results highlighting the overall document grade " + "which is derived from a quantitative score out of a maximum of 100. ") .append("</p>"); sb.append("<p>") .append("The second and final page identifies areas for improvement organized by clinical domains.") .append("</p>"); } private static void appendBasicResults(StringBuffer sb, Results results) { sb.append("<center>"); sb.append("<h2>"); sb.append("<span style=\"margin-right: 40px\">Grade: " + results.getFinalGrade() + "</span>"); sb.append("<span style=\"margin-left: 40px\">Score: " + results.getFinalNumericalGrade() + "/100" + "</span>"); sb.append("</h2>"); sb.append("</center>"); } private static void appendTopLevelResults(StringBuffer sb, Results results, List<Category> categories, List<ReferenceResult> referenceResults, SaveReportType reportType, String ccdaDocumentType) { boolean isReferenceResultsEmpty = ApplicationUtil.isEmpty(referenceResults); int conformanceErrorCount = isReferenceResultsEmpty ? 0 : referenceResults.get(CONFORMANCE_ERROR_INDEX).getTotalErrorCount(); int certificationFeedbackCount = isReferenceResultsEmpty ? 0 : referenceResults.get(CERTIFICATION_FEEDBACK_INDEX).getTotalErrorCount(); if(reportType == SaveReportType.SUMMARY) { //brief summary of overall document results (without scorecard issues count listed) sb.append("<h3>Summary</h3>"); sb.append("<p>" + "Your " + ccdaDocumentType + " document received a grade of <b>" + results.getFinalGrade() + "</b>" + " compared to an industry average of " + "<b>" + results.getIndustryAverageGradeForCcdaDocumentType() + "</b>" + ". " + "The industry average, specific to the document type sent, was computed by scoring " + results.getNumberOfDocsScoredPerCcdaDocumentType() + " " + ccdaDocumentType + (results.getNumberOfDocsScoredPerCcdaDocumentType() > 1 ? "s" : "" ) + ". " + "The document scored " + "<b>" + results.getFinalNumericalGrade() + "/100" + "</b>" + " and is " + (conformanceErrorCount > 0 ? "non-compliant" : "compliant") + " with the HL7 C-CDA IG" + " and is " + (certificationFeedbackCount > 0 ? "non-compliant" : "compliant") + " with 2015 Edition Certification requirements. " + "The detailed results organized by clinical domains are provided in the table below:" + "</p>"); //dynamic table appendHorizontalRuleWithBreaks(sb); sb.append("<br /><br />"); sb.append("<h2>Scorecard Results by Clinical Domain</h2>"); appendDynamicTopLevelResultsTable(sb, results, categories, referenceResults); } else { sb.append("<h3>Scorecard Grade: " + results.getFinalGrade() + "</h3>"); sb.append("<ul><li>"); sb.append("<p>Your document scored a " + "<b>" + results.getFinalGrade() + "</b>" + " compared to an industry average of " + "<b>" + results.getIndustryAverageGrade() + "</b>" + ".</p>"); sb.append("</ul></li>"); sb.append("<h3>Scorecard Score: " + results.getFinalNumericalGrade() + "</h3>"); sb.append("<ul><li>"); sb.append("<p>Your document scored " + "<b>" + +results.getFinalNumericalGrade() + "</b>" + " out of " + "<b>" + " 100 " + "</b>" + " total possible points.</p>"); sb.append("</ul></li>"); boolean isSingular = results.getNumberOfIssues() == 1; appendSummaryRow(sb, results.getNumberOfIssues(), "Scorecard Issues", null, isSingular ? "Scorecard Issue" : "Scorecard Issues", isSingular); sb.append("</ul></li>"); String messageSuffix = null; if (isReferenceResultsEmpty) { for (ReferenceInstanceType refType : ReferenceInstanceType.values()) { if (refType == ReferenceInstanceType.CERTIFICATION_2015) { messageSuffix = "results"; } appendSummaryRow(sb, 0, refType.getTypePrettyName(), messageSuffix, refType.getTypePrettyName(), false, reportType); sb.append("</ul></li>"); } } else { for (ReferenceResult refResult : referenceResults) { int refErrorCount = refResult.getTotalErrorCount(); isSingular = refErrorCount == 1; String refTypeName = refResult.getType().getTypePrettyName(); String messageSubject = ""; if (refResult.getType() == ReferenceInstanceType.IG_CONFORMANCE) { messageSubject = isSingular ? refTypeName.substring(0, refTypeName.length() - 1) : refTypeName; } else if (refResult.getType() == ReferenceInstanceType.CERTIFICATION_2015) { messageSuffix = isSingular ? "result" : "results"; messageSubject = refTypeName; } appendSummaryRow(sb, refErrorCount, refTypeName, messageSuffix, messageSubject, isSingular, reportType); sb.append("</ul></li>"); } } } } private static int getFailingSectionSpecificErrorCount(String categoryName, ReferenceInstanceType refType, List<ReferenceResult> referenceResults) { if (!ApplicationUtil.isEmpty(referenceResults)) { if (refType == ReferenceInstanceType.IG_CONFORMANCE) { List<ReferenceError> igErrors = referenceResults.get(CONFORMANCE_ERROR_INDEX).getReferenceErrors(); if (!ApplicationUtil.isEmpty(igErrors)) { return getFailingSectionSpecificErrorCountProcessor(categoryName, igErrors); } } else if (refType == ReferenceInstanceType.CERTIFICATION_2015) { List<ReferenceError> certErrors = referenceResults.get(CERTIFICATION_FEEDBACK_INDEX).getReferenceErrors(); if (!ApplicationUtil.isEmpty(certErrors)) { return getFailingSectionSpecificErrorCountProcessor(categoryName, certErrors); } } } return 0; } private static int getFailingSectionSpecificErrorCountProcessor( String categoryName, List<ReferenceError> errors) { int count = 0; for (int i = 0; i < errors.size(); i++) { String currentSectionInReferenceErrors = errors.get(i).getSectionName(); if (!ApplicationUtil.isEmpty(currentSectionInReferenceErrors)) { if (currentSectionInReferenceErrors.equalsIgnoreCase(categoryName)) { count++; } } } return count; } private static void appendDynamicTopLevelResultsTable(StringBuffer sb, Results results, List<Category> categories, List<ReferenceResult> referenceResults) { sb.append("<table id='dynamicTable'>"); sb.append(" <tbody>"); sb.append(" <tr class=\"popOuts\">"); sb.append(" <td id=\"gradePopOut\" colspan=\"2\">"); sb.append(" The Scorecard grade is a quantitative assessment of the data quality of the submitted document. " + "A higher grade indicates that HL7 best practices for C-CDA implementation are being followed by the organization and " + "has higher probability of being interoperable with other organizations."); sb.append(" </td>"); sb.append(" <td id=\"issuePopOut\">"); sb.append(" A Scorecard Issue identifies data within the document which can be represented in a better way using " + "HL7 best practices for C-CDA. This column should have numbers as close to zero as possible."); sb.append(" </td>"); sb.append(" <td id=\"errorPopOut\">"); sb.append(" A Conformance Error implies that the document is non-compliant with the HL7 C-CDA IG requirements. " + "This column should have zeros ideally. Providers should work with their health IT vendor to rectify the errors."); sb.append(" </td>"); sb.append(" <td id=\"feedbackPopOut\">"); sb.append(" A Certification Feedback result identifies areas where the generated documents are not compliant with " + "the requirements of 2015 Edition Certification. Ideally, this column should have all zeros."); sb.append(" </td>"); sb.append(" </tr>"); sb.append(" <tr>"); sb.append(" <td class=\"removeBorder\"></td>"); sb.append(" <td class=\"removeBorder\" id=\"gradePopOutLink\"></td>"); sb.append(" <td class=\"removeBorder\" id=\"issuePopOutLink\"></td>"); sb.append(" <td class=\"removeBorder\" id=\"errorPopOutLink\"></td>"); sb.append(" <td class=\"removeBorder\" id=\"feedbackPopOutLink\"></td>"); sb.append(" </tr> "); sb.append(" <tr style=\"background-color: ghostwhite\">"); sb.append(" <th>Clinical Domain</th> "); sb.append(" <th id=\"gradeHeader\">Scorecard Grade</th> "); sb.append(" <th id=\"issueHeader\">Scorecard Issues</th> "); sb.append(" <th id=\"errorHeader\">Conformance Errors</th> "); sb.append(" <th id=\"feedbackHeader\">Certification Feedback</th> "); sb.append(" </tr> "); for(Category category : getSortedCategories(categories)) { // if(category.getNumberOfIssues() > 0 || referenceResults.get(ReferenceInstanceType.IG/CERT).getTotalErrorCount() > 0) { // if(category.getNumberOfIssues() > 0 || category.isFailingConformance() || category.isCertificationFeedback()) { sb.append(" <tr>") .append(" <td>" + (category.getCategoryName() != null ? category.getCategoryName() : "Unknown") + "</td>") .append(" <td>" + (category.getCategoryGrade() != null ? category.getCategoryGrade() : "N/A") + "</td>") .append(" <td>" + (category.isFailingConformance() || category.isCertificationFeedback() || category.isNullFlavorNI() ? "N/A" : category.getNumberOfIssues()) + "</td>") .append(" <td>" + (!ApplicationUtil.isEmpty(category.getCategoryName()) ? getFailingSectionSpecificErrorCount(category.getCategoryName(), ReferenceInstanceType.IG_CONFORMANCE, referenceResults) : "N/A") + "</td>") .append(" <td>" + (!ApplicationUtil.isEmpty(category.getCategoryName()) ? getFailingSectionSpecificErrorCount(category.getCategoryName(), ReferenceInstanceType.CERTIFICATION_2015, referenceResults) : "N/A") + "</td>") .append(" </tr>"); // } } sb.append(" <tbody>"); sb.append("</table>"); } /** * Order from best to worst:<br/> * 1. Numerical score high to low 2. Empty/null 3. Certification Feedback 4. Conformance Error * @param categories - Category List to sort * @return sorted categories */ private static List<Category> getSortedCategories(List<Category> categories) { List<Category> sortedCategories = new ArrayList<Category>(categories); //prepare for sort of non-scored items for(Category category : sortedCategories) { if(category.isFailingConformance()) { category.setCategoryNumericalScore(-3); } else if(category.isCertificationFeedback()) { category.setCategoryNumericalScore(-2); } else if(category.isNullFlavorNI()) { category.setCategoryNumericalScore(-1); } } //sorts by numerical score via Comparable implementation in Category Collections.sort(sortedCategories, Collections.reverseOrder()); return sortedCategories; } private static void appendHeatmap(StringBuffer sb, Results results, List<Category> categories, List<ReferenceResult> referenceResults) { sb.append("<span id='heatMap'>" + "</span>"); for (Category curCategory : getSortedCategories(categories)) { sb.append("<h3>" + (curCategory.getNumberOfIssues() > 0 ? "<a href='#" + curCategory.getCategoryName() + "-category" + "'>" : "") + curCategory.getCategoryName() + (curCategory.getNumberOfIssues() > 0 ? "</a>" : "") + "</h3>"); sb.append("<ul>"); if (curCategory.getCategoryGrade() != null) { sb.append("<li>" + "Section Grade: " + "<b>" + curCategory.getCategoryGrade() + "</b>" + "</li>" + "<li>" + "Number of Issues: " + "<b>" + curCategory.getNumberOfIssues() + "</b>" + "</li>"); } else { sb.append("<li>" + "This category was not scored as it "); if(curCategory.isNullFlavorNI()) { sb.append("is an <b>empty section</b>"); } boolean failingConformance = curCategory.isFailingConformance(); boolean failingCertification = curCategory.isCertificationFeedback(); if(failingConformance || failingCertification) { boolean isCategoryNameValid = !ApplicationUtil.isEmpty(curCategory.getCategoryName()); if(failingConformance && failingCertification || failingConformance && !failingCertification) { //we default to IG if true for both since IG is considered a more serious issue (same with the heatmap label, so we match that) //there could be a duplicate for two reasons, right now, there's always at least one duplicate since we derive ig from cert in the backend //in the future this might not be the case, but, there could be multiple section fails in the same section, so we have a default for those too int igErrorCount = isCategoryNameValid ? getFailingSectionSpecificErrorCount(curCategory.getCategoryName(), ReferenceInstanceType.IG_CONFORMANCE, referenceResults) : -1; sb.append("contains" + (isCategoryNameValid ? " <b>" + igErrorCount + "</b> " : "") + "<a href='#" + ReferenceInstanceType.IG_CONFORMANCE.getTypePrettyName() + "-category'" + ">" + "Conformance Error" + (igErrorCount != 1 ? "s" : "") + "</a>"); } else if(failingCertification && !failingConformance) { int certFeedbackCount = isCategoryNameValid ? getFailingSectionSpecificErrorCount(curCategory.getCategoryName(), ReferenceInstanceType.CERTIFICATION_2015, referenceResults) : -1; sb.append("contains" + (isCategoryNameValid ? " <b>" + certFeedbackCount + "</b> " : "") + "<a href='#" + ReferenceInstanceType.CERTIFICATION_2015.getTypePrettyName() + "-category'" + ">" + "Certification Feedback" + "</a>" + " result" + (certFeedbackCount != 1 ? "s" : "")); } } sb.append("</li>"); } sb.append("</ul></li>"); } } private static void appendSummaryRow(StringBuffer sb, int result, String header, String messageSuffix, String messageSubject, boolean isSingular) { appendSummaryRow(sb, result, header, messageSuffix, messageSubject, isSingular, null); } private static void appendSummaryRow(StringBuffer sb, int result, String header, String messageSuffix, String messageSubject, boolean isSingular, SaveReportType reportType) { if(reportType == null) { reportType = SaveReportType.MATCH_UI; } sb.append("<h3>" + header + ": " + ("Scorecard Issues".equals(header) || result < 1 || reportType == SaveReportType.SUMMARY ? result : ("<a href=\"#" + header + "-category\">" + result + "</a>")) + "</h3>"); sb.append("<ul><li>"); sb.append("<p>There " + (isSingular ? "is" : "are") + " " + "<b>" + result + "</b>" + " " + messageSubject + (messageSuffix != null ? " " + messageSuffix : "") + " in your document.</p>"); } private static void appendDetailedResults(StringBuffer sb, List<Category> categories, List<ReferenceResult> referenceResults) { sb.append("<h2>" + "Detailed Results" + "</h2>"); if (!ApplicationUtil.isEmpty(referenceResults)) { for (ReferenceResult curRefInstance : referenceResults) { ReferenceInstanceType refType = curRefInstance.getType(); if (curRefInstance.getTotalErrorCount() > 0) { String refTypeName = refType.getTypePrettyName(); sb.append("<h3 id=\"" + refTypeName + "-category\">" + refTypeName + "</h3>"); sb.append("<ul>"); // START curRefInstance ul sb.append("<li>" + "Number of " + (refType == ReferenceInstanceType.CERTIFICATION_2015 ? "Results:" : "Errors:") + " " + curRefInstance.getTotalErrorCount() + "</li>"); sb.append("<ol>"); // START reference errors ol for (ReferenceError curRefError : curRefInstance .getReferenceErrors()) { sb.append("<li>" + (refType == ReferenceInstanceType.CERTIFICATION_2015 ? "Feedback:" : "Error:") + " " + curRefError.getDescription() + "</li>"); sb.append("<ul>"); // START ul within the curRefError if (!ApplicationUtil.isEmpty(curRefError .getSectionName())) { sb.append("<li>" + "Related Section: " + curRefError.getSectionName() + "</li>"); } sb.append("<li>" + "Document Line Number (approximate): " + curRefError.getDocumentLineNumber() + "</li>"); sb.append("<li>" + "xPath: " + "<xmp style='font-family: Consolas, monaco, monospace;'>" + curRefError.getxPath() + "</xmp>" + "</li>"); sb.append("</ul>"); // END ul within the curRefError } } sb.append("</ol>"); // END reference errors ol sb.append("</ul>"); // END curRefInstance ul appendBackToTopWithBreaks(sb); } //END for (ReferenceResult curRefInstance : referenceResults) } for (Category curCategory : getSortedCategories(categories)) { if (curCategory.getNumberOfIssues() > 0) { sb.append("<h3 id='" + curCategory.getCategoryName() + "-category" + "'>" + curCategory.getCategoryName() + "</h3>"); sb.append("<ul>"); // START curCategory ul sb.append("<li>" + "Section Grade: " + curCategory.getCategoryGrade() + "</li>" + "<li>" + "Number of Issues: " + curCategory.getNumberOfIssues() + "</li>"); sb.append("<ol>"); // START rules ol for (CCDAScoreCardRubrics curRubric : curCategory .getCategoryRubrics()) { if (curRubric.getNumberOfIssues() > 0) { sb.append("<li>" + "Rule: " + curRubric.getRule() + "</li>"); if (curRubric.getDescription() != null) { sb.append("<ul>" + "<li>" + "Description" + "</li>" + "<ul>" + "<li>" + curRubric.getDescription() + "</li>" + "</ul>" + "</ul>"); sb.append("<br />"); sb.append("<ol>"); // START snippets ol for (CCDAXmlSnippet curSnippet : curRubric .getIssuesList()) { sb.append("<li>" + "XML at line number " + curSnippet.getLineNumber() + "</li>" + "<br /><xmp style='font-family: Consolas, monaco, monospace;'>" + curSnippet.getXmlString() + "</xmp><br /><br />"); } sb.append("</ol>"); // END snippets ol } } else { // don't display rules without occurrences sb.append("</ol>"); } } sb.append("</ol>"); // END rules ol sb.append("</ul>"); // END curCategory ul appendBackToTopWithBreaks(sb); } //END if (curCategory.getNumberOfIssues() > 0) } //END for (Category curCategory : categories) } private static void appendPictorialGuide(StringBuffer sb, List<Category> categories, List<ReferenceResult> referenceResults) { //minimum breaks based on 11 categories sb.append("<br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />"); sb.append("<h2>" + "Guide to Interpret the Scorecard Results Table" + "</h2>"); sb.append("<p>" + "The following sample table identifies how to use the C-CDA Scorecard results " + "to improve the C-CDA documents generated by your organization. " + "Note: The table below is an example containing fictitious results " + "and does not reflect C-CDAs generated by your organization." + "</p>"); //static table sb.append("<table id=\"staticTable\">") .append(" <tbody>") .append(" <tr>") .append(" <td class=\"removeBorder\"></td>") .append(" <td class=\"removeBorder\"></td>") .append(" <td class=\"removeBorder\"></td>") .append(" <td class=\"removeBorder\"></td>") .append(" <td id=\"issuePopOut\" rowspan=\"2\">A Scorecard Issue identifies data within the document which can be represented in a better way using HL7 best practices for C-CDA. This column should have numbers as close to zero as possible.</td>") .append(" <td class=\"removeBorder\"></td>") .append(" <td class=\"removeBorder\"></td>") .append(" <td class=\"removeBorder\"></td>") .append(" <td class=\"removeBorder\"></td>") .append(" </tr>") .append(" <tr>") .append(" <td class=\"removeBorder\"></td>") .append(" <td class=\"removeBorder\"></td>") .append(" <td id=\"gradePopOut\" colspan=\"2\">The Scorecard grade is a quantitative assessment of the data quality of the submitted document. A higher grade indicates that HL7 best practices for C-CDA implementation are being followed by the organization and has higher probability of being interoperable") .append(" with other organizations.</td>") .append(" <td id=\"errorPopOut\" colspan=\"2\">A Conformance Error implies that the document is non-compliant with the HL7 C-CDA IG requirements. This column should have zeros ideally. Providers should work with their health IT vendor to rectify the errors.</td>") .append(" <td class=\"removeBorder\"></td>") .append(" <td class=\"removeBorder\"></td>") .append(" </tr>") .append(" <tr>") .append(" <td class=\"removeBorder\"></td>") .append(" <td class=\"removeBorder\"></td>") .append(" <td class=\"removeBorder\"></td>") .append(" <td id=\"gradePopOutLink\"></td>") .append(" <td id=\"issuePopOutLink\"></td>") .append(" <td id=\"errorPopOutLink\"></td>") .append(" <td class=\"removeBorder\"></td>") .append(" <td class=\"removeBorder\"></td>") .append(" <td class=\"removeBorder\"></td>") .append(" </tr>") .append(" <tr>") .append(" <td class=\"removeBorder\"></td>") .append(" <td class=\"removeBorder\"></td>") .append(" <th>Clinical Domain</th>") .append(" <th id=\"gradeHeader\">Scorecard Grade</th>") .append(" <th id=\"issueHeader\">Scorecard Issues</th>") .append(" <th id=\"errorHeader\">Conformance Errors</th>") .append(" <th id=\"feedbackHeader\">Certification Feedback</th>") .append(" <td id=\"feedbackPopOutLink\"></td>") .append(" <td id=\"feedbackPopOut\" rowspan=\"5\">A Certification Feedback result identifies areas where the generated documents are not compliant with the requirements of 2015 Edition Certification. Ideally, this column should have all zeros.</td>") .append(" </tr>") .append(" <tr>") .append(" <td id=\"perfectRowPopOut\" rowspan=\"4\">The Problems row in this example has an A+ grade and all zeros across the board. This is the most desirable outcome for a Clinical Domain result set.</td>") .append(" <td id=\"perfectRowPopOutLink\"></td>") .append(" <td id=\"perfectRowLeftHeader\">Problems</td>") .append(" <td class=\"perfectRowMiddleHeader\">A+</td>") .append(" <td class=\"perfectRowMiddleHeader\">0</td>") .append(" <td class=\"perfectRowMiddleHeader\">0</td>") .append(" <td id=\"perfectRowRightHeader\">0</td>") .append(" <td class=\"removeBorder\"></td>") .append(" </tr>") .append(" <tr>") .append(" <td class=\"removeBorder\"></td>") .append(" <td>Lab Results</td>") .append(" <td>A-</td>") .append(" <td>2</td>") .append(" <td>0</td>") .append(" <td>0</td>") .append(" <td class=\"removeBorder\"></td>") .append(" </tr>") .append(" <tr>") .append(" <td class=\"removeBorder\"></td>") .append(" <td>Vital Signs</td>") .append(" <td>A-</td>") .append(" <td>1</td>") .append(" <td>0</td>") .append(" <td>0</td>") .append(" <td class=\"removeBorder\"></td>") .append(" </tr>") .append(" <tr>") .append(" <td class=\"removeBorder\"></td>") .append(" <td>Encounters</td>") .append(" <td>D</td>") .append(" <td>12</td>") .append(" <td>0</td>") .append(" <td>0</td>") .append(" <td class=\"removeBorder\"></td>") .append(" <td class=\"removeBorder\"></td>") .append(" </tr>") .append(" <tr>") .append(" <td class=\"removeBorder\"></td>") .append(" <td class=\"removeBorder\"></td>") .append(" <td id=\"notScoredRowLeftHeader\">Medications</td>") .append(" <td class=\"notScoredRowMiddleHeader\">N/A</td>") .append(" <td class=\"notScoredRowMiddleHeader\">N/A</td>") .append(" <td class=\"notScoredRowMiddleHeader\">2</td>") .append(" <td id=\"notScoredRowRightHeader\">0</td>") .append(" <td id=\"notScoredRowPopOutLink\"></td>") .append(" <td id=\"notScoredRowPopOut\" rowspan=\"3\">This domain was not scored because the document did not have data pertaining to the clinical domain or there were conformance errors or certification results.</td>") .append(" </tr>") .append(" <tr>") .append(" <td class=\"removeBorder\"></td>") .append(" <td class=\"removeBorder\"></td>") .append(" <td>Allergies</td>") .append(" <td>N/A</td>") .append(" <td>N/A</td>") .append(" <td>0</td>") .append(" <td>4</td>") .append(" <td class=\"removeBorder\"></td>") .append(" <td class=\"removeBorder\"></td>") .append(" </tr>") .append(" <tr>") .append(" <td class=\"removeBorder\"></td>") .append(" <td class=\"removeBorder\"></td>") .append(" <td>Immunizations</td>") .append(" <td>N/A</td>") .append(" <td>N/A</td>") .append(" <td>0</td>") .append(" <td>0</td>") .append(" <td class=\"removeBorder\"></td>") .append(" <td class=\"removeBorder\"></td>") .append(" </tr>") .append(" </tbody>") .append("</table>"); } private static void appendPictorialGuideKey(StringBuffer sb) { sb.append("<h3>Additional Guidance to Interpret the Scorecard Results and Achieve Higher Grades</h3>") .append("<p>") .append(" <span id=\"keyGradeHeader\">Scorecard Grade: </span>") .append("The Scorecard grade is a quantitative assessment of the data quality of the submitted document. " + "A higher grade indicates that HL7 best practices for C-CDA implementation are being followed by the organization " + "and has higher probability of being interoperable with other organizations. " + "The grades are derived from the scores as follows: " + "A+ ( > 94), A- ( 90 to 94), B+ (85 to 89), B- (80 to 84), C (70 to 79) and D (< 70).") .append("</p>") .append("<p>") .append(" <span id=\"keyIssueHeader\">Scorecard Issues: </span>") .append("A Scorecard Issue identifies data within the document which can be represented in a better way using HL7 best practices for C-CDA. " + "This column should have numbers as close to zero as possible. " + "The issues are counted for each occurrence of unimplemented best practice. " + "For example, if a Vital Sign measurement is not using the appropriate UCUM units then each such occurrence would be flagged " + "as an issue. A provider should work with their health IT vendor to better understand the source for why a best practice " + "may not be implemented and then determine if it can be implemented in the future. Note: Scorecard Issues will be listed as " + "'N/A' for a clinical domain, when there is no data for the domain or if there are conformance or certification feedback results.") .append("</p>") .append("<p>") .append(" <span id=\"keyErrorHeader\">Conformance Errors: </span>") .append("A Conformance Error implies that the document is non-compliant with the HL7 C-CDA IG requirements. " + "This column should have zeros ideally. " + "Providers should work with their health IT vendor to rectify the errors.") .append("</p>") .append("<p>") .append(" <span id=\"keyFeedbackHeader\">Certification Feedback: </span>") .append("A Certification Feedback result identifies areas where the generated documents are not compliant with " + "the requirements of 2015 Edition Certification. Ideally, this column should have all zeros." + "Most of these results fall into incorrect use of vocabularies and terminologies. " + "Although not as severe as a Conformance Error, providers should work with their health IT vendor " + "to address feedback provided to improve interoperable use of structured data between systems.") .append("</p>"); } private static void appendClosingHtml(StringBuffer sb) { sb.append("</body>"); sb.append("</html>"); } private static void appendHorizontalRuleWithBreaks(StringBuffer sb) { sb.append("<br />"); sb.append("<hr />"); sb.append("<br />"); } private static void appendBackToTopWithBreaks(StringBuffer sb) { // sb.append("<br />"); sb.append("<a href='#topOfScorecard'>Back to Top</a>"); // sb.append("<br />"); // A PDF conversion bug is not processing this valid HTML so commenting // out until time to address // sb.append("<a href='#heatMap'>Back to Section List</a>"); sb.append("<br />"); // sb.append("<br />"); } private static void appendErrorMessage(StringBuffer sb, String errorMessage) { sb.append("<h2 style='color:red; background-color: #ffe6e6'>"); sb.append(errorMessage); sb.append("</h2>"); if(!errorMessage.contains("HL7 CDA Schema Errors")) { sb.append("<p>" + ApplicationConstants.ErrorMessages.CONTACT + "</p>"); } } private static void appendGenericErrorMessage(StringBuffer sb) { sb.append("<p>" + ApplicationConstants.ErrorMessages.JSON_TO_JAVA_JACKSON + "<br />" + ApplicationConstants.ErrorMessages.CONTACT + "</p>"); } private static void appendErrorMessageFromReport(StringBuffer sb, ResponseTO report) { appendErrorMessageFromReport(sb, report, null); } private static void appendErrorMessageFromReport(StringBuffer sb, ResponseTO report, String extraMessage) { if (report.getErrorMessage() != null && !report.getErrorMessage().isEmpty()) { boolean hasSchemaErrors = report.getSchemaErrorList() != null && !report.getSchemaErrorList().isEmpty(); if(!hasSchemaErrors) { appendErrorMessage(sb, report.getErrorMessage()); } else { sb.append("<h3>" + ApplicationConstants.ErrorMessages.ONE_CLICK_SCHEMA_MESSAGE_PART1 + "</h3>"); sb.append("<h3>" + ApplicationConstants.ErrorMessages.ONE_CLICK_SCHEMA_MESSAGE_PART2 + "</h3>"); final String noData = "No data available"; sb.append("<ol style='color:red'>"); for(ReferenceError schemaError : report.getSchemaErrorList()) { sb.append("<li>"); sb.append("<ul>"); sb.append("<li>Message: " + (schemaError.getDescription() != null ? schemaError.getDescription() : noData)); sb.append("</li>"); sb.append("<li>Path: " + (schemaError.getxPath() != null ? schemaError.getxPath() : noData)); sb.append("</li>"); sb.append("<li>Line Number (approximate): " + (schemaError.getDocumentLineNumber() != null ? schemaError.getDocumentLineNumber() : noData)); sb.append("</li>"); sb.append("<li>xPath: " + "<xmp style='font-family: Consolas, monaco, monospace;'>" + (schemaError.getxPath() != null ? schemaError.getxPath() : noData) + "</xmp>"); sb.append("<p></p>"); sb.append("</li>"); sb.append("</ul>"); sb.append("</li>"); } sb.append("</ol>"); } } else { appendGenericErrorMessage(sb); } if (extraMessage != null && !extraMessage.isEmpty()) { sb.append("<p>" + extraMessage + "</p>"); } } protected static String ensureLogicalParseTreeInHTML(String htmlReport) { org.jsoup.nodes.Document doc = Jsoup.parse(htmlReport); String cleanHtmlReport = doc.toString(); return cleanHtmlReport; } private static void convertHTMLToPDF(String cleanHtmlReport) { convertHTMLToPDF(cleanHtmlReport, null); } private static void convertHTMLToPDF(String cleanHtmlReport, HttpServletResponse response) { OutputStream out = null; try { DocumentBuilderFactory factory = DocumentBuilderFactory .newInstance(); factory.setNamespaceAware(false); factory.setValidating(false); DocumentBuilder builder = factory.newDocumentBuilder(); Document refinedDoc = builder.parse(new ByteArrayInputStream( cleanHtmlReport.getBytes("UTF-8"))); ITextRenderer renderer = new ITextRenderer(); renderer.setDocument(refinedDoc, null); renderer.layout(); if(response != null) { //Stream to Output response.setContentType("application/pdf"); response.setHeader("Content-disposition", "attachment; filename=" + "scorecardReport.pdf"); response.setHeader("max-age=3600", "must-revalidate"); response.addCookie(new Cookie("fileDownload=true", "path=/")); out = response.getOutputStream(); } else { //Save to local file system out = new FileOutputStream(new File("testSaveReportImplementation.pdf")); } renderer.createPDF(out); } catch (ParserConfigurationException pcE) { pcE.printStackTrace(); } catch (SAXException saxE) { saxE.printStackTrace(); } catch (DocumentException docE) { docE.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } finally { if (out != null) { try { out.flush(); out.close(); } catch (IOException e) { e.printStackTrace(); } } if(LOG_HTML) { ApplicationUtil.debugLog("cleanHtmlReport", cleanHtmlReport); } } } protected static void convertHTMLToPDFAndStreamToOutput( String cleanHtmlReport, HttpServletResponse response) { convertHTMLToPDF(cleanHtmlReport, response); } private static void convertHTMLToPDFAndSaveToLocalFileSystem(String cleanHtmlReport) { convertHTMLToPDF(cleanHtmlReport); } /** * Converts JSON to ResponseTO Java Object using The Jackson API * * @param jsonReportData * JSON which resembles ResponseTO * @return converted ResponseTO POJO */ protected static ResponseTO convertJsonToPojo(String jsonReportData) { ObjectMapper mapper = new ObjectMapper(); ResponseTO pojo = null; try { pojo = mapper.readValue(jsonReportData, ResponseTO.class); } catch (IOException e) { e.printStackTrace(); } return pojo; } public enum SaveReportType { MATCH_UI, SUMMARY; } private static void buildReportUsingJSONFromLocalFile(String filenameWithoutExtension, SaveReportType reportType) throws URISyntaxException { URI jsonFileURI = new File( "src/main/webapp/resources/" + filenameWithoutExtension + ".json").toURI(); System.out.println("jsonFileURI"); System.out.println(jsonFileURI); String jsonReportData = convertFileToString(jsonFileURI); System.out.println("jsonReportData"); System.out.println(jsonReportData); ResponseTO pojoResponse = convertJsonToPojo(jsonReportData); System.out.println("response"); System.out.println(pojoResponse.getCcdaDocumentType()); convertHTMLToPDFAndSaveToLocalFileSystem( ensureLogicalParseTreeInHTML(convertReportToHTML(pojoResponse, reportType))); } private static String convertFileToString(URI fileURI) { StringBuilder sb = new StringBuilder(); BufferedReader br = null; try { br = new BufferedReader(new FileReader(fileURI.getPath())); String sCurrentLine = ""; while ((sCurrentLine = br.readLine()) != null) { sb.append(sCurrentLine); } } catch (Exception e) { e.printStackTrace(); } finally { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } return sb.toString(); } public static void main(String[] args) { String[] filenames = {"highScoringSample", "lowScoringSample", "sampleWithErrors", "sampleWithSchemaErrors", "sampleWithoutAnyContent"}; final int HIGH_SCORING_SAMPLE = 0, LOW_SCORING_SAMPLE = 1, SAMPLE_WITH_ERRORS = 2, SAMPLE_WITH_SCHEMA_ERRORS = 3, SAMPLE_WITHOUT_ANY_CONTENT = 4; try { buildReportUsingJSONFromLocalFile(filenames[SAMPLE_WITH_ERRORS], SaveReportType.SUMMARY); } catch (URISyntaxException e) { e.printStackTrace(); } } }
src/main/java/org/sitenv/service/ccda/smartscorecard/controller/SaveReportController.java
package org.sitenv.service.ccda.smartscorecard.controller; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.OutputStream; import java.net.URI; import java.net.URISyntaxException; import java.nio.charset.Charset; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.List; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletResponse; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.apache.commons.io.IOUtils; import org.jsoup.Jsoup; import org.sitenv.ccdaparsing.model.CCDAXmlSnippet; import org.sitenv.service.ccda.smartscorecard.cofiguration.ApplicationConfiguration; import org.sitenv.service.ccda.smartscorecard.model.CCDAScoreCardRubrics; import org.sitenv.service.ccda.smartscorecard.model.Category; import org.sitenv.service.ccda.smartscorecard.model.ReferenceError; import org.sitenv.service.ccda.smartscorecard.model.ReferenceResult; import org.sitenv.service.ccda.smartscorecard.model.ReferenceTypes.ReferenceInstanceType; import org.sitenv.service.ccda.smartscorecard.model.ResponseTO; import org.sitenv.service.ccda.smartscorecard.model.Results; import org.sitenv.service.ccda.smartscorecard.processor.ScorecardProcessor; import org.sitenv.service.ccda.smartscorecard.util.ApplicationConstants; import org.sitenv.service.ccda.smartscorecard.util.ApplicationUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.FileSystemResource; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.http.converter.FormHttpMessageConverter; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.util.LinkedMultiValueMap; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; import org.springframework.web.multipart.MultipartFile; import org.w3c.dom.Document; import org.xhtmlrenderer.pdf.ITextRenderer; import org.xml.sax.SAXException; import com.fasterxml.jackson.databind.ObjectMapper; import com.lowagie.text.DocumentException; @RestController public class SaveReportController { @Autowired private ScorecardProcessor scorecardProcessor; public static final String SAVE_REPORT_CHARSET_NAME = "UTF8"; private static final int CONFORMANCE_ERROR_INDEX = 0; private static final int CERTIFICATION_FEEDBACK_INDEX = 1; private static final boolean LOG_HTML = true; /** * Converts received JSON to a ResponseTO POJO (via method signature * automagically), converts the ResponseTO to a cleaned (parsable) HTML * report including relevant data, converts the HTML to a PDF report, and, * finally, streams the data for consumption. * This is intended to be called from a frontend which has already collected the JSON results. * * @param jsonReportData * JSON which resembles ResponseTO * @param response * used to stream the PDF */ @RequestMapping(value = "/savescorecardservice", method = RequestMethod.POST) public void savescorecardservice(@RequestBody ResponseTO jsonReportData, HttpServletResponse response) { convertHTMLToPDFAndStreamToOutput( ensureLogicalParseTreeInHTML(convertReportToHTML(jsonReportData, SaveReportType.MATCH_UI)), response); } /** * A single service to handle a pure back-end implementation of the * scorecard which streams back a PDF report. * This does not require the completed JSON up-front, it creates it from the file sent. * * @param ccdaFile * The C-CDA XML file intended to be scored */ @RequestMapping(value = "/savescorecardservicebackend", method = RequestMethod.POST) public void savescorecardservicebackend( @RequestParam("ccdaFile") MultipartFile ccdaFile, HttpServletResponse response) { handlePureBackendCall(ccdaFile, response, SaveReportType.MATCH_UI, scorecardProcessor); } /** * A single service to handle a pure back-end implementation of the * scorecard which streams back a PDF report. * This does not require the completed JSON up-front, it creates it from the file sent. * This differs from the savescorecardservicebackend in that it has its own specific format of the results * (dynamic and static table with 'call outs', no filename, more overview type content, etc.) * and is intended to be used when a Direct Message is received with a C-CDA document. * * @param ccdaFile * The C-CDA XML file intended to be scored * @param sender * The email address of the sender to be logged in the report */ @RequestMapping(value = "/savescorecardservicebackendsummary", method = RequestMethod.POST) public void savescorecardservicebackendsummary( @RequestParam("ccdaFile") MultipartFile ccdaFile, @RequestParam("sender") String sender, HttpServletResponse response) { if(ApplicationUtil.isEmpty(sender)) { sender = "Unknown Sender"; } handlePureBackendCall(ccdaFile, response, SaveReportType.SUMMARY, scorecardProcessor, sender); } private static void handlePureBackendCall(MultipartFile ccdaFile, HttpServletResponse response, SaveReportType reportType, ScorecardProcessor scorecardProcessor) { handlePureBackendCall(ccdaFile, response, reportType, scorecardProcessor, "savescorecardservicebackend"); } private static void handlePureBackendCall(MultipartFile ccdaFile, HttpServletResponse response, SaveReportType reportType, ScorecardProcessor scorecardProcessor, String sender) { ResponseTO pojoResponse = callCcdascorecardserviceInternally(ccdaFile, scorecardProcessor, sender, reportType); if (pojoResponse == null) { pojoResponse = new ResponseTO(); pojoResponse.setResults(null); pojoResponse.setSuccess(false); pojoResponse .setErrorMessage(ApplicationConstants.ErrorMessages.NULL_RESULT_ON_SAVESCORECARDSERVICEBACKEND_CALL); } else { if (!ApplicationUtil.isEmpty(ccdaFile.getOriginalFilename()) && ccdaFile.getOriginalFilename().contains(".")) { pojoResponse.setFilename(ccdaFile.getOriginalFilename()); } else if (!ApplicationUtil.isEmpty(ccdaFile.getName()) && ccdaFile.getName().contains(".")) { pojoResponse.setFilename(ccdaFile.getName()); } if(ApplicationUtil.isEmpty(pojoResponse.getFilename())) { pojoResponse.setFilename("Unknown"); } // otherwise it uses the name given by ccdascorecardservice } if(reportType == SaveReportType.SUMMARY) { pojoResponse.setFilename(sender); } convertHTMLToPDFAndStreamToOutput( ensureLogicalParseTreeInHTML(convertReportToHTML(pojoResponse, reportType)), response); }; protected static ResponseTO callCcdascorecardserviceInternally(MultipartFile ccdaFile, ScorecardProcessor scorecardProcessor, String sender, SaveReportType reportType) { return scorecardProcessor.processCCDAFile(ccdaFile, reportType == SaveReportType.SUMMARY, sender); } public static ResponseTO callCcdascorecardserviceExternally(MultipartFile ccdaFile) { String endpoint = ApplicationConfiguration.CCDASCORECARDSERVICE_URL; return callServiceExternally(endpoint, ccdaFile, null); } public static ResponseTO callSavescorecardservicebackendExternally(MultipartFile ccdaFile) { String endpoint = ApplicationConfiguration.SAVESCORECARDSERVICEBACKEND_URL; return callServiceExternally(endpoint, ccdaFile, null); } public static ResponseTO callSavescorecardservicebackendsummaryExternally(MultipartFile ccdaFile, String senderValue) { String endpoint = ApplicationConfiguration.SAVESCORECARDSERVICEBACKENDSUMMARY_URL; return callServiceExternally(endpoint, ccdaFile, senderValue); } private static ResponseTO callServiceExternally(String endpoint, MultipartFile ccdaFile, String senderValue) { ResponseTO pojoResponse = null; LinkedMultiValueMap<String, Object> requestMap = new LinkedMultiValueMap<>(); FileOutputStream out = null; File tempFile = null; try { final String tempCcdaFileName = "ccdaFile"; tempFile = File.createTempFile(tempCcdaFileName, "xml"); out = new FileOutputStream(tempFile); IOUtils.copy(ccdaFile.getInputStream(), out); requestMap.add(tempCcdaFileName, new FileSystemResource(tempFile)); if(senderValue != null) { String senderKey = "sender"; requestMap.add(senderKey, senderValue); } HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.MULTIPART_FORM_DATA); HttpEntity<LinkedMultiValueMap<String, Object>> requestEntity = new HttpEntity<>( requestMap, headers); FormHttpMessageConverter formConverter = new FormHttpMessageConverter(); formConverter.setCharset(Charset.forName(SAVE_REPORT_CHARSET_NAME)); RestTemplate restTemplate = new RestTemplate(); restTemplate.getMessageConverters().add(formConverter); restTemplate.getMessageConverters().add( new MappingJackson2HttpMessageConverter()); pojoResponse = restTemplate.postForObject(endpoint, requestEntity, ResponseTO.class); } catch (Exception e) { e.printStackTrace(); } finally { if (out != null) { try { out.flush(); out.close(); } catch (IOException ioe) { ioe.printStackTrace(); } } if (tempFile != null && tempFile.isFile()) { tempFile.delete(); } } return pojoResponse; } /** * Parses (POJO ResponseTO converted) JSON and builds the results into an * HTML report * * @param report * the ResponseTO report intended to be converted to HTML * @return the converted HTML report as a String */ protected static String convertReportToHTML(ResponseTO report, SaveReportType reportType) { StringBuffer sb = new StringBuffer(); appendOpeningHtml(sb); if (report == null) { report = new ResponseTO(); report.setResults(null); report.setSuccess(false); report.setErrorMessage(ApplicationConstants.ErrorMessages.GENERIC_WITH_CONTACT); appendErrorMessageFromReport(sb, report, ApplicationConstants.ErrorMessages.RESULTS_ARE_NULL); } else { // report != null if (report.getResults() != null) { if (report.isSuccess()) { Results results = report.getResults(); List<Category> categories = results.getCategoryList(); List<ReferenceResult> referenceResults = report .getReferenceResults(); appendHeader(sb, report, results, reportType); appendHorizontalRuleWithBreaks(sb); if(reportType == SaveReportType.SUMMARY) { appendPreTopLevelResultsContent(sb); } appendTopLevelResults(sb, results, categories, referenceResults, reportType, report.getCcdaDocumentType()); if(reportType == SaveReportType.MATCH_UI) { appendHorizontalRuleWithBreaks(sb); appendHeatmap(sb, results, categories, referenceResults); } sb.append("<br />"); appendHorizontalRuleWithBreaks(sb); if(reportType == SaveReportType.MATCH_UI) { if(!ApplicationUtil.isEmpty(report.getReferenceResults()) || results.getNumberOfIssues() > 0) { appendDetailedResults(sb, categories, referenceResults); } } if(reportType == SaveReportType.SUMMARY) { /* appendPictorialGuide(sb, categories, referenceResults); appendPictorialGuideKey(sb); */ } } } else { // report.getResults() == null if (!report.isSuccess()) { appendErrorMessageFromReport(sb, report, null); } else { appendErrorMessageFromReport(sb, report); } } } appendClosingHtml(sb); return sb.toString(); } private static void appendOpeningHtml(StringBuffer sb) { sb.append("<!DOCTYPE html>"); sb.append("<html>"); sb.append("<head>"); sb.append("<title>SITE C-CDA Scorecard Report</title>"); appendStyleSheet(sb); sb.append("</head>"); sb.append("<body style='font-family: \"Helvetica Neue\",Helvetica,Arial,sans-serif;'>"); } private static void appendStyleSheet(StringBuffer sb) { sb.append("<style>" + " .site-header { background: url('https://sitenv.org/assets/images/site/bg-header-1920x170.png') repeat-x center top #1fdbfe; } " + " .site-logo { text-decoration: none; } " + " table { font-family: arial, sans-serif; border-collapse: separate; width: 100%; } " + " td, th { border: 1px solid #dddddd; text-align: left; padding: 8px; } " + " #dynamicTable tr:nth-child(even) { background-color: #dddddd; } " + " #staticTable { font-size: 11px; } " + " .popOuts { font-size: 11px; background-color: ghostwhite !important; } " + " .removeBorder { border: none; background-color: white; } " + " #notScoredRowPopOutLink { border-top: 6px double MAGENTA; border-bottom: none; border-left: none; border-right: none; } " + " #perfectRowPopOutLink { border-top: 6px double MEDIUMPURPLE; border-bottom: none; border-left: none; border-right: none; } " + " #gradePopOutLink { border-left: 6px solid MEDIUMSEAGREEN; border-right: none; border-bottom: none; border-top: none; } " + " #issuePopOutLink { border-left: 6px double orange; border-right: none; border-bottom: none; border-top: none; } " + " #errorPopOutLink { border-right: none; border-left: 6px solid red; border-bottom: none; border-top: none; } " + " #feedbackPopOutLink { border-right: none; border-left: 6px double DEEPSKYBLUE; border-bottom: none; border-top: none; } " + " #notScoredRowPopOut { border: 6px double MAGENTA; border-radius: 0px 25px 25px 25px; } " + " #perfectRowPopOut { border: 6px double MEDIUMPURPLE; border-radius: 25px 0px 25px 25px; } " + " #gradePopOut { border: 6px solid MEDIUMSEAGREEN; border-radius: 25px 25px 25px 25px; } " + " #issuePopOut { border: 6px double orange; border-radius: 25px 25px 25px 0px; } " + " #errorPopOut { border: 6px solid red; border-radius: 25px 25px 25px 0px; } " + " #feedbackPopOut { border: 6px double DEEPSKYBLUE; border-radius: 25px 25px 25px 0px; } " + " #perfectRowLeftHeader { border-left: 6px double MEDIUMPURPLE; border-top: 6px double MEDIUMPURPLE; border-bottom: 6px double MEDIUMPURPLE; } " + " #perfectRowRightHeader { border-right: 6px double MEDIUMPURPLE; border-top: 6px double MEDIUMPURPLE; border-bottom: 6px double MEDIUMPURPLE; } " + " .perfectRowMiddleHeader { border-top: 6px double MEDIUMPURPLE; border-bottom: 6px double MEDIUMPURPLE; } " + " #notScoredRowLeftHeader { border-left: 6px double MAGENTA; border-top: 6px double MAGENTA; border-bottom: 6px double MAGENTA; } " + " #notScoredRowRightHeader { border-right: 6px double MAGENTA; border-top: 6px double MAGENTA; border-bottom: 6px double MAGENTA; } " + " .notScoredRowMiddleHeader { border-top: 6px double MAGENTA; border-bottom: 6px double MAGENTA; } " + " #gradeHeader { border: 6px solid MEDIUMSEAGREEN; } " + " #issueHeader { border: 6px double orange; } " + " #errorHeader { border: 6px solid red; } " + " #feedbackHeader { border: 6px double DEEPSKYBLUE; } " + " #keyGradeHeader { color: MEDIUMSEAGREEN; font-weight: bold; } " + " #keyIssueHeader { color: orange; font-weight: bold; } " + " #keyErrorHeader { color: red; font-weight: bold; } " + " #keyFeedbackHeader { color: DEEPSKYBLUE; font-weight: bold; } " + " </style> "); } private static void appendHeader(StringBuffer sb, ResponseTO report, Results results, SaveReportType reportType) { sb.append("<header id='topOfScorecard'>"); sb.append("<center>"); sb.append("<div class=\"site-header\">") .append(" <a class=\"site-logo\" href=\"https://www.healthit.gov/\"") .append(" rel=\"external\" title=\"HealthIT.gov\"> <img alt=\"HealthIT.gov\"") .append(" src=\"https://sitenv.org/assets/images/site/healthit.gov.logo.png\" width='40%'>") .append(" </a>") .append("</div>"); sb.append("<br />"); appendHorizontalRuleWithBreaks(sb); sb.append("<h1>" + "C-CDA "); if(reportType == SaveReportType.SUMMARY) { sb.append("Scorecard For " + (report.getCcdaDocumentType() != null ? report .getCcdaDocumentType() : "document") + "</h1>"); sb.append("<h5>"); sb.append("<span style='float: left'>" + "Submitted By: " + (!ApplicationUtil.isEmpty(report.getFilename()) ? report.getFilename() : "Unknown") + "</span>"); DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss"); sb.append("<span style='float: right'>" + "Submission Time: " + dateFormat.format(new Date()) + "</span>"); sb.append("</h5>"); sb.append("<div style='clear: both'></div>"); appendBasicResults(sb, results); } else { sb.append(results.getCcdaVersion() + " " + (report.getCcdaDocumentType() != null ? report .getCcdaDocumentType() : "document") + " Scorecard For:" + "</h1>"); sb.append("<h2>" + report.getFilename() + "</h2>"); } sb.append("</center>"); sb.append("</header>"); } private static void appendPreTopLevelResultsContent(StringBuffer sb) { /* sb.append("<p>") .append(" The C-CDA Scorecard enables providers, implementers, and health") .append(" IT professionals with a tool that compares how artifacts (transition") .append(" of care documents, care plans etc) created by your organization") .append(" stack up against the HL7 C-CDA implementation guide and HL7 best") .append(" practices. The C-CDA Scorecard promotes best practices in C-CDA") .append(" implementation by assessing key aspects of the structured data found") .append(" in individual documents. The Scorecard tool provides a rough") .append(" quantitative assessment and highlights areas of improvement which") .append(" can be made today to move the needle forward in interoperability of") .append(" C-CDA documents. The ") .append(" <a href=\"http://www.hl7.org/documentcenter/public/wg/structure/C-CDA%20Scorecard%20Rubrics%203.pptx\">" + "best practices and quantitative scoring criteria" + "</a>") .append(" have been developed by HL7 through the HL7-ONC Cooperative agreement") .append(" to improve the implementation of health care standards. We hope that") .append(" providers and health IT developers will use the tool to identify and") .append(" resolve issues around C-CDA document interoperability in their") .append(" health IT systems.") .append("</p>") */ sb.append("<p>If you are not satisfied with your results:</p>"); sb.append("<ul>"); sb.append("<li>"); sb.append("Please ask your vendor to submit the document to the SITE C-CDA Scorecard website " + " at " + "<a href=\"https://healthit.gov/scorecard/\">" + "www.healthit.gov/scorecard" + "</a>" + " for more detailed information"); sb.append("</li>"); sb.append("<li>"); sb.append("Using the results provided by the online tool, " + "your vendor can update or provide insight on how to update your document to meet the latest HL7 best-practices"); sb.append("</li>"); sb.append("<li>"); sb.append("Once updated, " + "resubmitting your document to the ONC One Click Scorecard will produce a report with a higher score " + "and/or less or no conformance errors or less or no certification feedback results"); sb.append("</li>"); sb.append("</ul>"); sb.append("<p>") .append("This page contains a summary of the C-CDA Scorecard results highlighting the overall document grade " + "which is derived from a quantitative score out of a maximum of 100. ") .append("</p>"); sb.append("<p>") .append("The second and final page identifies areas for improvement organized by clinical domains.") .append("</p>"); } private static void appendBasicResults(StringBuffer sb, Results results) { sb.append("<center>"); sb.append("<h2>"); sb.append("<span style=\"margin-right: 40px\">Grade: " + results.getFinalGrade() + "</span>"); sb.append("<span style=\"margin-left: 40px\">Score: " + results.getFinalNumericalGrade() + "/100" + "</span>"); sb.append("</h2>"); sb.append("</center>"); } private static void appendTopLevelResults(StringBuffer sb, Results results, List<Category> categories, List<ReferenceResult> referenceResults, SaveReportType reportType, String ccdaDocumentType) { boolean isReferenceResultsEmpty = ApplicationUtil.isEmpty(referenceResults); int conformanceErrorCount = isReferenceResultsEmpty ? 0 : referenceResults.get(CONFORMANCE_ERROR_INDEX).getTotalErrorCount(); int certificationFeedbackCount = isReferenceResultsEmpty ? 0 : referenceResults.get(CERTIFICATION_FEEDBACK_INDEX).getTotalErrorCount(); if(reportType == SaveReportType.SUMMARY) { //brief summary of overall document results (without scorecard issues count listed) sb.append("<h3>Summary</h3>"); sb.append("<p>" + "Your " + ccdaDocumentType + " document received a grade of <b>" + results.getFinalGrade() + "</b>" + " compared to an industry average of " + "<b>" + results.getIndustryAverageGradeForCcdaDocumentType() + "</b>" + ". " + "The industry average, specific to the document type sent, was computed by scoring " + results.getNumberOfDocsScoredPerCcdaDocumentType() + " " + ccdaDocumentType + (results.getNumberOfDocsScoredPerCcdaDocumentType() > 1 ? "s" : "" ) + ". " + "The document scored " + "<b>" + results.getFinalNumericalGrade() + "/100" + "</b>" + " and is " + (conformanceErrorCount > 0 ? "non-compliant" : "compliant") + " with the HL7 C-CDA IG" + " and is " + (certificationFeedbackCount > 0 ? "non-compliant" : "compliant") + " with 2015 Edition Certification requirements. " + "The detailed results organized by clinical domains are provided in the table below:" + "</p>"); //dynamic table appendHorizontalRuleWithBreaks(sb); sb.append("<br /><br />"); sb.append("<h2>Scorecard Results by Clinical Domain</h2>"); appendDynamicTopLevelResultsTable(sb, results, categories, referenceResults); } else { sb.append("<h3>Scorecard Grade: " + results.getFinalGrade() + "</h3>"); sb.append("<ul><li>"); sb.append("<p>Your document scored a " + "<b>" + results.getFinalGrade() + "</b>" + " compared to an industry average of " + "<b>" + results.getIndustryAverageGrade() + "</b>" + ".</p>"); sb.append("</ul></li>"); sb.append("<h3>Scorecard Score: " + results.getFinalNumericalGrade() + "</h3>"); sb.append("<ul><li>"); sb.append("<p>Your document scored " + "<b>" + +results.getFinalNumericalGrade() + "</b>" + " out of " + "<b>" + " 100 " + "</b>" + " total possible points.</p>"); sb.append("</ul></li>"); boolean isSingular = results.getNumberOfIssues() == 1; appendSummaryRow(sb, results.getNumberOfIssues(), "Scorecard Issues", null, isSingular ? "Scorecard Issue" : "Scorecard Issues", isSingular); sb.append("</ul></li>"); String messageSuffix = null; if (isReferenceResultsEmpty) { for (ReferenceInstanceType refType : ReferenceInstanceType.values()) { if (refType == ReferenceInstanceType.CERTIFICATION_2015) { messageSuffix = "results"; } appendSummaryRow(sb, 0, refType.getTypePrettyName(), messageSuffix, refType.getTypePrettyName(), false, reportType); sb.append("</ul></li>"); } } else { for (ReferenceResult refResult : referenceResults) { int refErrorCount = refResult.getTotalErrorCount(); isSingular = refErrorCount == 1; String refTypeName = refResult.getType().getTypePrettyName(); String messageSubject = ""; if (refResult.getType() == ReferenceInstanceType.IG_CONFORMANCE) { messageSubject = isSingular ? refTypeName.substring(0, refTypeName.length() - 1) : refTypeName; } else if (refResult.getType() == ReferenceInstanceType.CERTIFICATION_2015) { messageSuffix = isSingular ? "result" : "results"; messageSubject = refTypeName; } appendSummaryRow(sb, refErrorCount, refTypeName, messageSuffix, messageSubject, isSingular, reportType); sb.append("</ul></li>"); } } } } private static int getFailingSectionSpecificErrorCount(String categoryName, ReferenceInstanceType refType, List<ReferenceResult> referenceResults) { if (!ApplicationUtil.isEmpty(referenceResults)) { if (refType == ReferenceInstanceType.IG_CONFORMANCE) { List<ReferenceError> igErrors = referenceResults.get(CONFORMANCE_ERROR_INDEX).getReferenceErrors(); if (!ApplicationUtil.isEmpty(igErrors)) { return getFailingSectionSpecificErrorCountProcessor(categoryName, igErrors); } } else if (refType == ReferenceInstanceType.CERTIFICATION_2015) { List<ReferenceError> certErrors = referenceResults.get(CERTIFICATION_FEEDBACK_INDEX).getReferenceErrors(); if (!ApplicationUtil.isEmpty(certErrors)) { return getFailingSectionSpecificErrorCountProcessor(categoryName, certErrors); } } } return 0; } private static int getFailingSectionSpecificErrorCountProcessor( String categoryName, List<ReferenceError> errors) { int count = 0; for (int i = 0; i < errors.size(); i++) { String currentSectionInReferenceErrors = errors.get(i).getSectionName(); if (!ApplicationUtil.isEmpty(currentSectionInReferenceErrors)) { if (currentSectionInReferenceErrors.equalsIgnoreCase(categoryName)) { count++; } } } return count; } private static void appendDynamicTopLevelResultsTable(StringBuffer sb, Results results, List<Category> categories, List<ReferenceResult> referenceResults) { sb.append("<table id='dynamicTable'>"); sb.append(" <tbody>"); sb.append(" <tr class=\"popOuts\">"); sb.append(" <td id=\"gradePopOut\" colspan=\"2\">"); sb.append(" The Scorecard grade is a quantitative assessment of the data quality of the submitted document. " + "A higher grade indicates that HL7 best practices for C-CDA implementation are being followed by the organization and " + "has higher probability of being interoperable with other organizations."); sb.append(" </td>"); sb.append(" <td id=\"issuePopOut\">"); sb.append(" A Scorecard Issue identifies data within the document which can be represented in a better way using " + "HL7 best practices for C-CDA. This column should have numbers as close to zero as possible."); sb.append(" </td>"); sb.append(" <td id=\"errorPopOut\">"); sb.append(" A Conformance Error implies that the document is non-compliant with the HL7 C-CDA IG requirements. " + "This column should have zeros ideally. Providers should work with their health IT vendor to rectify the errors."); sb.append(" </td>"); sb.append(" <td id=\"feedbackPopOut\">"); sb.append(" A Certification Feedback result identifies areas where the generated documents are not compliant with " + "the requirements of 2015 Edition Certification. Ideally, this column should have all zeros."); sb.append(" </td>"); sb.append(" </tr>"); sb.append(" <tr>"); sb.append(" <td class=\"removeBorder\"></td>"); sb.append(" <td class=\"removeBorder\" id=\"gradePopOutLink\"></td>"); sb.append(" <td class=\"removeBorder\" id=\"issuePopOutLink\"></td>"); sb.append(" <td class=\"removeBorder\" id=\"errorPopOutLink\"></td>"); sb.append(" <td class=\"removeBorder\" id=\"feedbackPopOutLink\"></td>"); sb.append(" </tr> "); sb.append(" <tr style=\"background-color: ghostwhite\">"); sb.append(" <th>Clinical Domain</th> "); sb.append(" <th id=\"gradeHeader\">Scorecard Grade</th> "); sb.append(" <th id=\"issueHeader\">Scorecard Issues</th> "); sb.append(" <th id=\"errorHeader\">Conformance Errors</th> "); sb.append(" <th id=\"feedbackHeader\">Certification Feedback</th> "); sb.append(" </tr> "); for(Category category : getSortedCategories(categories)) { // if(category.getNumberOfIssues() > 0 || referenceResults.get(ReferenceInstanceType.IG/CERT).getTotalErrorCount() > 0) { // if(category.getNumberOfIssues() > 0 || category.isFailingConformance() || category.isCertificationFeedback()) { sb.append(" <tr>") .append(" <td>" + (category.getCategoryName() != null ? category.getCategoryName() : "Unknown") + "</td>") .append(" <td>" + (category.getCategoryGrade() != null ? category.getCategoryGrade() : "N/A") + "</td>") .append(" <td>" + (category.isFailingConformance() || category.isCertificationFeedback() || category.isNullFlavorNI() ? "N/A" : category.getNumberOfIssues()) + "</td>") .append(" <td>" + (!ApplicationUtil.isEmpty(category.getCategoryName()) ? getFailingSectionSpecificErrorCount(category.getCategoryName(), ReferenceInstanceType.IG_CONFORMANCE, referenceResults) : "N/A") + "</td>") .append(" <td>" + (!ApplicationUtil.isEmpty(category.getCategoryName()) ? getFailingSectionSpecificErrorCount(category.getCategoryName(), ReferenceInstanceType.CERTIFICATION_2015, referenceResults) : "N/A") + "</td>") .append(" </tr>"); // } } sb.append(" <tbody>"); sb.append("</table>"); } /** * Order from best to worst:<br/> * 1. Numerical score high to low 2. Empty/null 3. Certification Feedback 4. Conformance Error * @param categories - Category List to sort * @return sorted categories */ private static List<Category> getSortedCategories(List<Category> categories) { List<Category> sortedCategories = new ArrayList<Category>(categories); //prepare for sort of non-scored items for(Category category : sortedCategories) { if(category.isFailingConformance()) { category.setCategoryNumericalScore(-3); } else if(category.isCertificationFeedback()) { category.setCategoryNumericalScore(-2); } else if(category.isNullFlavorNI()) { category.setCategoryNumericalScore(-1); } } //sorts by numerical score via Comparable implementation in Category Collections.sort(sortedCategories, Collections.reverseOrder()); return sortedCategories; } private static void appendHeatmap(StringBuffer sb, Results results, List<Category> categories, List<ReferenceResult> referenceResults) { sb.append("<span id='heatMap'>" + "</span>"); for (Category curCategory : getSortedCategories(categories)) { sb.append("<h3>" + (curCategory.getNumberOfIssues() > 0 ? "<a href='#" + curCategory.getCategoryName() + "-category" + "'>" : "") + curCategory.getCategoryName() + (curCategory.getNumberOfIssues() > 0 ? "</a>" : "") + "</h3>"); sb.append("<ul>"); if (curCategory.getCategoryGrade() != null) { sb.append("<li>" + "Section Grade: " + "<b>" + curCategory.getCategoryGrade() + "</b>" + "</li>" + "<li>" + "Number of Issues: " + "<b>" + curCategory.getNumberOfIssues() + "</b>" + "</li>"); } else { sb.append("<li>" + "This category was not scored as it "); if(curCategory.isNullFlavorNI()) { sb.append("is an <b>empty section</b>"); } boolean failingConformance = curCategory.isFailingConformance(); boolean failingCertification = curCategory.isCertificationFeedback(); if(failingConformance || failingCertification) { boolean isCategoryNameValid = !ApplicationUtil.isEmpty(curCategory.getCategoryName()); if(failingConformance && failingCertification || failingConformance && !failingCertification) { //we default to IG if true for both since IG is considered a more serious issue (same with the heatmap label, so we match that) //there could be a duplicate for two reasons, right now, there's always at least one duplicate since we derive ig from cert in the backend //in the future this might not be the case, but, there could be multiple section fails in the same section, so we have a default for those too int igErrorCount = isCategoryNameValid ? getFailingSectionSpecificErrorCount(curCategory.getCategoryName(), ReferenceInstanceType.IG_CONFORMANCE, referenceResults) : -1; sb.append("contains" + (isCategoryNameValid ? " <b>" + igErrorCount + "</b> " : "") + "<a href='#" + ReferenceInstanceType.IG_CONFORMANCE.getTypePrettyName() + "-category'" + ">" + "Conformance Error" + (igErrorCount != 1 ? "s" : "") + "</a>"); } else if(failingCertification && !failingConformance) { int certFeedbackCount = isCategoryNameValid ? getFailingSectionSpecificErrorCount(curCategory.getCategoryName(), ReferenceInstanceType.CERTIFICATION_2015, referenceResults) : -1; sb.append("contains" + (isCategoryNameValid ? " <b>" + certFeedbackCount + "</b> " : "") + "<a href='#" + ReferenceInstanceType.CERTIFICATION_2015.getTypePrettyName() + "-category'" + ">" + "Certification Feedback" + "</a>" + " result" + (certFeedbackCount != 1 ? "s" : "")); } } sb.append("</li>"); } sb.append("</ul></li>"); } } private static void appendSummaryRow(StringBuffer sb, int result, String header, String messageSuffix, String messageSubject, boolean isSingular) { appendSummaryRow(sb, result, header, messageSuffix, messageSubject, isSingular, null); } private static void appendSummaryRow(StringBuffer sb, int result, String header, String messageSuffix, String messageSubject, boolean isSingular, SaveReportType reportType) { if(reportType == null) { reportType = SaveReportType.MATCH_UI; } sb.append("<h3>" + header + ": " + ("Scorecard Issues".equals(header) || result < 1 || reportType == SaveReportType.SUMMARY ? result : ("<a href=\"#" + header + "-category\">" + result + "</a>")) + "</h3>"); sb.append("<ul><li>"); sb.append("<p>There " + (isSingular ? "is" : "are") + " " + "<b>" + result + "</b>" + " " + messageSubject + (messageSuffix != null ? " " + messageSuffix : "") + " in your document.</p>"); } private static void appendDetailedResults(StringBuffer sb, List<Category> categories, List<ReferenceResult> referenceResults) { sb.append("<h2>" + "Detailed Results" + "</h2>"); if (!ApplicationUtil.isEmpty(referenceResults)) { for (ReferenceResult curRefInstance : referenceResults) { ReferenceInstanceType refType = curRefInstance.getType(); if (curRefInstance.getTotalErrorCount() > 0) { String refTypeName = refType.getTypePrettyName(); sb.append("<h3 id=\"" + refTypeName + "-category\">" + refTypeName + "</h3>"); sb.append("<ul>"); // START curRefInstance ul sb.append("<li>" + "Number of " + (refType == ReferenceInstanceType.CERTIFICATION_2015 ? "Results:" : "Errors:") + " " + curRefInstance.getTotalErrorCount() + "</li>"); sb.append("<ol>"); // START reference errors ol for (ReferenceError curRefError : curRefInstance .getReferenceErrors()) { sb.append("<li>" + (refType == ReferenceInstanceType.CERTIFICATION_2015 ? "Feedback:" : "Error:") + " " + curRefError.getDescription() + "</li>"); sb.append("<ul>"); // START ul within the curRefError if (!ApplicationUtil.isEmpty(curRefError .getSectionName())) { sb.append("<li>" + "Related Section: " + curRefError.getSectionName() + "</li>"); } sb.append("<li>" + "Document Line Number (approximate): " + curRefError.getDocumentLineNumber() + "</li>"); sb.append("<li>" + "xPath: " + "<xmp style='font-family: Consolas, monaco, monospace;'>" + curRefError.getxPath() + "</xmp>" + "</li>"); sb.append("</ul>"); // END ul within the curRefError } } sb.append("</ol>"); // END reference errors ol sb.append("</ul>"); // END curRefInstance ul appendBackToTopWithBreaks(sb); } //END for (ReferenceResult curRefInstance : referenceResults) } for (Category curCategory : getSortedCategories(categories)) { if (curCategory.getNumberOfIssues() > 0) { sb.append("<h3 id='" + curCategory.getCategoryName() + "-category" + "'>" + curCategory.getCategoryName() + "</h3>"); sb.append("<ul>"); // START curCategory ul sb.append("<li>" + "Section Grade: " + curCategory.getCategoryGrade() + "</li>" + "<li>" + "Number of Issues: " + curCategory.getNumberOfIssues() + "</li>"); sb.append("<ol>"); // START rules ol for (CCDAScoreCardRubrics curRubric : curCategory .getCategoryRubrics()) { if (curRubric.getNumberOfIssues() > 0) { sb.append("<li>" + "Rule: " + curRubric.getRule() + "</li>"); if (curRubric.getDescription() != null) { sb.append("<ul>" + "<li>" + "Description" + "</li>" + "<ul>" + "<li>" + curRubric.getDescription() + "</li>" + "</ul>" + "</ul>"); sb.append("<br />"); sb.append("<ol>"); // START snippets ol for (CCDAXmlSnippet curSnippet : curRubric .getIssuesList()) { sb.append("<li>" + "XML at line number " + curSnippet.getLineNumber() + "</li>" + "<br /><xmp style='font-family: Consolas, monaco, monospace;'>" + curSnippet.getXmlString() + "</xmp><br /><br />"); } sb.append("</ol>"); // END snippets ol } } else { // don't display rules without occurrences sb.append("</ol>"); } } sb.append("</ol>"); // END rules ol sb.append("</ul>"); // END curCategory ul appendBackToTopWithBreaks(sb); } //END if (curCategory.getNumberOfIssues() > 0) } //END for (Category curCategory : categories) } private static void appendPictorialGuide(StringBuffer sb, List<Category> categories, List<ReferenceResult> referenceResults) { //minimum breaks based on 11 categories sb.append("<br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />"); sb.append("<h2>" + "Guide to Interpret the Scorecard Results Table" + "</h2>"); sb.append("<p>" + "The following sample table identifies how to use the C-CDA Scorecard results " + "to improve the C-CDA documents generated by your organization. " + "Note: The table below is an example containing fictitious results " + "and does not reflect C-CDAs generated by your organization." + "</p>"); //static table sb.append("<table id=\"staticTable\">") .append(" <tbody>") .append(" <tr>") .append(" <td class=\"removeBorder\"></td>") .append(" <td class=\"removeBorder\"></td>") .append(" <td class=\"removeBorder\"></td>") .append(" <td class=\"removeBorder\"></td>") .append(" <td id=\"issuePopOut\" rowspan=\"2\">A Scorecard Issue identifies data within the document which can be represented in a better way using HL7 best practices for C-CDA. This column should have numbers as close to zero as possible.</td>") .append(" <td class=\"removeBorder\"></td>") .append(" <td class=\"removeBorder\"></td>") .append(" <td class=\"removeBorder\"></td>") .append(" <td class=\"removeBorder\"></td>") .append(" </tr>") .append(" <tr>") .append(" <td class=\"removeBorder\"></td>") .append(" <td class=\"removeBorder\"></td>") .append(" <td id=\"gradePopOut\" colspan=\"2\">The Scorecard grade is a quantitative assessment of the data quality of the submitted document. A higher grade indicates that HL7 best practices for C-CDA implementation are being followed by the organization and has higher probability of being interoperable") .append(" with other organizations.</td>") .append(" <td id=\"errorPopOut\" colspan=\"2\">A Conformance Error implies that the document is non-compliant with the HL7 C-CDA IG requirements. This column should have zeros ideally. Providers should work with their health IT vendor to rectify the errors.</td>") .append(" <td class=\"removeBorder\"></td>") .append(" <td class=\"removeBorder\"></td>") .append(" </tr>") .append(" <tr>") .append(" <td class=\"removeBorder\"></td>") .append(" <td class=\"removeBorder\"></td>") .append(" <td class=\"removeBorder\"></td>") .append(" <td id=\"gradePopOutLink\"></td>") .append(" <td id=\"issuePopOutLink\"></td>") .append(" <td id=\"errorPopOutLink\"></td>") .append(" <td class=\"removeBorder\"></td>") .append(" <td class=\"removeBorder\"></td>") .append(" <td class=\"removeBorder\"></td>") .append(" </tr>") .append(" <tr>") .append(" <td class=\"removeBorder\"></td>") .append(" <td class=\"removeBorder\"></td>") .append(" <th>Clinical Domain</th>") .append(" <th id=\"gradeHeader\">Scorecard Grade</th>") .append(" <th id=\"issueHeader\">Scorecard Issues</th>") .append(" <th id=\"errorHeader\">Conformance Errors</th>") .append(" <th id=\"feedbackHeader\">Certification Feedback</th>") .append(" <td id=\"feedbackPopOutLink\"></td>") .append(" <td id=\"feedbackPopOut\" rowspan=\"5\">A Certification Feedback result identifies areas where the generated documents are not compliant with the requirements of 2015 Edition Certification. Ideally, this column should have all zeros.</td>") .append(" </tr>") .append(" <tr>") .append(" <td id=\"perfectRowPopOut\" rowspan=\"4\">The Problems row in this example has an A+ grade and all zeros across the board. This is the most desirable outcome for a Clinical Domain result set.</td>") .append(" <td id=\"perfectRowPopOutLink\"></td>") .append(" <td id=\"perfectRowLeftHeader\">Problems</td>") .append(" <td class=\"perfectRowMiddleHeader\">A+</td>") .append(" <td class=\"perfectRowMiddleHeader\">0</td>") .append(" <td class=\"perfectRowMiddleHeader\">0</td>") .append(" <td id=\"perfectRowRightHeader\">0</td>") .append(" <td class=\"removeBorder\"></td>") .append(" </tr>") .append(" <tr>") .append(" <td class=\"removeBorder\"></td>") .append(" <td>Lab Results</td>") .append(" <td>A-</td>") .append(" <td>2</td>") .append(" <td>0</td>") .append(" <td>0</td>") .append(" <td class=\"removeBorder\"></td>") .append(" </tr>") .append(" <tr>") .append(" <td class=\"removeBorder\"></td>") .append(" <td>Vital Signs</td>") .append(" <td>A-</td>") .append(" <td>1</td>") .append(" <td>0</td>") .append(" <td>0</td>") .append(" <td class=\"removeBorder\"></td>") .append(" </tr>") .append(" <tr>") .append(" <td class=\"removeBorder\"></td>") .append(" <td>Encounters</td>") .append(" <td>D</td>") .append(" <td>12</td>") .append(" <td>0</td>") .append(" <td>0</td>") .append(" <td class=\"removeBorder\"></td>") .append(" <td class=\"removeBorder\"></td>") .append(" </tr>") .append(" <tr>") .append(" <td class=\"removeBorder\"></td>") .append(" <td class=\"removeBorder\"></td>") .append(" <td id=\"notScoredRowLeftHeader\">Medications</td>") .append(" <td class=\"notScoredRowMiddleHeader\">N/A</td>") .append(" <td class=\"notScoredRowMiddleHeader\">N/A</td>") .append(" <td class=\"notScoredRowMiddleHeader\">2</td>") .append(" <td id=\"notScoredRowRightHeader\">0</td>") .append(" <td id=\"notScoredRowPopOutLink\"></td>") .append(" <td id=\"notScoredRowPopOut\" rowspan=\"3\">This domain was not scored because the document did not have data pertaining to the clinical domain or there were conformance errors or certification results.</td>") .append(" </tr>") .append(" <tr>") .append(" <td class=\"removeBorder\"></td>") .append(" <td class=\"removeBorder\"></td>") .append(" <td>Allergies</td>") .append(" <td>N/A</td>") .append(" <td>N/A</td>") .append(" <td>0</td>") .append(" <td>4</td>") .append(" <td class=\"removeBorder\"></td>") .append(" <td class=\"removeBorder\"></td>") .append(" </tr>") .append(" <tr>") .append(" <td class=\"removeBorder\"></td>") .append(" <td class=\"removeBorder\"></td>") .append(" <td>Immunizations</td>") .append(" <td>N/A</td>") .append(" <td>N/A</td>") .append(" <td>0</td>") .append(" <td>0</td>") .append(" <td class=\"removeBorder\"></td>") .append(" <td class=\"removeBorder\"></td>") .append(" </tr>") .append(" </tbody>") .append("</table>"); } private static void appendPictorialGuideKey(StringBuffer sb) { sb.append("<h3>Additional Guidance to Interpret the Scorecard Results and Achieve Higher Grades</h3>") .append("<p>") .append(" <span id=\"keyGradeHeader\">Scorecard Grade: </span>") .append("The Scorecard grade is a quantitative assessment of the data quality of the submitted document. " + "A higher grade indicates that HL7 best practices for C-CDA implementation are being followed by the organization " + "and has higher probability of being interoperable with other organizations. " + "The grades are derived from the scores as follows: " + "A+ ( > 94), A- ( 90 to 94), B+ (85 to 89), B- (80 to 84), C (70 to 79) and D (< 70).") .append("</p>") .append("<p>") .append(" <span id=\"keyIssueHeader\">Scorecard Issues: </span>") .append("A Scorecard Issue identifies data within the document which can be represented in a better way using HL7 best practices for C-CDA. " + "This column should have numbers as close to zero as possible. " + "The issues are counted for each occurrence of unimplemented best practice. " + "For example, if a Vital Sign measurement is not using the appropriate UCUM units then each such occurrence would be flagged " + "as an issue. A provider should work with their health IT vendor to better understand the source for why a best practice " + "may not be implemented and then determine if it can be implemented in the future. Note: Scorecard Issues will be listed as " + "'N/A' for a clinical domain, when there is no data for the domain or if there are conformance or certification feedback results.") .append("</p>") .append("<p>") .append(" <span id=\"keyErrorHeader\">Conformance Errors: </span>") .append("A Conformance Error implies that the document is non-compliant with the HL7 C-CDA IG requirements. " + "This column should have zeros ideally. " + "Providers should work with their health IT vendor to rectify the errors.") .append("</p>") .append("<p>") .append(" <span id=\"keyFeedbackHeader\">Certification Feedback: </span>") .append("A Certification Feedback result identifies areas where the generated documents are not compliant with " + "the requirements of 2015 Edition Certification. Ideally, this column should have all zeros." + "Most of these results fall into incorrect use of vocabularies and terminologies. " + "Although not as severe as a Conformance Error, providers should work with their health IT vendor " + "to address feedback provided to improve interoperable use of structured data between systems.") .append("</p>"); } private static void appendClosingHtml(StringBuffer sb) { sb.append("</body>"); sb.append("</html>"); } private static void appendHorizontalRuleWithBreaks(StringBuffer sb) { sb.append("<br />"); sb.append("<hr />"); sb.append("<br />"); } private static void appendBackToTopWithBreaks(StringBuffer sb) { // sb.append("<br />"); sb.append("<a href='#topOfScorecard'>Back to Top</a>"); // sb.append("<br />"); // A PDF conversion bug is not processing this valid HTML so commenting // out until time to address // sb.append("<a href='#heatMap'>Back to Section List</a>"); sb.append("<br />"); // sb.append("<br />"); } private static void appendErrorMessage(StringBuffer sb, String errorMessage) { sb.append("<h2 style='color:red; background-color: #ffe6e6'>"); sb.append(errorMessage); sb.append("</h2>"); if(!errorMessage.contains("HL7 CDA Schema Errors")) { sb.append("<p>" + ApplicationConstants.ErrorMessages.CONTACT + "</p>"); } } private static void appendGenericErrorMessage(StringBuffer sb) { sb.append("<p>" + ApplicationConstants.ErrorMessages.JSON_TO_JAVA_JACKSON + "<br />" + ApplicationConstants.ErrorMessages.CONTACT + "</p>"); } private static void appendErrorMessageFromReport(StringBuffer sb, ResponseTO report) { appendErrorMessageFromReport(sb, report, null); } private static void appendErrorMessageFromReport(StringBuffer sb, ResponseTO report, String extraMessage) { if (report.getErrorMessage() != null && !report.getErrorMessage().isEmpty()) { boolean hasSchemaErrors = report.getSchemaErrorList() != null && !report.getSchemaErrorList().isEmpty(); if(!hasSchemaErrors) { appendErrorMessage(sb, report.getErrorMessage()); } else { sb.append("<h3>" + ApplicationConstants.ErrorMessages.ONE_CLICK_SCHEMA_MESSAGE_PART1 + "</h3>"); sb.append("<h3>" + ApplicationConstants.ErrorMessages.ONE_CLICK_SCHEMA_MESSAGE_PART2 + "</h3>"); final String noData = "No data available"; sb.append("<ol style='color:red'>"); for(ReferenceError schemaError : report.getSchemaErrorList()) { sb.append("<li>"); sb.append("<ul>"); sb.append("<li>Message: " + (schemaError.getDescription() != null ? schemaError.getDescription() : noData)); sb.append("</li>"); sb.append("<li>Path: " + (schemaError.getxPath() != null ? schemaError.getxPath() : noData)); sb.append("</li>"); sb.append("<li>Line Number (approximate): " + (schemaError.getDocumentLineNumber() != null ? schemaError.getDocumentLineNumber() : noData)); sb.append("</li>"); sb.append("<li>xPath: " + "<xmp style='font-family: Consolas, monaco, monospace;'>" + (schemaError.getxPath() != null ? schemaError.getxPath() : noData) + "</xmp>"); sb.append("<p></p>"); sb.append("</li>"); sb.append("</ul>"); sb.append("</li>"); } sb.append("</ol>"); } } else { appendGenericErrorMessage(sb); } if (extraMessage != null && !extraMessage.isEmpty()) { sb.append("<p>" + extraMessage + "</p>"); } } protected static String ensureLogicalParseTreeInHTML(String htmlReport) { org.jsoup.nodes.Document doc = Jsoup.parse(htmlReport); String cleanHtmlReport = doc.toString(); return cleanHtmlReport; } private static void convertHTMLToPDF(String cleanHtmlReport) { convertHTMLToPDF(cleanHtmlReport, null); } private static void convertHTMLToPDF(String cleanHtmlReport, HttpServletResponse response) { OutputStream out = null; try { DocumentBuilderFactory factory = DocumentBuilderFactory .newInstance(); factory.setNamespaceAware(false); factory.setValidating(false); DocumentBuilder builder = factory.newDocumentBuilder(); Document refineddoc = builder.parse(new ByteArrayInputStream( cleanHtmlReport.getBytes("UTF-8"))); ITextRenderer renderer = new ITextRenderer(); renderer.setDocument(refineddoc, null); renderer.layout(); if(response != null) { //Stream to Output response.setContentType("application/pdf"); response.setHeader("Content-disposition", "attachment; filename=" + "scorecardReport.pdf"); response.setHeader("max-age=3600", "must-revalidate"); response.addCookie(new Cookie("fileDownload=true", "path=/")); out = response.getOutputStream(); } else { //Save to local file system out = new FileOutputStream(new File("testSaveReportImplementation.pdf")); } renderer.createPDF(out); } catch (ParserConfigurationException pcE) { pcE.printStackTrace(); } catch (SAXException saxE) { saxE.printStackTrace(); } catch (DocumentException docE) { docE.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } finally { if (out != null) { try { out.flush(); out.close(); } catch (IOException e) { e.printStackTrace(); } } if(LOG_HTML) { ApplicationUtil.debugLog("cleanHtmlReport", cleanHtmlReport); } } } protected static void convertHTMLToPDFAndStreamToOutput( String cleanHtmlReport, HttpServletResponse response) { convertHTMLToPDF(cleanHtmlReport, response); } private static void convertHTMLToPDFAndSaveToLocalFileSystem(String cleanHtmlReport) { convertHTMLToPDF(cleanHtmlReport); } /** * Converts JSON to ResponseTO Java Object using The Jackson API * * @param jsonReportData * JSON which resembles ResponseTO * @return converted ResponseTO POJO */ protected static ResponseTO convertJsonToPojo(String jsonReportData) { ObjectMapper mapper = new ObjectMapper(); ResponseTO pojo = null; try { pojo = mapper.readValue(jsonReportData, ResponseTO.class); } catch (IOException e) { e.printStackTrace(); } return pojo; } public enum SaveReportType { MATCH_UI, SUMMARY; } private static void buildReportUsingJSONFromLocalFile(String filenameWithoutExtension, SaveReportType reportType) throws URISyntaxException { URI jsonFileURI = new File( "src/main/webapp/resources/" + filenameWithoutExtension + ".json").toURI(); System.out.println("jsonFileURI"); System.out.println(jsonFileURI); String jsonReportData = convertFileToString(jsonFileURI); System.out.println("jsonReportData"); System.out.println(jsonReportData); ResponseTO pojoResponse = convertJsonToPojo(jsonReportData); System.out.println("response"); System.out.println(pojoResponse.getCcdaDocumentType()); convertHTMLToPDFAndSaveToLocalFileSystem( ensureLogicalParseTreeInHTML(convertReportToHTML(pojoResponse, reportType))); } private static String convertFileToString(URI fileURI) { StringBuilder sb = new StringBuilder(); BufferedReader br = null; try { br = new BufferedReader(new FileReader(fileURI.getPath())); String sCurrentLine = ""; while ((sCurrentLine = br.readLine()) != null) { sb.append(sCurrentLine); } } catch (Exception e) { e.printStackTrace(); } finally { try { br.close(); } catch (IOException e) { e.printStackTrace(); } } return sb.toString(); } public static void main(String[] args) { String[] filenames = {"highScoringSample", "lowScoringSample", "sampleWithErrors", "sampleWithSchemaErrors", "sampleWithoutAnyContent"}; final int HIGH_SCORING_SAMPLE = 0, LOW_SCORING_SAMPLE = 1, SAMPLE_WITH_ERRORS = 2, SAMPLE_WITH_SCHEMA_ERRORS = 3, SAMPLE_WITHOUT_ANY_CONTENT = 4; try { buildReportUsingJSONFromLocalFile(filenames[SAMPLE_WITH_ERRORS], SaveReportType.SUMMARY); } catch (URISyntaxException e) { e.printStackTrace(); } } }
Add author, subject, keywords, and language metadata for 508
src/main/java/org/sitenv/service/ccda/smartscorecard/controller/SaveReportController.java
Add author, subject, keywords, and language metadata for 508
Java
bsd-3-clause
dd84c3fa851d76c837b9df396501884f5095fc3a
0
lockss/lockss-daemon,lockss/lockss-daemon,edina/lockss-daemon,edina/lockss-daemon,lockss/lockss-daemon,lockss/lockss-daemon,edina/lockss-daemon,lockss/lockss-daemon,edina/lockss-daemon,lockss/lockss-daemon,edina/lockss-daemon,edina/lockss-daemon,edina/lockss-daemon,lockss/lockss-daemon
/* * $Id: TestOnixBooksSourceArchivalUnit.java,v 1.3 2014-01-13 19:33:31 alexandraohlson Exp $ */ /* Copyright (c) 2000-2013 Board of Trustees of Leland Stanford Jr. University, all rights reserved. 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 STANFORD UNIVERSITY 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. Except as contained in this notice, the name of Stanford University shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from Stanford University. */ package org.lockss.plugin.clockss.onixbooks; import java.net.URL; import java.util.Properties; import org.lockss.config.Configuration; import org.lockss.daemon.*; import org.lockss.plugin.*; import org.lockss.plugin.base.*; import org.lockss.plugin.definable.*; import org.lockss.test.*; import org.lockss.util.*; // // This plugin test framework is set up to run the same tests in two variants - CLOCKSS and GLN // without having to actually duplicate any of the written tests // public class TestOnixBooksSourceArchivalUnit extends LockssTestCase { private MockLockssDaemon theDaemon; static final String BASE_URL_KEY = ConfigParamDescr.BASE_URL.getKey(); static final String YEAR_KEY = ConfigParamDescr.YEAR.getKey(); static final String ROOT_URL = "http://www.sourcecontent.com/"; //this is not a real url static Logger log = Logger.getLogger("TestOnixBooksSourceArchivalUnit"); static final String PLUGIN_ID = "org.lockss.plugin.clockss.onixbooks.ClockssOnix3BooksSourcePlugin"; static final String PluginName = "ONIX 3 Books Source Plugin (CLOCKSS)"; public void setUp() throws Exception { super.setUp(); setUpDiskSpace(); theDaemon = getMockLockssDaemon(); theDaemon.getHashService(); } public void tearDown() throws Exception { super.tearDown(); } private DefinableArchivalUnit makeAu(URL url, String year) throws Exception { Properties props = new Properties(); props.setProperty(YEAR_KEY, year); if (url != null) { props.setProperty(BASE_URL_KEY, url.toString()); } Configuration config = ConfigurationUtil.fromProps(props); DefinablePlugin ap = new DefinablePlugin(); ap.initPlugin(getMockLockssDaemon(), PLUGIN_ID); DefinableArchivalUnit au = (DefinableArchivalUnit)ap.createAu(config); return au; } public void testConstructNullUrl() throws Exception { try { makeAu(null, "2012"); fail("Should have thrown ArchivalUnit.ConfigurationException"); } catch (ArchivalUnit.ConfigurationException e) { } } // // Test the crawl rules // public void testShouldCacheProperPages() throws Exception { URL base = new URL(ROOT_URL); ArchivalUnit sourceAU = makeAu(base, "2012"); theDaemon.getLockssRepository(sourceAU); theDaemon.getNodeManager(sourceAU); BaseCachedUrlSet cus = new BaseCachedUrlSet(sourceAU, new RangeCachedUrlSetSpec(base.toString())); // Test for pages that should get crawled //with a subdirectory under the year shouldCacheTest(ROOT_URL+"2012/Berghahn_Press/", true, sourceAU, cus); shouldCacheTest(ROOT_URL+"2012/Berghahn_Press/blah.xml", true, sourceAU, cus); shouldCacheTest(ROOT_URL+"2012/Berghahn_Press/blah.pdf", true, sourceAU, cus); shouldCacheTest(ROOT_URL+"2012/Berghahn_Press/blah.epub", true, sourceAU, cus); shouldCacheTest(ROOT_URL+"2012/Berghahn_Press/blah.jpg", true, sourceAU, cus); //without a subdirectory under the year shouldCacheTest(ROOT_URL+"2012/", true, sourceAU, cus); shouldCacheTest(ROOT_URL+"2012/blah.xml", true, sourceAU, cus); shouldCacheTest(ROOT_URL+"2012/blah.pdf", true, sourceAU, cus); shouldCacheTest(ROOT_URL+"2012/blah.epub", true, sourceAU, cus); shouldCacheTest(ROOT_URL+"2012/blah.jpg", true, sourceAU, cus); // Now a couple that shouldn't get crawled // md5sum file shouldCacheTest(ROOT_URL+"2012/xxxx/blah.pdf.md5sum", false, sourceAU, cus); //wrong year shouldCacheTest(ROOT_URL+"2013/xxxx/blah.pdf", false, sourceAU, cus); // too deep shouldCacheTest(ROOT_URL+"2012/Berghahn_Press/randomdirectory/blah.jpg", true, sourceAU, cus); } private void shouldCacheTest(String url, boolean shouldCache, ArchivalUnit au, CachedUrlSet cus) { UrlCacher uc = au.makeUrlCacher(url); assertEquals(shouldCache, uc.shouldBeCached()); } public void testgetName() throws Exception { DefinableArchivalUnit au = makeAu(new URL("http://www.source.com/"), "2011"); assertEquals(PluginName + ", Base URL http://www.source.com/, Year 2011", au.getName()); DefinableArchivalUnit au1 = makeAu(new URL("http://www.source.com/"), "2009"); assertEquals(PluginName + ", Base URL http://www.source.com/, Year 2009", au1.getName()); } }
plugins/test/src/org/lockss/plugin/clockss/onixbooks/TestOnixBooksSourceArchivalUnit.java
/* * $Id: TestOnixBooksSourceArchivalUnit.java,v 1.2 2013-11-13 18:47:37 alexandraohlson Exp $ */ /* Copyright (c) 2000-2013 Board of Trustees of Leland Stanford Jr. University, all rights reserved. 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 STANFORD UNIVERSITY 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. Except as contained in this notice, the name of Stanford University shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from Stanford University. */ package org.lockss.plugin.clockss.onixbooks; import java.net.URL; import java.util.Properties; import org.lockss.config.Configuration; import org.lockss.daemon.*; import org.lockss.plugin.*; import org.lockss.plugin.base.*; import org.lockss.plugin.definable.*; import org.lockss.test.*; import org.lockss.util.*; // // This plugin test framework is set up to run the same tests in two variants - CLOCKSS and GLN // without having to actually duplicate any of the written tests // public class TestOnixBooksSourceArchivalUnit extends LockssTestCase { private MockLockssDaemon theDaemon; static final String BASE_URL_KEY = ConfigParamDescr.BASE_URL.getKey(); static final String YEAR_KEY = ConfigParamDescr.YEAR.getKey(); static final String ROOT_URL = "http://www.sourcecontent.com/"; //this is not a real url static Logger log = Logger.getLogger("TestOnixBooksSourceArchivalUnit"); static final String PLUGIN_ID = "org.lockss.plugin.clockss.onixbooks.ClockssOnix3BooksSourcePlugin"; static final String PluginName = "Onix3 Books Source Plugin (CLOCKSS)"; public void setUp() throws Exception { super.setUp(); setUpDiskSpace(); theDaemon = getMockLockssDaemon(); theDaemon.getHashService(); } public void tearDown() throws Exception { super.tearDown(); } private DefinableArchivalUnit makeAu(URL url, String year) throws Exception { Properties props = new Properties(); props.setProperty(YEAR_KEY, year); if (url != null) { props.setProperty(BASE_URL_KEY, url.toString()); } Configuration config = ConfigurationUtil.fromProps(props); DefinablePlugin ap = new DefinablePlugin(); ap.initPlugin(getMockLockssDaemon(), PLUGIN_ID); DefinableArchivalUnit au = (DefinableArchivalUnit)ap.createAu(config); return au; } public void testConstructNullUrl() throws Exception { try { makeAu(null, "2012"); fail("Should have thrown ArchivalUnit.ConfigurationException"); } catch (ArchivalUnit.ConfigurationException e) { } } // // Test the crawl rules // public void testShouldCacheProperPages() throws Exception { URL base = new URL(ROOT_URL); ArchivalUnit sourceAU = makeAu(base, "2012"); theDaemon.getLockssRepository(sourceAU); theDaemon.getNodeManager(sourceAU); BaseCachedUrlSet cus = new BaseCachedUrlSet(sourceAU, new RangeCachedUrlSetSpec(base.toString())); // Test for pages that should get crawled //with a subdirectory under the year shouldCacheTest(ROOT_URL+"2012/Berghahn_Press/", true, sourceAU, cus); shouldCacheTest(ROOT_URL+"2012/Berghahn_Press/blah.xml", true, sourceAU, cus); shouldCacheTest(ROOT_URL+"2012/Berghahn_Press/blah.pdf", true, sourceAU, cus); shouldCacheTest(ROOT_URL+"2012/Berghahn_Press/blah.epub", true, sourceAU, cus); shouldCacheTest(ROOT_URL+"2012/Berghahn_Press/blah.jpg", true, sourceAU, cus); //without a subdirectory under the year shouldCacheTest(ROOT_URL+"2012/", true, sourceAU, cus); shouldCacheTest(ROOT_URL+"2012/blah.xml", true, sourceAU, cus); shouldCacheTest(ROOT_URL+"2012/blah.pdf", true, sourceAU, cus); shouldCacheTest(ROOT_URL+"2012/blah.epub", true, sourceAU, cus); shouldCacheTest(ROOT_URL+"2012/blah.jpg", true, sourceAU, cus); // Now a couple that shouldn't get crawled // md5sum file shouldCacheTest(ROOT_URL+"2012/xxxx/blah.pdf.md5sum", false, sourceAU, cus); //wrong year shouldCacheTest(ROOT_URL+"2013/xxxx/blah.pdf", false, sourceAU, cus); // too deep shouldCacheTest(ROOT_URL+"2012/Berghahn_Press/randomdirectory/blah.jpg", true, sourceAU, cus); } private void shouldCacheTest(String url, boolean shouldCache, ArchivalUnit au, CachedUrlSet cus) { UrlCacher uc = au.makeUrlCacher(url); assertEquals(shouldCache, uc.shouldBeCached()); } public void testgetName() throws Exception { DefinableArchivalUnit au = makeAu(new URL("http://www.source.com/"), "2011"); assertEquals(PluginName + ", Base URL http://www.source.com/, Year 2011", au.getName()); DefinableArchivalUnit au1 = makeAu(new URL("http://www.source.com/"), "2009"); assertEquals(PluginName + ", Base URL http://www.source.com/, Year 2009", au1.getName()); } }
update test to handle updated plugin name git-svn-id: 293778eaa97c8c94097d610b1bd5133a8f478f36@32023 4f837ed2-42f5-46e7-a7a5-fa17313484d4
plugins/test/src/org/lockss/plugin/clockss/onixbooks/TestOnixBooksSourceArchivalUnit.java
update test to handle updated plugin name
Java
bsd-3-clause
287c53379524f2c0038e33be75a0573e26d3cc7e
0
vivo-project/Vitro,vivo-project/Vitro,vivo-project/Vitro,vivo-project/Vitro
/* $This file is distributed under the terms of the license in /doc/license.txt$ */ package edu.cornell.mannlib.vitro.webapp.dao.jena; import java.util.ArrayList; import java.util.List; import com.hp.hpl.jena.ontology.OntModel; import com.hp.hpl.jena.rdf.listeners.StatementListener; import com.hp.hpl.jena.rdf.model.Literal; import com.hp.hpl.jena.rdf.model.NodeIterator; import com.hp.hpl.jena.rdf.model.Property; import com.hp.hpl.jena.rdf.model.RDFNode; import com.hp.hpl.jena.rdf.model.ResourceFactory; import com.hp.hpl.jena.rdf.model.Statement; import edu.cornell.mannlib.vitro.webapp.beans.Portal; import edu.cornell.mannlib.vitro.webapp.dao.ApplicationDao; import edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary; public class ApplicationDaoJena extends JenaBaseDao implements ApplicationDao { private static final Property LINKED_NAMESPACE_PROP = ResourceFactory.createProperty( VitroVocabulary.DISPLAY + "linkedNamespace"); Integer portalCount = null; List<String> externallyLinkedNamespaces = null; public ApplicationDaoJena(WebappDaoFactoryJena wadf) { super(wadf); getOntModelSelector().getDisplayModel().register( new ExternalNamespacesChangeListener()); } public boolean isFlag1Active() { boolean somePortalIsFiltering=false; if (portalCount == null) { boolean active = false; for (Portal p : getWebappDaoFactory().getPortalDao().getAllPortals()) { if (p.isFlag1Filtering()) { somePortalIsFiltering = true; } } } return somePortalIsFiltering && getWebappDaoFactory().getPortalDao().getAllPortals().size() > 1; } public boolean isFlag2Active() { return (getFlag2ValueMap().isEmpty()) ? false : true; } private static final boolean CLEAR_CACHE = true; public synchronized List<String> getExternallyLinkedNamespaces() { return getExternallyLinkedNamespaces(!CLEAR_CACHE); } public synchronized List<String> getExternallyLinkedNamespaces(boolean clearCache) { if (clearCache || externallyLinkedNamespaces == null) { externallyLinkedNamespaces = new ArrayList<String>(); OntModel ontModel = getOntModelSelector().getDisplayModel(); NodeIterator nodes = ontModel.listObjectsOfProperty(LINKED_NAMESPACE_PROP); while (nodes.hasNext()) { RDFNode node = nodes.next(); if (node.isLiteral()) { String namespace = ((Literal)node).getLexicalForm(); // org.openrdf.model.impl.URIImpl.URIImpl.getNamespace() returns a // namespace with a final slash, so this makes matching easier. // It also accords with the way the default namespace is defined. if (!namespace.endsWith("/")) { namespace = namespace + "/"; } externallyLinkedNamespaces.add(namespace); } } } return externallyLinkedNamespaces; } private class ExternalNamespacesChangeListener extends StatementListener { @Override public void addedStatement(Statement stmt) { process(stmt); } @Override public void removedStatement(Statement stmt) { process(stmt); } //We could also listen for end-of-edit events, //but there should be so few of these statments that //it won't be very expensive to run this method multiple //times when the model is updated. private void process(Statement stmt) { if (stmt.getPredicate().equals(LINKED_NAMESPACE_PROP)) { getExternallyLinkedNamespaces(CLEAR_CACHE); } } } }
webapp/src/edu/cornell/mannlib/vitro/webapp/dao/jena/ApplicationDaoJena.java
/* $This file is distributed under the terms of the license in /doc/license.txt$ */ package edu.cornell.mannlib.vitro.webapp.dao.jena; import java.util.ArrayList; import java.util.List; import com.hp.hpl.jena.ontology.OntModel; import com.hp.hpl.jena.rdf.listeners.StatementListener; import com.hp.hpl.jena.rdf.model.Literal; import com.hp.hpl.jena.rdf.model.NodeIterator; import com.hp.hpl.jena.rdf.model.Property; import com.hp.hpl.jena.rdf.model.RDFNode; import com.hp.hpl.jena.rdf.model.ResourceFactory; import com.hp.hpl.jena.rdf.model.Statement; import edu.cornell.mannlib.vitro.webapp.beans.Portal; import edu.cornell.mannlib.vitro.webapp.dao.ApplicationDao; import edu.cornell.mannlib.vitro.webapp.dao.VitroVocabulary; public class ApplicationDaoJena extends JenaBaseDao implements ApplicationDao { Property LINKED_NAMESPACE_PROP = ResourceFactory.createProperty( VitroVocabulary.DISPLAY + "linkedNamespace"); Integer portalCount = null; List<String> externallyLinkedNamespaces = null; public ApplicationDaoJena(WebappDaoFactoryJena wadf) { super(wadf); getOntModelSelector().getDisplayModel().register( new ExternalNamespacesChangeListener()); } public boolean isFlag1Active() { boolean somePortalIsFiltering=false; if (portalCount == null) { boolean active = false; for (Portal p : getWebappDaoFactory().getPortalDao().getAllPortals()) { if (p.isFlag1Filtering()) { somePortalIsFiltering = true; } } } return somePortalIsFiltering && getWebappDaoFactory().getPortalDao().getAllPortals().size() > 1; } public boolean isFlag2Active() { return (getFlag2ValueMap().isEmpty()) ? false : true; } private static final boolean CLEAR_CACHE = true; public synchronized List<String> getExternallyLinkedNamespaces() { return getExternallyLinkedNamespaces(!CLEAR_CACHE); } public synchronized List<String> getExternallyLinkedNamespaces(boolean clearCache) { if (clearCache || externallyLinkedNamespaces == null) { externallyLinkedNamespaces = new ArrayList<String>(); OntModel ontModel = getOntModelSelector().getDisplayModel(); NodeIterator nodes = ontModel.listObjectsOfProperty(LINKED_NAMESPACE_PROP); while (nodes.hasNext()) { RDFNode node = nodes.next(); if (node.isLiteral()) { String namespace = ((Literal)node).getLexicalForm(); // org.openrdf.model.impl.URIImpl.URIImpl.getNamespace() returns a // namespace with a final slash, so this makes matching easier. // It also accords with the way the default namespace is defined. if (!namespace.endsWith("/")) { namespace = namespace + "/"; } externallyLinkedNamespaces.add(namespace); } } } return externallyLinkedNamespaces; } private class ExternalNamespacesChangeListener extends StatementListener { @Override public void addedStatement(Statement stmt) { process(stmt); } @Override public void removedStatement(Statement stmt) { process(stmt); } //We could also listen for end-of-edit events, //but there should be so few of these statments that //it won't be very expensive to run this method multiple //times when the model is updated. private void process(Statement stmt) { if (stmt.getPredicate().equals(LINKED_NAMESPACE_PROP)) { getExternallyLinkedNamespaces(CLEAR_CACHE); } } } }
NIHVIVO-1193 listener to update externally-linked namespaces
webapp/src/edu/cornell/mannlib/vitro/webapp/dao/jena/ApplicationDaoJena.java
NIHVIVO-1193 listener to update externally-linked namespaces
Java
bsd-3-clause
c7c1a22bae08b75c7c3183a31e149b48943fc4ba
0
darklordwonton/ElementsOfPower
package gigaherz.elementsofpower.client.renderers; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Maps; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.Tessellator; import net.minecraft.client.renderer.VertexBuffer; import net.minecraft.client.renderer.block.model.BakedQuad; import net.minecraft.client.renderer.block.model.IBakedModel; import net.minecraft.client.renderer.vertex.DefaultVertexFormats; import net.minecraft.client.renderer.vertex.VertexFormat; import net.minecraft.client.resources.IReloadableResourceManager; import net.minecraft.client.resources.IResourceManager; import net.minecraft.client.resources.IResourceManagerReloadListener; import net.minecraft.crash.CrashReport; import net.minecraft.util.ReportedException; import net.minecraft.util.ResourceLocation; import net.minecraftforge.client.model.*; import net.minecraftforge.client.model.pipeline.LightUtil; import org.lwjgl.opengl.GL11; import javax.annotation.Nonnull; import java.util.Map; public class ModelHandle { static Map<String, IBakedModel> loadedModels = Maps.newHashMap(); private String model; private String key; private final Map<String, String> textureReplacements = Maps.newHashMap(); private VertexFormat vertexFormat = Attributes.DEFAULT_BAKED_FORMAT; private ModelHandle(String model) { this.model = model; this.key = model; } public ModelHandle replace(String texChannel, String resloc) { key += "//" + texChannel + "/" + resloc; textureReplacements.put(texChannel, resloc); return this; } public ModelHandle vertexFormat(VertexFormat fmt) { key += "//VF:" + fmt.hashCode(); vertexFormat = fmt; return this; } public String getModel() { return model; } public String getKey() { return key; } public Map<String, String> getTextureReplacements() { return textureReplacements; } public VertexFormat getVertexFormat() { return vertexFormat; } public IBakedModel get() { return loadModel(this); } // ========================================================= STATIC METHODS public static void init() { IResourceManager rm = Minecraft.getMinecraft().getResourceManager(); if (rm instanceof IReloadableResourceManager) { ((IReloadableResourceManager) rm).registerReloadListener(new IResourceManagerReloadListener() { @Override public void onResourceManagerReload(IResourceManager __) { loadedModels.clear(); } }); } } @Nonnull public static ModelHandle of(String model) { return new ModelHandle(model); } public static void renderModel(IBakedModel model) { renderModel(model, DefaultVertexFormats.ITEM); } public static void renderModel(IBakedModel model, VertexFormat fmt) { Tessellator tessellator = Tessellator.getInstance(); VertexBuffer worldrenderer = tessellator.getBuffer(); worldrenderer.begin(GL11.GL_QUADS, fmt); for (BakedQuad bakedquad : model.getQuads(null, null, 0)) { worldrenderer.addVertexData(bakedquad.getVertexData()); } tessellator.draw(); } public static void renderModel(IBakedModel model, int color) { Tessellator tessellator = Tessellator.getInstance(); VertexBuffer worldrenderer = tessellator.getBuffer(); worldrenderer.begin(GL11.GL_QUADS, DefaultVertexFormats.ITEM); for (BakedQuad bakedquad : model.getQuads(null, null, 0)) { LightUtil.renderQuadColor(worldrenderer, bakedquad, color); } tessellator.draw(); } private static IBakedModel loadModel(ModelHandle handle) { IBakedModel model = loadedModels.get(handle.getKey()); if (model != null) return model; try { IModel mod = ModelLoaderRegistry.getModel(new ResourceLocation(handle.getModel())); if (mod instanceof IRetexturableModel && handle.getTextureReplacements().size() > 0) { IRetexturableModel rtm = (IRetexturableModel) mod; mod = rtm.retexture(ImmutableMap.copyOf(handle.getTextureReplacements())); } model = mod.bake(mod.getDefaultState(), handle.getVertexFormat(), ModelLoader.defaultTextureGetter()); loadedModels.put(handle.getKey(), model); return model; } catch (Exception e) { throw new ReportedException(new CrashReport("Error loading custom model " + handle.getModel(), e)); } } }
src/main/java/gigaherz/elementsofpower/client/renderers/ModelHandle.java
package gigaherz.elementsofpower.client.renderers; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Maps; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.Tessellator; import net.minecraft.client.renderer.VertexBuffer; import net.minecraft.client.renderer.block.model.BakedQuad; import net.minecraft.client.renderer.block.model.IBakedModel; import net.minecraft.client.renderer.vertex.DefaultVertexFormats; import net.minecraft.client.renderer.vertex.VertexFormat; import net.minecraft.client.resources.IReloadableResourceManager; import net.minecraft.client.resources.IResourceManager; import net.minecraft.client.resources.IResourceManagerReloadListener; import net.minecraft.crash.CrashReport; import net.minecraft.util.ReportedException; import net.minecraft.util.ResourceLocation; import net.minecraftforge.client.model.*; import net.minecraftforge.client.model.pipeline.LightUtil; import org.lwjgl.opengl.GL11; import javax.annotation.Nonnull; import java.util.Map; public class ModelHandle { static Map<String, IBakedModel> loadedModels = Maps.newHashMap(); private String model; private String key; private final Map<String, String> textureReplacements = Maps.newHashMap(); private VertexFormat vertexFormat = Attributes.DEFAULT_BAKED_FORMAT; private ModelHandle(String model) { this.model = model; this.key = model; } public ModelHandle replace(String texChannel, String resloc) { key += "//" + texChannel + "/" + resloc; textureReplacements.put(texChannel, resloc); return this; } public ModelHandle vertexFormat(VertexFormat fmt) { key += "//VF:" + fmt.hashCode(); vertexFormat = fmt; return this; } public String getModel() { return model; } public String getKey() { return key; } public Map<String, String> getTextureReplacements() { return textureReplacements; } public VertexFormat getVertexFormat() { return vertexFormat; } public void setVertexFormat(VertexFormat vertexFormat) { this.vertexFormat = vertexFormat; } public IBakedModel get() { return loadModel(this); } // ========================================================= STATIC METHODS public static void init() { IResourceManager rm = Minecraft.getMinecraft().getResourceManager(); if (rm instanceof IReloadableResourceManager) { ((IReloadableResourceManager) rm).registerReloadListener(new IResourceManagerReloadListener() { @Override public void onResourceManagerReload(IResourceManager __) { loadedModels.clear(); } }); } } @Nonnull public static ModelHandle of(String model) { return new ModelHandle(model); } public static void renderModel(IBakedModel model) { renderModel(model, DefaultVertexFormats.ITEM); } public static void renderModel(IBakedModel model, VertexFormat fmt) { Tessellator tessellator = Tessellator.getInstance(); VertexBuffer worldrenderer = tessellator.getBuffer(); worldrenderer.begin(GL11.GL_QUADS, fmt); for (BakedQuad bakedquad : model.getQuads(null, null, 0)) { worldrenderer.addVertexData(bakedquad.getVertexData()); } tessellator.draw(); } public static void renderModel(IBakedModel model, int color) { Tessellator tessellator = Tessellator.getInstance(); VertexBuffer worldrenderer = tessellator.getBuffer(); worldrenderer.begin(GL11.GL_QUADS, DefaultVertexFormats.ITEM); for (BakedQuad bakedquad : model.getQuads(null, null, 0)) { LightUtil.renderQuadColor(worldrenderer, bakedquad, color); } tessellator.draw(); } private static IBakedModel loadModel(ModelHandle handle) { IBakedModel model = loadedModels.get(handle.getKey()); if (model != null) return model; try { IModel mod = ModelLoaderRegistry.getModel(new ResourceLocation(handle.getModel())); if (mod instanceof IRetexturableModel && handle.getTextureReplacements().size() > 0) { IRetexturableModel rtm = (IRetexturableModel) mod; mod = rtm.retexture(ImmutableMap.copyOf(handle.getTextureReplacements())); } model = mod.bake(mod.getDefaultState(), handle.getVertexFormat(), ModelLoader.defaultTextureGetter()); loadedModels.put(handle.getKey(), model); return model; } catch (Exception e) { throw new ReportedException(new CrashReport("Error loading custom model " + handle.getModel(), e)); } } }
Remove derp from using the IDE to autogenerate accessors.
src/main/java/gigaherz/elementsofpower/client/renderers/ModelHandle.java
Remove derp from using the IDE to autogenerate accessors.
Java
mit
cee6b683119db56130352b5e034c02ab51d83b76
0
EduardoHFreitas/ExemplosJavaSE
package br.univel; import java.awt.BorderLayout; import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; import java.awt.GridBagLayout; import javax.swing.JScrollPane; import java.awt.GridBagConstraints; import javax.swing.JTable; import javax.swing.JButton; import java.awt.Insets; import java.awt.Point; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.math.BigDecimal; import java.text.NumberFormat; import java.util.ArrayList; import java.util.List; import java.util.Locale; public class TelaTabela extends JFrame { private JPanel contentPane; private JTable table; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { TelaTabela frame = new TelaTabela(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the frame. */ public TelaTabela() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 450, 300); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); GridBagLayout gbl_contentPane = new GridBagLayout(); gbl_contentPane.columnWidths = new int[] { 0, 0 }; gbl_contentPane.rowHeights = new int[] { 0, 0, 0, 0, 0 }; gbl_contentPane.columnWeights = new double[] { 1.0, Double.MIN_VALUE }; gbl_contentPane.rowWeights = new double[] { 0.0, 0.0, 0.0, 1.0, Double.MIN_VALUE }; contentPane.setLayout(gbl_contentPane); JButton btnNewButton = new JButton("Preenche"); btnNewButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { preencheTabela(); } }); GridBagConstraints gbc_btnNewButton = new GridBagConstraints(); gbc_btnNewButton.insets = new Insets(0, 0, 5, 0); gbc_btnNewButton.gridx = 0; gbc_btnNewButton.gridy = 0; contentPane.add(btnNewButton, gbc_btnNewButton); JButton btnRemove = new JButton("Remove"); btnRemove.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { removerSelecionado(); } }); GridBagConstraints gbc_btnRemove = new GridBagConstraints(); gbc_btnRemove.insets = new Insets(0, 0, 5, 0); gbc_btnRemove.gridx = 0; gbc_btnRemove.gridy = 1; contentPane.add(btnRemove, gbc_btnRemove); JButton btnAdiciona = new JButton("Adiciona"); btnAdiciona.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { adicionarDoAlem(); } }); GridBagConstraints gbc_btnAdiciona = new GridBagConstraints(); gbc_btnAdiciona.insets = new Insets(0, 0, 5, 0); gbc_btnAdiciona.gridx = 0; gbc_btnAdiciona.gridy = 2; contentPane.add(btnAdiciona, gbc_btnAdiciona); JScrollPane scrollPane = new JScrollPane(); GridBagConstraints gbc_scrollPane = new GridBagConstraints(); gbc_scrollPane.fill = GridBagConstraints.BOTH; gbc_scrollPane.gridx = 0; gbc_scrollPane.gridy = 3; contentPane.add(scrollPane, gbc_scrollPane); table = new JTable() { @Override public String getToolTipText(MouseEvent e) { String tip = null; Point p = e.getPoint(); int rowIndex = rowAtPoint(p); int colIndex = columnAtPoint(p); if (rowIndex == -1 || colIndex == -1) { return null; } try { tip = getValueAt(rowIndex, colIndex).toString(); } catch (RuntimeException e1) { } return tip; } }; scrollPane.setViewportView(table); // final configuraTabela(); } protected void adicionarDoAlem() { Produto c = new Produto(123, "Treta", new BigDecimal(15)); ((ProdutoModel)table.getModel()).adicionarProduto(c); } protected void removerSelecionado() { Produto c = getProdutoSelecionadoNaTabela(); if (c != null) { ((ProdutoModel)table.getModel()).removerProduto(c); } } private void configuraTabela() { table.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if (e.getClickCount() == 2) { Produto c = getProdutoSelecionadoNaTabela(); if (c != null) { JOptionPane.showMessageDialog(null, "Produto: " + c.toString()); } } } }); } protected void preencheTabela() { /* List<Produto> lista = new ArrayList<>(); for (int i = 0; i < 10; i++) { lista.add(new Produto(i, "Produto ", new BigDecimal(0))); } */ ReaderURL reader = new ReaderURL(); List<String> lista = reader.lerUrl(); // ReaderArquivo reader = new ReaderArquivo(); // List<String> lista = reader.lerArquivo(); ProdutoParser parser = new ProdutoParser(); List<Produto> listaPrd = parser.getProduto(lista); NumberFormat formatUS = NumberFormat.getCurrencyInstance(new Locale("en", "US")); NumberFormat formatBR = NumberFormat.getCurrencyInstance(new Locale("pt", "BR")); BigDecimal cotacao = new BigDecimal(3.37); /* formato para valores MONETARIOS*/ ProdutoModel model = new ProdutoModel(listaPrd); table.setModel(model); } private Produto getProdutoSelecionadoNaTabela() { Produto c = null; int index = table.getSelectedRow(); if (index == -1) { JOptionPane.showMessageDialog(null, "Nenhuma linha selecionada!"); } else { c = ((ProdutoModel) table.getModel()).getProdutoNaLinha(index); } return c; } }
CadastroImport/src/br/univel/TelaTabela.java
package br.univel; import java.awt.BorderLayout; import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; import java.awt.GridBagLayout; import javax.swing.JScrollPane; import java.awt.GridBagConstraints; import javax.swing.JTable; import javax.swing.JButton; import java.awt.Insets; import java.awt.Point; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; public class TelaTabela extends JFrame { private JPanel contentPane; private JTable table; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { TelaTabela frame = new TelaTabela(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the frame. */ public TelaTabela() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 450, 300); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); GridBagLayout gbl_contentPane = new GridBagLayout(); gbl_contentPane.columnWidths = new int[] { 0, 0 }; gbl_contentPane.rowHeights = new int[] { 0, 0, 0, 0, 0 }; gbl_contentPane.columnWeights = new double[] { 1.0, Double.MIN_VALUE }; gbl_contentPane.rowWeights = new double[] { 0.0, 0.0, 0.0, 1.0, Double.MIN_VALUE }; contentPane.setLayout(gbl_contentPane); JButton btnNewButton = new JButton("Preenche"); btnNewButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { preencheTabela(); } }); GridBagConstraints gbc_btnNewButton = new GridBagConstraints(); gbc_btnNewButton.insets = new Insets(0, 0, 5, 0); gbc_btnNewButton.gridx = 0; gbc_btnNewButton.gridy = 0; contentPane.add(btnNewButton, gbc_btnNewButton); JButton btnRemove = new JButton("Remove"); btnRemove.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { removerSelecionado(); } }); GridBagConstraints gbc_btnRemove = new GridBagConstraints(); gbc_btnRemove.insets = new Insets(0, 0, 5, 0); gbc_btnRemove.gridx = 0; gbc_btnRemove.gridy = 1; contentPane.add(btnRemove, gbc_btnRemove); JButton btnAdiciona = new JButton("Adiciona"); btnAdiciona.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { adicionarDoAlem(); } }); GridBagConstraints gbc_btnAdiciona = new GridBagConstraints(); gbc_btnAdiciona.insets = new Insets(0, 0, 5, 0); gbc_btnAdiciona.gridx = 0; gbc_btnAdiciona.gridy = 2; contentPane.add(btnAdiciona, gbc_btnAdiciona); JScrollPane scrollPane = new JScrollPane(); GridBagConstraints gbc_scrollPane = new GridBagConstraints(); gbc_scrollPane.fill = GridBagConstraints.BOTH; gbc_scrollPane.gridx = 0; gbc_scrollPane.gridy = 3; contentPane.add(scrollPane, gbc_scrollPane); table = new JTable() { @Override public String getToolTipText(MouseEvent e) { String tip = null; Point p = e.getPoint(); int rowIndex = rowAtPoint(p); int colIndex = columnAtPoint(p); if (rowIndex == -1 || colIndex == -1) { return null; } try { tip = getValueAt(rowIndex, colIndex).toString(); } catch (RuntimeException e1) { } return tip; } }; scrollPane.setViewportView(table); // final configuraTabela(); } protected void adicionarDoAlem() { Produto c = new Produto(123, "Treta", new BigDecimal(15)); ((ProdutoModel)table.getModel()).adicionarProduto(c); } protected void removerSelecionado() { Produto c = getProdutoSelecionadoNaTabela(); if (c != null) { ((ProdutoModel)table.getModel()).removerProduto(c); } } private void configuraTabela() { table.addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { if (e.getClickCount() == 2) { Produto c = getProdutoSelecionadoNaTabela(); if (c != null) { JOptionPane.showMessageDialog(null, "Produto: " + c.toString()); } } } }); } protected void preencheTabela() { List<Produto> lista = new ArrayList<>(); for (int i = 0; i < 10; i++) { lista.add(new Produto(i, "Produto ", new BigDecimal(0))); } ProdutoModel model = new ProdutoModel(lista); table.setModel(model); } private Produto getProdutoSelecionadoNaTabela() { Produto c = null; int index = table.getSelectedRow(); if (index == -1) { JOptionPane.showMessageDialog(null, "Nenhuma linha selecionada!"); } else { c = ((ProdutoModel) table.getModel()).getProdutoNaLinha(index); } return c; } }
deu bom
CadastroImport/src/br/univel/TelaTabela.java
deu bom
Java
mit
760da43742c28f6c4998205d6af407c4aa998076
0
stachon/XChange,andre77/XChange,nopy/XChange,timmolter/XChange,LeonidShamis/XChange,npomfret/XChange,gaborkolozsy/XChange,evdubs/XChange,ww3456/XChange,Panchen/XChange,chrisrico/XChange,douggie/XChange,TSavo/XChange
package org.knowm.xchange.examples.bittrex.v1.trade; import java.io.IOException; import java.math.BigDecimal; import org.knowm.xchange.Exchange; import org.knowm.xchange.bittrex.v1.service.BittrexTradeServiceRaw; import org.knowm.xchange.currency.CurrencyPair; import org.knowm.xchange.dto.Order.OrderType; import org.knowm.xchange.dto.trade.LimitOrder; import org.knowm.xchange.examples.bittrex.v1.BittrexExamplesUtils; import org.knowm.xchange.service.trade.TradeService; public class BittrexTradeDemo { public static void main(String[] args) throws IOException { Exchange exchange = BittrexExamplesUtils.getExchange(); TradeService tradeService = exchange.getTradeService(); generic(tradeService); raw((BittrexTradeServiceRaw) tradeService); } private static void generic(TradeService tradeService) throws IOException { CurrencyPair pair = new CurrencyPair("ZET", "BTC"); LimitOrder limitOrder = new LimitOrder.Builder(OrderType.BID, pair).limitPrice(new BigDecimal("0.00001000")).tradableAmount(new BigDecimal("100")) .build(); try { String uuid = tradeService.placeLimitOrder(limitOrder); System.out.println("Order successfully placed. ID=" + uuid); Thread.sleep(7000); // wait for order to propagate System.out.println(); System.out.println(tradeService.getOpenOrders()); System.out.println("Attempting to cancel order " + uuid); boolean cancelled = tradeService.cancelOrder(uuid); if (cancelled) { System.out.println("Order successfully canceled."); } else { System.out.println("Order not successfully canceled."); } Thread.sleep(7000); // wait for cancellation to propagate System.out.println(); System.out.println(tradeService.getOpenOrders()); } catch (Exception e) { e.printStackTrace(); } } private static void raw(BittrexTradeServiceRaw tradeService) throws IOException { CurrencyPair pair = new CurrencyPair("ZET", "BTC"); LimitOrder limitOrder = new LimitOrder.Builder(OrderType.BID, pair).limitPrice(new BigDecimal("0.00001000")).tradableAmount(new BigDecimal("100")) .build(); try { String uuid = tradeService.placeBittrexLimitOrder(limitOrder); System.out.println("Order successfully placed. ID=" + uuid); Thread.sleep(7000); // wait for order to propagate System.out.println(); System.out.println(tradeService.getBittrexOpenOrders(null)); System.out.println("Attempting to cancel order " + uuid); boolean cancelled = tradeService.cancelBittrexLimitOrder(uuid); if (cancelled) { System.out.println("Order successfully canceled."); } else { System.out.println("Order not successfully canceled."); } Thread.sleep(7000); // wait for cancellation to propagate System.out.println(); System.out.println(tradeService.getBittrexOpenOrders(null)); } catch (Exception e) { e.printStackTrace(); } } }
xchange-examples/src/main/java/org/knowm/xchange/examples/bittrex/v1/trade/BittrexTradeDemo.java
package org.knowm.xchange.examples.bittrex.v1.trade; import java.io.IOException; import java.math.BigDecimal; import org.knowm.xchange.Exchange; import org.knowm.xchange.bittrex.v1.service.BittrexTradeServiceRaw; import org.knowm.xchange.currency.CurrencyPair; import org.knowm.xchange.dto.Order.OrderType; import org.knowm.xchange.dto.trade.LimitOrder; import org.knowm.xchange.examples.bittrex.v1.BittrexExamplesUtils; import org.knowm.xchange.service.trade.TradeService; public class BittrexTradeDemo { public static void main(String[] args) throws IOException { Exchange exchange = BittrexExamplesUtils.getExchange(); TradeService tradeService = exchange.getTradeService(); generic(tradeService); raw((BittrexTradeServiceRaw) tradeService); } private static void generic(TradeService tradeService) throws IOException { CurrencyPair pair = new CurrencyPair("ZET", "BTC"); LimitOrder limitOrder = new LimitOrder.Builder(OrderType.BID, pair).limitPrice(new BigDecimal("0.00001000")).tradableAmount(new BigDecimal("100")) .build(); try { String uuid = tradeService.placeLimitOrder(limitOrder); System.out.println("Order successfully placed. ID=" + uuid); Thread.sleep(7000); // wait for order to propagate System.out.println(); System.out.println(tradeService.getOpenOrders()); System.out.println("Attempting to cancel order " + uuid); boolean cancelled = tradeService.cancelOrder(uuid); if (cancelled) { System.out.println("Order successfully canceled."); } else { System.out.println("Order not successfully canceled."); } Thread.sleep(7000); // wait for cancellation to propagate System.out.println(); System.out.println(tradeService.getOpenOrders()); } catch (Exception e) { e.printStackTrace(); } } private static void raw(BittrexTradeServiceRaw tradeService) throws IOException { CurrencyPair pair = new CurrencyPair("ZET", "BTC"); LimitOrder limitOrder = new LimitOrder.Builder(OrderType.BID, pair).limitPrice(new BigDecimal("0.00001000")).tradableAmount(new BigDecimal("100")) .build(); try { String uuid = tradeService.placeBittrexLimitOrder(limitOrder); System.out.println("Order successfully placed. ID=" + uuid); Thread.sleep(7000); // wait for order to propagate System.out.println(); System.out.println(tradeService.getBittrexOpenOrders()); System.out.println("Attempting to cancel order " + uuid); boolean cancelled = tradeService.cancelBittrexLimitOrder(uuid); if (cancelled) { System.out.println("Order successfully canceled."); } else { System.out.println("Order not successfully canceled."); } Thread.sleep(7000); // wait for cancellation to propagate System.out.println(); System.out.println(tradeService.getBittrexOpenOrders()); } catch (Exception e) { e.printStackTrace(); } } }
another build fix
xchange-examples/src/main/java/org/knowm/xchange/examples/bittrex/v1/trade/BittrexTradeDemo.java
another build fix
Java
mit
793ecb4569633d297f7f407ad4bc76802ffbabd4
0
Vlatombe/git-plugin,kzantow/git-plugin,mlgiroux/git-plugin,martinda/git-plugin,ivan-fedorov/git-plugin,mlgiroux/git-plugin,bjacklyn/git-plugin,avdv/git-plugin,KostyaSha/git-plugin,KostyaSha/git-plugin,jenkinsci/git-plugin,Vlatombe/git-plugin,Deveo/git-plugin,martinda/git-plugin,ydubreuil/git-plugin,ndeloof/git-plugin,Talend/git-plugin,martinda/git-plugin,Deveo/git-plugin,jacob-keller/git-plugin,v1v/git-plugin,MarkEWaite/git-plugin,kzantow/git-plugin,loomchild/git-plugin,abaditsegay/git-plugin,kzantow/git-plugin,ldtkms/git-plugin,ldtkms/git-plugin,abaditsegay/git-plugin,recena/git-plugin,jenkinsci/git-plugin,ydubreuil/git-plugin,pauxus/git-plugin,Jellyvision/git-plugin,loomchild/git-plugin,mklein0/git-plugin,jenkinsci/git-plugin,recena/git-plugin,nordstrand/git-plugin,MarkEWaite/git-plugin,ialbors/git-plugin,nKey/git-plugin,nKey/git-plugin,Talend/git-plugin,bjacklyn/git-plugin,pauxus/git-plugin,ialbors/git-plugin,jacob-keller/git-plugin,nordstrand/git-plugin,PinguinAG/git-plugin,nordstrand/git-plugin,PinguinAG/git-plugin,avdv/git-plugin,Deveo/git-plugin,sgargan/git-plugin,mklein0/git-plugin,sgargan/git-plugin,ndeloof/git-plugin,Nonymus/git-plugin,Vlatombe/git-plugin,jenkinsci/git-plugin,MarkEWaite/git-plugin,mlgiroux/git-plugin,Talend/git-plugin,Nonymus/git-plugin,Jellyvision/git-plugin,jacob-keller/git-plugin,recena/git-plugin,abaditsegay/git-plugin,sgargan/git-plugin,ydubreuil/git-plugin,Nonymus/git-plugin,ivan-fedorov/git-plugin,v1v/git-plugin,nKey/git-plugin,mklein0/git-plugin,loomchild/git-plugin,ivan-fedorov/git-plugin,v1v/git-plugin,MarkEWaite/git-plugin,ldtkms/git-plugin,avdv/git-plugin,pauxus/git-plugin,Jellyvision/git-plugin,bjacklyn/git-plugin,ndeloof/git-plugin
package hudson.plugins.git.util; import hudson.Extension; import hudson.model.TaskListener; import hudson.plugins.git.Branch; import hudson.plugins.git.BranchSpec; import hudson.plugins.git.GitException; import hudson.plugins.git.GitSCM; import hudson.plugins.git.IGitAPI; import hudson.plugins.git.Revision; import org.kohsuke.stapler.DataBoundConstructor; import org.eclipse.jgit.lib.ObjectId; import java.io.IOException; import java.text.MessageFormat; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.Set; import static java.util.Collections.emptyList; public class DefaultBuildChooser extends BuildChooser { @DataBoundConstructor public DefaultBuildChooser() { } /** * Determines which Revisions to build. * * If only one branch is chosen and only one repository is listed, then * just attempt to find the latest revision number for the chosen branch. * * If multiple branches are selected or the branches include wildcards, then * use the advanced usecase as defined in the getAdvancedCandidateRevisons * method. * * @throws IOException * @throws GitException */ public Collection<Revision> getCandidateRevisions(boolean isPollCall, String singleBranch, IGitAPI git, TaskListener listener, BuildData data) throws GitException, IOException { verbose(listener,"getCandidateRevisions({0},{1},,,{2}) considering branches to build",isPollCall,singleBranch,data); // if the branch name contains more wildcards then the simple usecase // does not apply and we need to skip to the advanced usecase if (singleBranch == null || singleBranch.contains("*")) return getAdvancedCandidateRevisions(isPollCall,listener,new GitUtils(listener,git),data); // check if we're trying to build a specific commit // this only makes sense for a build, there is no // reason to poll for a commit if (!isPollCall && singleBranch.matches("[0-9a-f]{6,40}")) { try { ObjectId sha1 = git.revParse(singleBranch); Revision revision = new Revision(sha1); revision.getBranches().add(new Branch("detached", sha1)); verbose(listener,"Will build the detached SHA1 {0}",sha1); return Collections.singletonList(revision); } catch (GitException e) { // revision does not exist, may still be a branch // for example a branch called "badface" would show up here verbose(listener, "Not a valid SHA1 {0}", singleBranch); } } // if it doesn't contain '/' then it could be either a tag or an unqualified branch if (!singleBranch.contains("/")) { // the 'branch' could actually be a tag: Set<String> tags = git.getTagNames(singleBranch); if(tags.size() == 0) { // its not a tag, so lets fully qualify the branch String repository = gitSCM.getRepositories().get(0).getName(); singleBranch = repository + "/" + singleBranch; verbose(listener, "{0} is not a tag. Qualifying with the repository {1} a a branch", singleBranch, repository); } } try { ObjectId sha1 = git.revParse(singleBranch); verbose(listener, "rev-parse {0} -> {1}", singleBranch, sha1); // if polling for changes don't select something that has // already been built as a build candidate if (isPollCall && data.hasBeenBuilt(sha1)) { verbose(listener, "{0} has already been built", sha1); return emptyList(); } verbose(listener, "Found a new commit {0} to be built on {1}", sha1, singleBranch); Revision revision = new Revision(sha1); revision.getBranches().add(new Branch(singleBranch, sha1)); return Collections.singletonList(revision); } catch (GitException e) { // branch does not exist, there is nothing to build verbose(listener, "Failed to rev-parse: {0}", singleBranch); return emptyList(); } } /** * In order to determine which Revisions to build. * * Does the following : * 1. Find all the branch revisions * 2. Filter out branches that we don't care about from the revisions. * Any Revisions with no interesting branches are dropped. * 3. Get rid of any revisions that are wholly subsumed by another * revision we're considering. * 4. Get rid of any revisions that we've already built. * * NB: Alternate BuildChooser implementations are possible - this * may be beneficial if "only 1" branch is to be built, as much of * this work is irrelevant in that usecase. * @throws IOException * @throws GitException */ private Collection<Revision> getAdvancedCandidateRevisions(boolean isPollCall, TaskListener listener, GitUtils utils, BuildData data) throws GitException, IOException { // 1. Get all the (branch) revisions that exist Collection<Revision> revs = utils.getAllBranchRevisions(); verbose(listener, "Starting with all the branches: {0}", revs); // 2. Filter out any revisions that don't contain any branches that we // actually care about (spec) for (Iterator<Revision> i = revs.iterator(); i.hasNext();) { Revision r = i.next(); // filter out uninteresting branches for (Iterator<Branch> j = r.getBranches().iterator(); j.hasNext();) { Branch b = j.next(); boolean keep = false; for (BranchSpec bspec : gitSCM.getBranches()) { if (bspec.matches(b.getName())) { keep = true; break; } } if (!keep) { verbose(listener, "Ignoring {0} because it doesn''t match branch specifier", b); j.remove(); } } if (r.getBranches().size() == 0) { verbose(listener, "Ignoring {0} because we don''t care about any of the branches that point to it", r); i.remove(); } } verbose(listener, "After branch filtering: {0}", revs); // 3. We only want 'tip' revisions revs = utils.filterTipBranches(revs); verbose(listener, "After non-tip filtering: {0}", revs); // 4. Finally, remove any revisions that have already been built. verbose(listener, "Removing what''s already been built: {0}", data.getBuildsByBranchName()); for (Iterator<Revision> i = revs.iterator(); i.hasNext();) { Revision r = i.next(); if (data.hasBeenBuilt(r.getSha1())) { i.remove(); } } verbose(listener, "After filtering out what''s already been built: {0}", revs); // if we're trying to run a build (not an SCM poll) and nothing new // was found then just run the last build again if (!isPollCall && revs.isEmpty() && data.getLastBuiltRevision() != null) { verbose(listener, "Nothing seems worth building, so falling back to the previously built revision: {0}", data.getLastBuiltRevision()); return Collections.singletonList(data.getLastBuiltRevision()); } return revs; } /** * Write the message to the listener only when the verbose mode is on. */ private void verbose(TaskListener listener, String format, Object... args) { if (GitSCM.VERBOSE) listener.getLogger().println(MessageFormat.format(format,args)); } @Extension public static final class DescriptorImpl extends BuildChooserDescriptor { @Override public String getDisplayName() { return "Default"; } @Override public String getLegacyId() { return "Default"; } } }
src/main/java/hudson/plugins/git/util/DefaultBuildChooser.java
package hudson.plugins.git.util; import hudson.Extension; import hudson.model.TaskListener; import hudson.plugins.git.Branch; import hudson.plugins.git.BranchSpec; import hudson.plugins.git.GitException; import hudson.plugins.git.GitSCM; import hudson.plugins.git.IGitAPI; import hudson.plugins.git.Revision; import org.kohsuke.stapler.DataBoundConstructor; import org.eclipse.jgit.lib.ObjectId; import java.io.IOException; import java.text.MessageFormat; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.Set; import static java.util.Collections.emptyList; public class DefaultBuildChooser extends BuildChooser { @DataBoundConstructor public DefaultBuildChooser() { } /** * Determines which Revisions to build. * * If only one branch is chosen and only one repository is listed, then * just attempt to find the latest revision number for the chosen branch. * * If multiple branches are selected or the branches include wildcards, then * use the advanced usecase as defined in the getAdvancedCandidateRevisons * method. * * @throws IOException * @throws GitException */ public Collection<Revision> getCandidateRevisions(boolean isPollCall, String singleBranch, IGitAPI git, TaskListener listener, BuildData data) throws GitException, IOException { verbose(listener,"getCandidateRevisions({0},{1},,,{2}) considering branches to build",isPollCall,singleBranch,data); // if the branch name contains more wildcards then the simple usecase // does not apply and we need to skip to the advanced usecase if (singleBranch == null || singleBranch.contains("*")) return getAdvancedCandidateRevisions(isPollCall,listener,new GitUtils(listener,git),data); // check if we're trying to build a specific commit // this only makes sense for a build, there is no // reason to poll for a commit if (!isPollCall && singleBranch.matches("[0-9a-f]{6,40}")) { try { ObjectId sha1 = git.revParse(singleBranch); Revision revision = new Revision(sha1); revision.getBranches().add(new Branch("detached", sha1)); verbose(listener,"Will build the detached SHA1 {0}",sha1); return Collections.singletonList(revision); } catch (GitException e) { // revision does not exist, may still be a branch // for example a branch called "badface" would show up here verbose(listener, "Not a valid SHA1 {0}", singleBranch); } } // if it doesn't contain '/' then it could be either a tag or an unqualified branch if (!singleBranch.contains("/")) { // the 'branch' could actually be a tag: Set<String> tags = git.getTagNames(singleBranch); if(tags.size() == 0) { // its not a tag, so lets fully qualify the branch String repository = gitSCM.getRepositories().get(0).getName(); singleBranch = repository + "/" + singleBranch; verbose(listener, "{0} is not a tag. Qualifying with the repository {1} a a branch", singleBranch, repository); } } try { ObjectId sha1 = git.revParse(singleBranch); verbose(listener, "rev-parse {0} -> {1}", singleBranch, sha1); // if polling for changes don't select something that has // already been built as a build candidate if (isPollCall && data.hasBeenBuilt(sha1)) { verbose(listener, "{0} has already been built", sha1); return emptyList(); } verbose(listener, "Found a new commit {0} to be built on {1}", sha1, singleBranch); Revision revision = new Revision(sha1); revision.getBranches().add(new Branch(singleBranch, sha1)); return Collections.singletonList(revision); } catch (GitException e) { // branch does not exist, there is nothing to build verbose(listener, "Failed to rev-parse: {0}", singleBranch); return emptyList(); } } /** * In order to determine which Revisions to build. * * Does the following : * 1. Find all the branch revisions * 2. Filter out branches that we don't care about from the revisions. * Any Revisions with no interesting branches are dropped. * 3. Get rid of any revisions that are wholly subsumed by another * revision we're considering. * 4. Get rid of any revisions that we've already built. * * NB: Alternate BuildChooser implementations are possible - this * may be beneficial if "only 1" branch is to be built, as much of * this work is irrelevant in that usecase. * @throws IOException * @throws GitException */ private Collection<Revision> getAdvancedCandidateRevisions(boolean isPollCall, TaskListener listener, GitUtils utils, BuildData data) throws GitException, IOException { // 1. Get all the (branch) revisions that exist Collection<Revision> revs = utils.getAllBranchRevisions(); verbose(listener, "Starting with all the branches: {0}", revs); // 2. Filter out any revisions that don't contain any branches that we // actually care about (spec) for (Iterator<Revision> i = revs.iterator(); i.hasNext();) { Revision r = i.next(); // filter out uninteresting branches for (Iterator<Branch> j = r.getBranches().iterator(); j.hasNext();) { Branch b = j.next(); boolean keep = false; for (BranchSpec bspec : gitSCM.getBranches()) { if (bspec.matches(b.getName())) { keep = true; break; } } if (!keep) { verbose(listener, "Ignoring {0} because it doesn't match branch specifier", b); j.remove(); } } if (r.getBranches().size() == 0) { verbose(listener, "Ignoring {0} because we don't care about any of the branches that point to it", r); i.remove(); } } verbose(listener, "After branch filtering: {0}", revs); // 3. We only want 'tip' revisions revs = utils.filterTipBranches(revs); verbose(listener, "After non-tip filtering: {0}", revs); // 4. Finally, remove any revisions that have already been built. verbose(listener, "Removing what''s already been built: {0}", data.getBuildsByBranchName()); for (Iterator<Revision> i = revs.iterator(); i.hasNext();) { Revision r = i.next(); if (data.hasBeenBuilt(r.getSha1())) { i.remove(); } } verbose(listener, "After filtering out what''s already been built: {0}", revs); // if we're trying to run a build (not an SCM poll) and nothing new // was found then just run the last build again if (!isPollCall && revs.isEmpty() && data.getLastBuiltRevision() != null) { verbose(listener, "Nothing seems worth building, so falling back to the previously built revision: {0}", data.getLastBuiltRevision()); return Collections.singletonList(data.getLastBuiltRevision()); } return revs; } /** * Write the message to the listener only when the verbose mode is on. */ private void verbose(TaskListener listener, String format, Object... args) { if (GitSCM.VERBOSE) listener.getLogger().println(MessageFormat.format(format,args)); } @Extension public static final class DescriptorImpl extends BuildChooserDescriptor { @Override public String getDisplayName() { return "Default"; } @Override public String getLegacyId() { return "Default"; } } }
Add missing single-quote in calls to MessageFormat Closes pull request #29
src/main/java/hudson/plugins/git/util/DefaultBuildChooser.java
Add missing single-quote in calls to MessageFormat
Java
mit
553418c0958317310181d7d4998b22b405cf719c
0
McJty/LostCities
package mcjty.lostcities.dimensions.world; import mcjty.lib.compat.CompatChunkGenerator; import mcjty.lib.compat.CompatMapGenStructure; import mcjty.lib.tools.EntityTools; import mcjty.lostcities.api.IChunkPrimerFactory; import mcjty.lostcities.api.ILostChunkGenerator; import mcjty.lostcities.api.ILostChunkInfo; import mcjty.lostcities.config.LostCityProfile; import mcjty.lostcities.dimensions.world.lost.BiomeInfo; import mcjty.lostcities.dimensions.world.lost.BuildingInfo; import mcjty.lostcities.dimensions.world.lost.cityassets.AssetRegistries; import mcjty.lostcities.dimensions.world.lost.cityassets.WorldStyle; import mcjty.lostcities.varia.ChunkCoord; import net.minecraft.block.BlockChest; import net.minecraft.block.BlockFalling; import net.minecraft.block.BlockSapling; import net.minecraft.block.BlockVine; import net.minecraft.block.properties.PropertyBool; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.EnumCreatureType; import net.minecraft.init.Biomes; import net.minecraft.init.Blocks; import net.minecraft.tileentity.TileEntity; import net.minecraft.tileentity.TileEntityChest; import net.minecraft.tileentity.TileEntityMobSpawner; import net.minecraft.util.EnumFacing; import net.minecraft.util.ResourceLocation; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.ChunkPos; import net.minecraft.world.World; import net.minecraft.world.WorldEntitySpawner; import net.minecraft.world.WorldType; import net.minecraft.world.biome.Biome; import net.minecraft.world.chunk.Chunk; import net.minecraft.world.chunk.ChunkPrimer; import net.minecraft.world.gen.ChunkProviderSettings; import net.minecraft.world.gen.MapGenBase; import net.minecraft.world.gen.MapGenCaves; import net.minecraft.world.gen.MapGenRavine; import net.minecraft.world.gen.feature.WorldGenDungeons; import net.minecraft.world.gen.feature.WorldGenLakes; import net.minecraft.world.gen.structure.*; import net.minecraft.world.storage.loot.LootTableList; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.event.terraingen.PopulateChunkEvent; import net.minecraftforge.event.terraingen.TerrainGen; import org.apache.commons.lang3.tuple.Pair; import java.util.*; import static net.minecraftforge.event.terraingen.InitMapGenEvent.EventType.*; public class LostCityChunkGenerator implements CompatChunkGenerator, ILostChunkGenerator { public LostCityProfile profile; // Current profile public WorldStyle worldStyle; public Random rand; public long seed; public int dimensionId; public World worldObj; public WorldType worldType; public final LostCitiesTerrainGenerator terrainGenerator; private ChunkProviderSettings settings = null; private Biome[] biomesForGeneration; private MapGenBase caveGenerator; // Sometimes we have to precalculate primers for a chunk before the // chunk is generated. In that case we cache them here so that when the // chunk is really generated it will find it and use that instead of // making that primer again // @todo, make this cache timed so that primers expire if they are not used quickly enough? private Map<ChunkCoord, ChunkPrimer> cachedPrimers = new HashMap<>(); private Map<ChunkCoord, ChunkHeightmap> cachedHeightmaps = new HashMap<>(); private MapGenStronghold strongholdGenerator = new MapGenStronghold(); private StructureOceanMonument oceanMonumentGenerator = new StructureOceanMonument(); private MapGenVillage villageGenerator = new MapGenVillage(); private MapGenMineshaft mineshaftGenerator = new MapGenMineshaft(); private MapGenScatteredFeature scatteredFeatureGenerator = new MapGenScatteredFeature(); public ChunkProviderSettings getSettings() { if (settings == null) { ChunkProviderSettings.Factory factory = new ChunkProviderSettings.Factory(); settings = factory.build(); } return settings; } // Holds ravine generator private MapGenBase ravineGenerator = new MapGenRavine(); public IChunkPrimerFactory otherGenerator = null; public LostCityChunkGenerator(World world, IChunkPrimerFactory otherGenerator) { this(world, world.getSeed()); this.otherGenerator = otherGenerator; } public LostCityChunkGenerator(World world, long seed) { { caveGenerator = new LostGenCaves(this); caveGenerator = TerrainGen.getModdedMapGen(caveGenerator, CAVE); strongholdGenerator = (MapGenStronghold) TerrainGen.getModdedMapGen(strongholdGenerator, STRONGHOLD); villageGenerator = (MapGenVillage) TerrainGen.getModdedMapGen(villageGenerator, VILLAGE); mineshaftGenerator = (MapGenMineshaft) TerrainGen.getModdedMapGen(mineshaftGenerator, MINESHAFT); scatteredFeatureGenerator = (MapGenScatteredFeature) TerrainGen.getModdedMapGen(scatteredFeatureGenerator, SCATTERED_FEATURE); ravineGenerator = TerrainGen.getModdedMapGen(ravineGenerator, RAVINE); oceanMonumentGenerator = (StructureOceanMonument) TerrainGen.getModdedMapGen(oceanMonumentGenerator, OCEAN_MONUMENT); } dimensionId = world.provider.getDimension(); profile = LostWorldType.getProfile(world); System.out.println("LostCityChunkGenerator.LostCityChunkGenerator: profile=" + profile.getName()); worldStyle = AssetRegistries.WORLDSTYLES.get(profile.getWorldStyle()); if (worldStyle == null) { throw new RuntimeException("Unknown worldstyle '" + profile.getWorldStyle() + "'!"); } String generatorOptions = profile.GENERATOR_OPTIONS; if (generatorOptions != null && !generatorOptions.isEmpty()) { this.settings = ChunkProviderSettings.Factory.jsonToFactory(generatorOptions).build(); } this.worldObj = world; this.worldType = world.getWorldInfo().getTerrainType(); this.seed = seed; this.rand = new Random((seed + 516) * 314); int waterLevel = (byte) (profile.GROUNDLEVEL - profile.WATERLEVEL_OFFSET); world.setSeaLevel(waterLevel); terrainGenerator = new LostCitiesTerrainGenerator(this); terrainGenerator.setup(world); } public ChunkPrimer generatePrimer(int chunkX, int chunkZ) { this.rand.setSeed(chunkX * 341873128712L + chunkZ * 132897987541L); ChunkPrimer chunkprimer = new ChunkPrimer(); if (otherGenerator != null) { // For ATG, experimental otherGenerator.fillChunk(chunkX, chunkZ, chunkprimer); } else { terrainGenerator.doCoreChunk(chunkX, chunkZ, chunkprimer); } return chunkprimer; } // Get a heightmap for a chunk. If needed calculate (and cache) a primer public ChunkHeightmap getHeightmap(int chunkX, int chunkZ) { ChunkCoord key = new ChunkCoord(worldObj.provider.getDimension(), chunkX, chunkZ); if (cachedHeightmaps.containsKey(key)) { return cachedHeightmaps.get(key); } else if (cachedPrimers.containsKey(key)) { ChunkHeightmap heightmap = new ChunkHeightmap(cachedPrimers.get(key)); cachedHeightmaps.put(key, heightmap); return heightmap; } else { ChunkPrimer primer = generatePrimer(chunkX, chunkZ); cachedPrimers.put(key, primer); ChunkHeightmap heightmap = new ChunkHeightmap(cachedPrimers.get(key)); cachedHeightmaps.put(key, heightmap); return heightmap; } } @Override public Chunk provideChunk(int chunkX, int chunkZ) { LostCitiesTerrainGenerator.setupChars(); boolean isCity = BuildingInfo.isCity(chunkX, chunkZ, this); ChunkPrimer chunkprimer; if (isCity) { chunkprimer = new ChunkPrimer(); } else { ChunkCoord key = new ChunkCoord(worldObj.provider.getDimension(), chunkX, chunkZ); if (cachedPrimers.containsKey(key)) { // We calculated a primer earlier. Reuse it chunkprimer = cachedPrimers.get(key); cachedPrimers.remove(key); } else { chunkprimer = generatePrimer(chunkX, chunkZ); } // Calculate the chunk heightmap in case we need it later if (!cachedHeightmaps.containsKey(key)) { // We might need this later cachedHeightmaps.put(key, new ChunkHeightmap(chunkprimer)); } } terrainGenerator.generate(chunkX, chunkZ, chunkprimer); this.biomesForGeneration = this.worldObj.getBiomeProvider().getBiomes(this.biomesForGeneration, chunkX * 16, chunkZ * 16, 16, 16); terrainGenerator.replaceBlocksForBiome(chunkX, chunkZ, chunkprimer, this.biomesForGeneration); if (profile.GENERATE_CAVES) { this.caveGenerator.generate(this.worldObj, chunkX, chunkZ, chunkprimer); } if (profile.GENERATE_RAVINES) { if (!profile.PREVENT_LAKES_RAVINES_IN_CITIES || !isCity) { this.ravineGenerator.generate(this.worldObj, chunkX, chunkZ, chunkprimer); } } if (profile.GENERATE_MINESHAFTS) { this.mineshaftGenerator.generate(this.worldObj, chunkX, chunkZ, chunkprimer); } if (profile.GENERATE_VILLAGES) { if (profile.PREVENT_VILLAGES_IN_CITIES) { if (!isCity) { this.villageGenerator.generate(this.worldObj, chunkX, chunkZ, chunkprimer); } } else { this.villageGenerator.generate(this.worldObj, chunkX, chunkZ, chunkprimer); } } if (profile.GENERATE_STRONGHOLDS) { this.strongholdGenerator.generate(this.worldObj, chunkX, chunkZ, chunkprimer); } if (profile.GENERATE_SCATTERED) { this.scatteredFeatureGenerator.generate(this.worldObj, chunkX, chunkZ, chunkprimer); } if (profile.GENERATE_OCEANMONUMENTS) { this.oceanMonumentGenerator.generate(this.worldObj, chunkX, chunkZ, chunkprimer); } Chunk chunk = new Chunk(this.worldObj, chunkprimer, chunkX, chunkZ); byte[] abyte = chunk.getBiomeArray(); for (int i = 0; i < abyte.length; ++i) { abyte[i] = (byte) Biome.getIdForBiome(this.biomesForGeneration[i]); } chunk.generateSkylightMap(); return chunk; } private void generateTrees(Random random, int chunkX, int chunkZ, World world, LostCityChunkGenerator provider) { BuildingInfo info = BuildingInfo.getBuildingInfo(chunkX, chunkZ, provider); for (BlockPos pos : info.getSaplingTodo()) { IBlockState state = world.getBlockState(pos); if (state.getBlock() == Blocks.SAPLING) { ((BlockSapling)Blocks.SAPLING).generateTree(world, pos, state, random); } } info.clearSaplingTodo(); } private void generateVines(Random random, int chunkX, int chunkZ, World world, LostCityChunkGenerator provider) { int cx = chunkX * 16; int cz = chunkZ * 16; BuildingInfo info = BuildingInfo.getBuildingInfo(chunkX, chunkZ, provider); if (info.hasBuilding) { BuildingInfo adjacent = info.getXmax(); int bottom = Math.max(adjacent.getCityGroundLevel() + 3, adjacent.hasBuilding ? adjacent.getMaxHeight() : (adjacent.getCityGroundLevel() + 3)); for (int z = 0; z < 15; z++) { for (int y = bottom; y < (info.getMaxHeight()); y++) { if (random.nextFloat() < provider.profile.VINE_CHANCE) { createVineStrip(random, world, bottom, BlockVine.WEST, new BlockPos(cx + 16, y, cz + z), new BlockPos(cx + 15, y, cz + z)); } } } } if (info.getXmax().hasBuilding) { BuildingInfo adjacent = info.getXmax(); int bottom = Math.max(info.getCityGroundLevel() + 3, info.hasBuilding ? info.getMaxHeight() : (info.getCityGroundLevel() + 3)); for (int z = 0; z < 15; z++) { for (int y = bottom; y < (adjacent.getMaxHeight()); y++) { if (random.nextFloat() < provider.profile.VINE_CHANCE) { createVineStrip(random, world, bottom, BlockVine.EAST, new BlockPos(cx + 15, y, cz + z), new BlockPos(cx + 16, y, cz + z)); } } } } if (info.hasBuilding) { BuildingInfo adjacent = info.getZmax(); int bottom = Math.max(adjacent.getCityGroundLevel() + 3, adjacent.hasBuilding ? adjacent.getMaxHeight() : (adjacent.getCityGroundLevel() + 3)); for (int x = 0; x < 15; x++) { for (int y = bottom; y < (info.getMaxHeight()); y++) { if (random.nextFloat() < provider.profile.VINE_CHANCE) { createVineStrip(random, world, bottom, BlockVine.NORTH, new BlockPos(cx + x, y, cz + 16), new BlockPos(cx + x, y, cz + 15)); } } } } if (info.getZmax().hasBuilding) { BuildingInfo adjacent = info.getZmax(); int bottom = Math.max(info.getCityGroundLevel() + 3, info.hasBuilding ? info.getMaxHeight() : (info.getCityGroundLevel() + 3)); for (int x = 0; x < 15; x++) { for (int y = bottom; y < (adjacent.getMaxHeight()); y++) { if (random.nextFloat() < provider.profile.VINE_CHANCE) { createVineStrip(random, world, bottom, BlockVine.SOUTH, new BlockPos(cx + x, y, cz + 15), new BlockPos(cx + x, y, cz + 16)); } } } } } private void createVineStrip(Random random, World world, int bottom, PropertyBool direction, BlockPos pos, BlockPos vineHolderPos) { if (world.isAirBlock(vineHolderPos)) { return; } if (!world.isAirBlock(pos)) { return; } world.setBlockState(pos, Blocks.VINE.getDefaultState().withProperty(direction, true)); pos = pos.down(); while (pos.getY() >= bottom && random.nextFloat() < .8f) { if (!world.isAirBlock(pos)) { return; } world.setBlockState(pos, Blocks.VINE.getDefaultState().withProperty(direction, true)); pos = pos.down(); } } private void generateLootSpawners(Random random, int chunkX, int chunkZ, World world, LostCityChunkGenerator chunkGenerator) { BuildingInfo info = BuildingInfo.getBuildingInfo(chunkX, chunkZ, chunkGenerator); for (Pair<BlockPos, String> pair : info.getMobSpawnerTodo()) { BlockPos pos = pair.getKey(); // Double check that it is still a spawner (could be destroyed by explosion) if (world.getBlockState(pos).getBlock() == Blocks.MOB_SPAWNER) { TileEntity tileentity = world.getTileEntity(pos); if (tileentity instanceof TileEntityMobSpawner) { TileEntityMobSpawner spawner = (TileEntityMobSpawner) tileentity; String id = pair.getValue(); String fixedId = EntityTools.fixEntityId(id); EntityTools.setSpawnerEntity(world, spawner, new ResourceLocation(fixedId), fixedId); } } } info.clearMobSpawnerTodo(); for (Pair<BlockPos, String> pair : info.getChestTodo()) { BlockPos pos = pair.getKey(); // Double check that it is still a chest (could be destroyed by explosion) IBlockState state = world.getBlockState(pos); if (state.getBlock() == Blocks.CHEST) { if (chunkGenerator.profile.GENERATE_LOOT) { createLootChest(random, world, pos, pair.getRight()); } } } info.clearChestTodo(); for (BlockPos pos : info.getGenericTodo()) { IBlockState state = world.getBlockState(pos); if (state.getBlock() == Blocks.GLOWSTONE) { world.setBlockState(pos, state, 3); } } info.clearGenericTodo(); } private void createLootChest(Random random, World world, BlockPos pos, String lootTable) { world.setBlockState(pos, Blocks.CHEST.getDefaultState().withProperty(BlockChest.FACING, EnumFacing.SOUTH)); TileEntity tileentity = world.getTileEntity(pos); if (tileentity instanceof TileEntityChest) { if (lootTable != null) { ((TileEntityChest) tileentity).setLootTable(new ResourceLocation(lootTable), random.nextLong()); } else { switch (random.nextInt(30)) { case 0: ((TileEntityChest) tileentity).setLootTable(LootTableList.CHESTS_DESERT_PYRAMID, random.nextLong()); break; case 1: ((TileEntityChest) tileentity).setLootTable(LootTableList.CHESTS_JUNGLE_TEMPLE, random.nextLong()); break; case 2: ((TileEntityChest) tileentity).setLootTable(LootTableList.CHESTS_VILLAGE_BLACKSMITH, random.nextLong()); break; case 3: ((TileEntityChest) tileentity).setLootTable(LootTableList.CHESTS_ABANDONED_MINESHAFT, random.nextLong()); break; case 4: ((TileEntityChest) tileentity).setLootTable(LootTableList.CHESTS_NETHER_BRIDGE, random.nextLong()); break; default: ((TileEntityChest) tileentity).setLootTable(LootTableList.CHESTS_SIMPLE_DUNGEON, random.nextLong()); break; } } } } @Override public void populate(int chunkX, int chunkZ) { BlockFalling.fallInstantly = true; int x = chunkX * 16; int z = chunkZ * 16; World w = this.worldObj; Biome Biome = w.getBiomeForCoordsBody(new BlockPos(x + 16, 0, z + 16)); this.rand.setSeed(w.getSeed()); long i1 = this.rand.nextLong() / 2L * 2L + 1L; long j1 = this.rand.nextLong() / 2L * 2L + 1L; this.rand.setSeed(chunkX * i1 + chunkZ * j1 ^ w.getSeed()); boolean flag = false; MinecraftForge.EVENT_BUS.post(new PopulateChunkEvent.Pre(this, w, rand, chunkX, chunkZ, flag)); ChunkPos cp = new ChunkPos(chunkX, chunkZ); if (profile.GENERATE_MINESHAFTS) { this.mineshaftGenerator.generateStructure(w, this.rand, cp); } if (profile.GENERATE_VILLAGES) { if (profile.PREVENT_VILLAGES_IN_CITIES) { if (!BuildingInfo.isCity(chunkX, chunkZ, this)) { flag = this.villageGenerator.generateStructure(w, this.rand, cp); } } else { flag = this.villageGenerator.generateStructure(w, this.rand, cp); } } if (profile.GENERATE_STRONGHOLDS) { this.strongholdGenerator.generateStructure(w, this.rand, cp); } if (profile.GENERATE_SCATTERED) { this.scatteredFeatureGenerator.generateStructure(w, this.rand, cp); } if (profile.GENERATE_OCEANMONUMENTS) { this.oceanMonumentGenerator.generateStructure(w, this.rand, cp); } int k1; int l1; int i2; if (profile.GENERATE_LAKES) { boolean isCity = BuildingInfo.isCity(chunkX, chunkZ, this); if (!profile.PREVENT_LAKES_RAVINES_IN_CITIES || !isCity) { if (Biome != Biomes.DESERT && Biome != Biomes.DESERT_HILLS && !flag && this.rand.nextInt(4) == 0 && TerrainGen.populate(this, w, rand, chunkX, chunkZ, flag, PopulateChunkEvent.Populate.EventType.LAKE)) { k1 = x + this.rand.nextInt(16) + 8; l1 = this.rand.nextInt(256); i2 = z + this.rand.nextInt(16) + 8; (new WorldGenLakes(Blocks.WATER)).generate(w, this.rand, new BlockPos(k1, l1, i2)); } if (TerrainGen.populate(this, w, rand, chunkX, chunkZ, flag, PopulateChunkEvent.Populate.EventType.LAVA) && !flag && this.rand.nextInt(8) == 0) { k1 = x + this.rand.nextInt(16) + 8; l1 = this.rand.nextInt(this.rand.nextInt(248) + 8); i2 = z + this.rand.nextInt(16) + 8; if (l1 < (profile.GROUNDLEVEL - profile.WATERLEVEL_OFFSET) || this.rand.nextInt(10) == 0) { (new WorldGenLakes(Blocks.LAVA)).generate(w, this.rand, new BlockPos(k1, l1, i2)); } } } } boolean doGen = false; if (profile.GENERATE_DUNGEONS) { doGen = TerrainGen.populate(this, w, rand, chunkX, chunkZ, flag, PopulateChunkEvent.Populate.EventType.DUNGEON); for (k1 = 0; doGen && k1 < 8; ++k1) { l1 = x + this.rand.nextInt(16) + 8; i2 = this.rand.nextInt(256); int j2 = z + this.rand.nextInt(16) + 8; (new WorldGenDungeons()).generate(w, this.rand, new BlockPos(l1, i2, j2)); } } BlockPos pos = new BlockPos(x, 0, z); Biome.decorate(w, this.rand, pos); if (TerrainGen.populate(this, w, rand, chunkX, chunkZ, flag, PopulateChunkEvent.Populate.EventType.ANIMALS)) { WorldEntitySpawner.performWorldGenSpawning(w, Biome, x + 8, z + 8, 16, 16, this.rand); } x += 8; z += 8; doGen = TerrainGen.populate(this, w, rand, chunkX, chunkZ, flag, PopulateChunkEvent.Populate.EventType.ICE); for (k1 = 0; doGen && k1 < 16; ++k1) { for (l1 = 0; l1 < 16; ++l1) { i2 = w.getPrecipitationHeight(new BlockPos(x + k1, 0, z + l1)).getY(); if (w.canBlockFreeze(new BlockPos(k1 + x, i2 - 1, l1 + z), false)) { w.setBlockState(new BlockPos(k1 + x, i2 - 1, l1 + z), Blocks.ICE.getDefaultState(), 2); } if (w.canSnowAt(new BlockPos(k1 + x, i2, l1 + z), true)) { w.setBlockState(new BlockPos(k1 + x, i2, l1 + z), Blocks.SNOW_LAYER.getDefaultState(), 2); } } } generateTrees(rand, chunkX, chunkZ, w, this); generateVines(rand, chunkX, chunkZ, w, this); generateLootSpawners(rand, chunkX, chunkZ, w, this); MinecraftForge.EVENT_BUS.post(new PopulateChunkEvent.Post(this, w, rand, chunkX, chunkZ, flag)); BlockFalling.fallInstantly = false; } @Override public boolean generateStructures(Chunk chunkIn, int x, int z) { boolean flag = false; if (profile.GENERATE_OCEANMONUMENTS) { if (chunkIn.getInhabitedTime() < 3600L) { flag |= this.oceanMonumentGenerator.generateStructure(this.worldObj, this.rand, new ChunkPos(x, z)); } } return flag; } @Override public List<Biome.SpawnListEntry> getPossibleCreatures(EnumCreatureType creatureType, BlockPos pos) { return getDefaultCreatures(creatureType, pos); } private List getDefaultCreatures(EnumCreatureType creatureType, BlockPos pos) { Biome Biome = this.worldObj.getBiomeForCoordsBody(pos); if (creatureType == EnumCreatureType.MONSTER) { if (profile.GENERATE_SCATTERED) { if (this.scatteredFeatureGenerator.isInsideStructure(pos)) { return this.scatteredFeatureGenerator.getScatteredFeatureSpawnList(); } } if (profile.GENERATE_OCEANMONUMENTS) { if (this.oceanMonumentGenerator.isPositionInStructure(this.worldObj, pos)) { return this.oceanMonumentGenerator.getScatteredFeatureSpawnList(); } } } return Biome.getSpawnableList(creatureType); } @Override public BlockPos clGetStrongholdGen(World worldIn, String structureName, BlockPos position) { return "Stronghold".equals(structureName) && this.strongholdGenerator != null ? CompatMapGenStructure.getClosestStrongholdPos(this.strongholdGenerator, worldIn, position) : null; } @Override public void recreateStructures(Chunk chunkIn, int x, int z) { if (profile.GENERATE_MINESHAFTS) { this.mineshaftGenerator.generate(this.worldObj, x, z, null); } if (profile.GENERATE_VILLAGES) { if (profile.PREVENT_VILLAGES_IN_CITIES) { if (!BuildingInfo.isCity(x, z, this)) { this.villageGenerator.generate(this.worldObj, x, z, null); } } else { this.villageGenerator.generate(this.worldObj, x, z, null); } } if (profile.GENERATE_STRONGHOLDS) { this.strongholdGenerator.generate(this.worldObj, x, z, null); } if (profile.GENERATE_SCATTERED) { this.scatteredFeatureGenerator.generate(this.worldObj, x, z, null); } if (profile.GENERATE_OCEANMONUMENTS) { this.oceanMonumentGenerator.generate(this.worldObj, x, z, null); } } @Override public ILostChunkInfo getChunkInfo(int chunkX, int chunkZ) { return BuildingInfo.getBuildingInfo(chunkX, chunkZ, this); } @Override public int getRealHeight(int level) { return profile.GROUNDLEVEL + level * 6; } }
src/main/java/mcjty/lostcities/dimensions/world/LostCityChunkGenerator.java
package mcjty.lostcities.dimensions.world; import mcjty.lib.compat.CompatChunkGenerator; import mcjty.lib.compat.CompatMapGenStructure; import mcjty.lib.tools.EntityTools; import mcjty.lostcities.api.IChunkPrimerFactory; import mcjty.lostcities.api.ILostChunkGenerator; import mcjty.lostcities.api.ILostChunkInfo; import mcjty.lostcities.config.LostCityProfile; import mcjty.lostcities.dimensions.world.lost.BiomeInfo; import mcjty.lostcities.dimensions.world.lost.BuildingInfo; import mcjty.lostcities.dimensions.world.lost.cityassets.AssetRegistries; import mcjty.lostcities.dimensions.world.lost.cityassets.WorldStyle; import mcjty.lostcities.varia.ChunkCoord; import net.minecraft.block.BlockChest; import net.minecraft.block.BlockFalling; import net.minecraft.block.BlockSapling; import net.minecraft.block.BlockVine; import net.minecraft.block.properties.PropertyBool; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.EnumCreatureType; import net.minecraft.init.Biomes; import net.minecraft.init.Blocks; import net.minecraft.tileentity.TileEntity; import net.minecraft.tileentity.TileEntityChest; import net.minecraft.tileentity.TileEntityMobSpawner; import net.minecraft.util.EnumFacing; import net.minecraft.util.ResourceLocation; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.ChunkPos; import net.minecraft.world.World; import net.minecraft.world.WorldEntitySpawner; import net.minecraft.world.WorldType; import net.minecraft.world.biome.Biome; import net.minecraft.world.chunk.Chunk; import net.minecraft.world.chunk.ChunkPrimer; import net.minecraft.world.gen.ChunkProviderSettings; import net.minecraft.world.gen.MapGenBase; import net.minecraft.world.gen.MapGenCaves; import net.minecraft.world.gen.MapGenRavine; import net.minecraft.world.gen.feature.WorldGenDungeons; import net.minecraft.world.gen.feature.WorldGenLakes; import net.minecraft.world.gen.structure.*; import net.minecraft.world.storage.loot.LootTableList; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.event.terraingen.PopulateChunkEvent; import net.minecraftforge.event.terraingen.TerrainGen; import org.apache.commons.lang3.tuple.Pair; import java.util.*; import static net.minecraftforge.event.terraingen.InitMapGenEvent.EventType.*; public class LostCityChunkGenerator implements CompatChunkGenerator, ILostChunkGenerator { public LostCityProfile profile; // Current profile public WorldStyle worldStyle; public Random rand; public long seed; public int dimensionId; public World worldObj; public WorldType worldType; public final LostCitiesTerrainGenerator terrainGenerator; private ChunkProviderSettings settings = null; private Biome[] biomesForGeneration; private MapGenBase caveGenerator; // Sometimes we have to precalculate primers for a chunk before the // chunk is generated. In that case we cache them here so that when the // chunk is really generated it will find it and use that instead of // making that primer again // @todo, make this cache timed so that primers expire if they are not used quickly enough? private Map<ChunkCoord, ChunkPrimer> cachedPrimers = new HashMap<>(); private Map<ChunkCoord, ChunkHeightmap> cachedHeightmaps = new HashMap<>(); private MapGenStronghold strongholdGenerator = new MapGenStronghold(); private StructureOceanMonument oceanMonumentGenerator = new StructureOceanMonument(); private MapGenVillage villageGenerator = new MapGenVillage(); private MapGenMineshaft mineshaftGenerator = new MapGenMineshaft(); private MapGenScatteredFeature scatteredFeatureGenerator = new MapGenScatteredFeature(); public ChunkProviderSettings getSettings() { if (settings == null) { ChunkProviderSettings.Factory factory = new ChunkProviderSettings.Factory(); settings = factory.build(); } return settings; } // Holds ravine generator private MapGenBase ravineGenerator = new MapGenRavine(); public IChunkPrimerFactory otherGenerator = null; public LostCityChunkGenerator(World world, IChunkPrimerFactory otherGenerator) { this(world, world.getSeed()); this.otherGenerator = otherGenerator; } public LostCityChunkGenerator(World world, long seed) { { caveGenerator = new LostGenCaves(this); caveGenerator = TerrainGen.getModdedMapGen(caveGenerator, CAVE); strongholdGenerator = (MapGenStronghold) TerrainGen.getModdedMapGen(strongholdGenerator, STRONGHOLD); villageGenerator = (MapGenVillage) TerrainGen.getModdedMapGen(villageGenerator, VILLAGE); mineshaftGenerator = (MapGenMineshaft) TerrainGen.getModdedMapGen(mineshaftGenerator, MINESHAFT); scatteredFeatureGenerator = (MapGenScatteredFeature) TerrainGen.getModdedMapGen(scatteredFeatureGenerator, SCATTERED_FEATURE); ravineGenerator = TerrainGen.getModdedMapGen(ravineGenerator, RAVINE); oceanMonumentGenerator = (StructureOceanMonument) TerrainGen.getModdedMapGen(oceanMonumentGenerator, OCEAN_MONUMENT); } dimensionId = world.provider.getDimension(); profile = LostWorldType.getProfile(world); System.out.println("LostCityChunkGenerator.LostCityChunkGenerator: profile=" + profile.getName()); worldStyle = AssetRegistries.WORLDSTYLES.get(profile.getWorldStyle()); if (worldStyle == null) { throw new RuntimeException("Unknown worldstyle '" + profile.getWorldStyle() + "'!"); } String generatorOptions = profile.GENERATOR_OPTIONS; if (generatorOptions != null && !generatorOptions.isEmpty()) { this.settings = ChunkProviderSettings.Factory.jsonToFactory(generatorOptions).build(); } this.worldObj = world; this.worldType = world.getWorldInfo().getTerrainType(); this.seed = seed; this.rand = new Random((seed + 516) * 314); int waterLevel = (byte) (profile.GROUNDLEVEL - profile.WATERLEVEL_OFFSET); world.setSeaLevel(waterLevel); terrainGenerator = new LostCitiesTerrainGenerator(this); terrainGenerator.setup(world); } public ChunkPrimer generatePrimer(int chunkX, int chunkZ) { this.rand.setSeed(chunkX * 341873128712L + chunkZ * 132897987541L); ChunkPrimer chunkprimer = new ChunkPrimer(); if (otherGenerator != null) { // For ATG, experimental otherGenerator.fillChunk(chunkX, chunkZ, chunkprimer); } else { terrainGenerator.doCoreChunk(chunkX, chunkZ, chunkprimer); } return chunkprimer; } // Get a heightmap for a chunk. If needed calculate (and cache) a primer public ChunkHeightmap getHeightmap(int chunkX, int chunkZ) { ChunkCoord key = new ChunkCoord(worldObj.provider.getDimension(), chunkX, chunkZ); if (cachedHeightmaps.containsKey(key)) { return cachedHeightmaps.get(key); } else if (cachedPrimers.containsKey(key)) { ChunkHeightmap heightmap = new ChunkHeightmap(cachedPrimers.get(key)); cachedHeightmaps.put(key, heightmap); return heightmap; } else { ChunkPrimer primer = generatePrimer(chunkX, chunkZ); cachedPrimers.put(key, primer); ChunkHeightmap heightmap = new ChunkHeightmap(cachedPrimers.get(key)); cachedHeightmaps.put(key, heightmap); return heightmap; } } private static Set<ChunkCoord> providedChunks = new HashSet<>(); @Override public Chunk provideChunk(int chunkX, int chunkZ) { LostCitiesTerrainGenerator.setupChars(); boolean isCity = BuildingInfo.isCity(chunkX, chunkZ, this); ChunkPrimer chunkprimer; if (isCity) { chunkprimer = new ChunkPrimer(); } else { ChunkCoord key = new ChunkCoord(worldObj.provider.getDimension(), chunkX, chunkZ); if (cachedPrimers.containsKey(key)) { // We calculated a primer earlier. Reuse it chunkprimer = cachedPrimers.get(key); cachedPrimers.remove(key); } else { chunkprimer = generatePrimer(chunkX, chunkZ); } // Calculate the chunk heightmap in case we need it later if (!cachedHeightmaps.containsKey(key)) { // We might need this later cachedHeightmaps.put(key, new ChunkHeightmap(chunkprimer)); } } terrainGenerator.generate(chunkX, chunkZ, chunkprimer); this.biomesForGeneration = this.worldObj.getBiomeProvider().getBiomes(this.biomesForGeneration, chunkX * 16, chunkZ * 16, 16, 16); terrainGenerator.replaceBlocksForBiome(chunkX, chunkZ, chunkprimer, this.biomesForGeneration); if (profile.GENERATE_CAVES) { this.caveGenerator.generate(this.worldObj, chunkX, chunkZ, chunkprimer); } if (profile.GENERATE_RAVINES) { if (!profile.PREVENT_LAKES_RAVINES_IN_CITIES || !isCity) { this.ravineGenerator.generate(this.worldObj, chunkX, chunkZ, chunkprimer); } } if (profile.GENERATE_MINESHAFTS) { this.mineshaftGenerator.generate(this.worldObj, chunkX, chunkZ, chunkprimer); } if (profile.GENERATE_VILLAGES) { if (profile.PREVENT_VILLAGES_IN_CITIES) { if (!isCity) { this.villageGenerator.generate(this.worldObj, chunkX, chunkZ, chunkprimer); } } else { this.villageGenerator.generate(this.worldObj, chunkX, chunkZ, chunkprimer); } } if (profile.GENERATE_STRONGHOLDS) { this.strongholdGenerator.generate(this.worldObj, chunkX, chunkZ, chunkprimer); } if (profile.GENERATE_SCATTERED) { this.scatteredFeatureGenerator.generate(this.worldObj, chunkX, chunkZ, chunkprimer); } if (profile.GENERATE_OCEANMONUMENTS) { this.oceanMonumentGenerator.generate(this.worldObj, chunkX, chunkZ, chunkprimer); } Chunk chunk = new Chunk(this.worldObj, chunkprimer, chunkX, chunkZ); byte[] abyte = chunk.getBiomeArray(); for (int i = 0; i < abyte.length; ++i) { abyte[i] = (byte) Biome.getIdForBiome(this.biomesForGeneration[i]); } chunk.generateSkylightMap(); providedChunks.add(new ChunkCoord(dimensionId, chunkX, chunkZ)); return chunk; } private void generateTrees(Random random, int chunkX, int chunkZ, World world, LostCityChunkGenerator provider) { BuildingInfo info = BuildingInfo.getBuildingInfo(chunkX, chunkZ, provider); for (BlockPos pos : info.getSaplingTodo()) { IBlockState state = world.getBlockState(pos); if (state.getBlock() == Blocks.SAPLING) { ((BlockSapling)Blocks.SAPLING).generateTree(world, pos, state, random); } } info.clearSaplingTodo(); } private void generateVines(Random random, int chunkX, int chunkZ, World world, LostCityChunkGenerator provider) { int cx = chunkX * 16; int cz = chunkZ * 16; BuildingInfo info = BuildingInfo.getBuildingInfo(chunkX, chunkZ, provider); if (info.hasBuilding) { BuildingInfo adjacent = info.getXmax(); int bottom = Math.max(adjacent.getCityGroundLevel() + 3, adjacent.hasBuilding ? adjacent.getMaxHeight() : (adjacent.getCityGroundLevel() + 3)); for (int z = 0; z < 15; z++) { for (int y = bottom; y < (info.getMaxHeight()); y++) { if (random.nextFloat() < provider.profile.VINE_CHANCE) { createVineStrip(random, world, bottom, BlockVine.WEST, new BlockPos(cx + 16, y, cz + z), new BlockPos(cx + 15, y, cz + z)); } } } } if (info.getXmax().hasBuilding) { BuildingInfo adjacent = info.getXmax(); int bottom = Math.max(info.getCityGroundLevel() + 3, info.hasBuilding ? info.getMaxHeight() : (info.getCityGroundLevel() + 3)); for (int z = 0; z < 15; z++) { for (int y = bottom; y < (adjacent.getMaxHeight()); y++) { if (random.nextFloat() < provider.profile.VINE_CHANCE) { createVineStrip(random, world, bottom, BlockVine.EAST, new BlockPos(cx + 15, y, cz + z), new BlockPos(cx + 16, y, cz + z)); } } } } if (info.hasBuilding) { BuildingInfo adjacent = info.getZmax(); int bottom = Math.max(adjacent.getCityGroundLevel() + 3, adjacent.hasBuilding ? adjacent.getMaxHeight() : (adjacent.getCityGroundLevel() + 3)); for (int x = 0; x < 15; x++) { for (int y = bottom; y < (info.getMaxHeight()); y++) { if (random.nextFloat() < provider.profile.VINE_CHANCE) { createVineStrip(random, world, bottom, BlockVine.NORTH, new BlockPos(cx + x, y, cz + 16), new BlockPos(cx + x, y, cz + 15)); } } } } if (info.getZmax().hasBuilding) { BuildingInfo adjacent = info.getZmax(); int bottom = Math.max(info.getCityGroundLevel() + 3, info.hasBuilding ? info.getMaxHeight() : (info.getCityGroundLevel() + 3)); for (int x = 0; x < 15; x++) { for (int y = bottom; y < (adjacent.getMaxHeight()); y++) { if (random.nextFloat() < provider.profile.VINE_CHANCE) { createVineStrip(random, world, bottom, BlockVine.SOUTH, new BlockPos(cx + x, y, cz + 15), new BlockPos(cx + x, y, cz + 16)); } } } } } private void createVineStrip(Random random, World world, int bottom, PropertyBool direction, BlockPos pos, BlockPos vineHolderPos) { if (world.isAirBlock(vineHolderPos)) { return; } if (!world.isAirBlock(pos)) { return; } world.setBlockState(pos, Blocks.VINE.getDefaultState().withProperty(direction, true)); pos = pos.down(); while (pos.getY() >= bottom && random.nextFloat() < .8f) { if (!world.isAirBlock(pos)) { return; } world.setBlockState(pos, Blocks.VINE.getDefaultState().withProperty(direction, true)); pos = pos.down(); } } private void generateLootSpawners(Random random, int chunkX, int chunkZ, World world, LostCityChunkGenerator chunkGenerator) { BuildingInfo info = BuildingInfo.getBuildingInfo(chunkX, chunkZ, chunkGenerator); for (Pair<BlockPos, String> pair : info.getMobSpawnerTodo()) { BlockPos pos = pair.getKey(); // Double check that it is still a spawner (could be destroyed by explosion) if (world.getBlockState(pos).getBlock() == Blocks.MOB_SPAWNER) { TileEntity tileentity = world.getTileEntity(pos); if (tileentity instanceof TileEntityMobSpawner) { TileEntityMobSpawner spawner = (TileEntityMobSpawner) tileentity; String id = pair.getValue(); String fixedId = EntityTools.fixEntityId(id); EntityTools.setSpawnerEntity(world, spawner, new ResourceLocation(fixedId), fixedId); } } } info.clearMobSpawnerTodo(); for (Pair<BlockPos, String> pair : info.getChestTodo()) { BlockPos pos = pair.getKey(); // Double check that it is still a chest (could be destroyed by explosion) IBlockState state = world.getBlockState(pos); if (state.getBlock() == Blocks.CHEST) { if (chunkGenerator.profile.GENERATE_LOOT) { createLootChest(random, world, pos, pair.getRight()); } } } info.clearChestTodo(); for (BlockPos pos : info.getGenericTodo()) { IBlockState state = world.getBlockState(pos); if (state.getBlock() == Blocks.GLOWSTONE) { world.setBlockState(pos, state, 3); } } info.clearGenericTodo(); } private void createLootChest(Random random, World world, BlockPos pos, String lootTable) { world.setBlockState(pos, Blocks.CHEST.getDefaultState().withProperty(BlockChest.FACING, EnumFacing.SOUTH)); TileEntity tileentity = world.getTileEntity(pos); if (tileentity instanceof TileEntityChest) { if (lootTable != null) { ((TileEntityChest) tileentity).setLootTable(new ResourceLocation(lootTable), random.nextLong()); } else { switch (random.nextInt(30)) { case 0: ((TileEntityChest) tileentity).setLootTable(LootTableList.CHESTS_DESERT_PYRAMID, random.nextLong()); break; case 1: ((TileEntityChest) tileentity).setLootTable(LootTableList.CHESTS_JUNGLE_TEMPLE, random.nextLong()); break; case 2: ((TileEntityChest) tileentity).setLootTable(LootTableList.CHESTS_VILLAGE_BLACKSMITH, random.nextLong()); break; case 3: ((TileEntityChest) tileentity).setLootTable(LootTableList.CHESTS_ABANDONED_MINESHAFT, random.nextLong()); break; case 4: ((TileEntityChest) tileentity).setLootTable(LootTableList.CHESTS_NETHER_BRIDGE, random.nextLong()); break; default: ((TileEntityChest) tileentity).setLootTable(LootTableList.CHESTS_SIMPLE_DUNGEON, random.nextLong()); break; } } } } @Override public void populate(int chunkX, int chunkZ) { BlockFalling.fallInstantly = true; int x = chunkX * 16; int z = chunkZ * 16; World w = this.worldObj; Biome Biome = w.getBiomeForCoordsBody(new BlockPos(x + 16, 0, z + 16)); this.rand.setSeed(w.getSeed()); long i1 = this.rand.nextLong() / 2L * 2L + 1L; long j1 = this.rand.nextLong() / 2L * 2L + 1L; this.rand.setSeed(chunkX * i1 + chunkZ * j1 ^ w.getSeed()); boolean flag = false; MinecraftForge.EVENT_BUS.post(new PopulateChunkEvent.Pre(this, w, rand, chunkX, chunkZ, flag)); ChunkPos cp = new ChunkPos(chunkX, chunkZ); if (profile.GENERATE_MINESHAFTS) { this.mineshaftGenerator.generateStructure(w, this.rand, cp); } if (profile.GENERATE_VILLAGES) { if (profile.PREVENT_VILLAGES_IN_CITIES) { if (!BuildingInfo.isCity(chunkX, chunkZ, this)) { flag = this.villageGenerator.generateStructure(w, this.rand, cp); } } else { flag = this.villageGenerator.generateStructure(w, this.rand, cp); } } if (profile.GENERATE_STRONGHOLDS) { this.strongholdGenerator.generateStructure(w, this.rand, cp); } if (profile.GENERATE_SCATTERED) { this.scatteredFeatureGenerator.generateStructure(w, this.rand, cp); } if (profile.GENERATE_OCEANMONUMENTS) { this.oceanMonumentGenerator.generateStructure(w, this.rand, cp); } int k1; int l1; int i2; if (profile.GENERATE_LAKES) { boolean isCity = BuildingInfo.isCity(chunkX, chunkZ, this); if (!profile.PREVENT_LAKES_RAVINES_IN_CITIES || !isCity) { if (Biome != Biomes.DESERT && Biome != Biomes.DESERT_HILLS && !flag && this.rand.nextInt(4) == 0 && TerrainGen.populate(this, w, rand, chunkX, chunkZ, flag, PopulateChunkEvent.Populate.EventType.LAKE)) { k1 = x + this.rand.nextInt(16) + 8; l1 = this.rand.nextInt(256); i2 = z + this.rand.nextInt(16) + 8; (new WorldGenLakes(Blocks.WATER)).generate(w, this.rand, new BlockPos(k1, l1, i2)); } if (TerrainGen.populate(this, w, rand, chunkX, chunkZ, flag, PopulateChunkEvent.Populate.EventType.LAVA) && !flag && this.rand.nextInt(8) == 0) { k1 = x + this.rand.nextInt(16) + 8; l1 = this.rand.nextInt(this.rand.nextInt(248) + 8); i2 = z + this.rand.nextInt(16) + 8; if (l1 < (profile.GROUNDLEVEL - profile.WATERLEVEL_OFFSET) || this.rand.nextInt(10) == 0) { (new WorldGenLakes(Blocks.LAVA)).generate(w, this.rand, new BlockPos(k1, l1, i2)); } } } } boolean doGen = false; if (profile.GENERATE_DUNGEONS) { doGen = TerrainGen.populate(this, w, rand, chunkX, chunkZ, flag, PopulateChunkEvent.Populate.EventType.DUNGEON); for (k1 = 0; doGen && k1 < 8; ++k1) { l1 = x + this.rand.nextInt(16) + 8; i2 = this.rand.nextInt(256); int j2 = z + this.rand.nextInt(16) + 8; (new WorldGenDungeons()).generate(w, this.rand, new BlockPos(l1, i2, j2)); } } BlockPos pos = new BlockPos(x, 0, z); Biome.decorate(w, this.rand, pos); if (TerrainGen.populate(this, w, rand, chunkX, chunkZ, flag, PopulateChunkEvent.Populate.EventType.ANIMALS)) { WorldEntitySpawner.performWorldGenSpawning(w, Biome, x + 8, z + 8, 16, 16, this.rand); } x += 8; z += 8; doGen = TerrainGen.populate(this, w, rand, chunkX, chunkZ, flag, PopulateChunkEvent.Populate.EventType.ICE); for (k1 = 0; doGen && k1 < 16; ++k1) { for (l1 = 0; l1 < 16; ++l1) { i2 = w.getPrecipitationHeight(new BlockPos(x + k1, 0, z + l1)).getY(); if (w.canBlockFreeze(new BlockPos(k1 + x, i2 - 1, l1 + z), false)) { w.setBlockState(new BlockPos(k1 + x, i2 - 1, l1 + z), Blocks.ICE.getDefaultState(), 2); } if (w.canSnowAt(new BlockPos(k1 + x, i2, l1 + z), true)) { w.setBlockState(new BlockPos(k1 + x, i2, l1 + z), Blocks.SNOW_LAYER.getDefaultState(), 2); } } } generateTrees(rand, chunkX, chunkZ, w, this); generateVines(rand, chunkX, chunkZ, w, this); generateLootSpawners(rand, chunkX, chunkZ, w, this); MinecraftForge.EVENT_BUS.post(new PopulateChunkEvent.Post(this, w, rand, chunkX, chunkZ, flag)); BlockFalling.fallInstantly = false; } @Override public boolean generateStructures(Chunk chunkIn, int x, int z) { boolean flag = false; if (profile.GENERATE_OCEANMONUMENTS) { if (chunkIn.getInhabitedTime() < 3600L) { flag |= this.oceanMonumentGenerator.generateStructure(this.worldObj, this.rand, new ChunkPos(x, z)); } } return flag; } @Override public List<Biome.SpawnListEntry> getPossibleCreatures(EnumCreatureType creatureType, BlockPos pos) { return getDefaultCreatures(creatureType, pos); } private List getDefaultCreatures(EnumCreatureType creatureType, BlockPos pos) { Biome Biome = this.worldObj.getBiomeForCoordsBody(pos); if (creatureType == EnumCreatureType.MONSTER) { if (profile.GENERATE_SCATTERED) { if (this.scatteredFeatureGenerator.isInsideStructure(pos)) { return this.scatteredFeatureGenerator.getScatteredFeatureSpawnList(); } } if (profile.GENERATE_OCEANMONUMENTS) { if (this.oceanMonumentGenerator.isPositionInStructure(this.worldObj, pos)) { return this.oceanMonumentGenerator.getScatteredFeatureSpawnList(); } } } return Biome.getSpawnableList(creatureType); } @Override public BlockPos clGetStrongholdGen(World worldIn, String structureName, BlockPos position) { return "Stronghold".equals(structureName) && this.strongholdGenerator != null ? CompatMapGenStructure.getClosestStrongholdPos(this.strongholdGenerator, worldIn, position) : null; } @Override public void recreateStructures(Chunk chunkIn, int x, int z) { if (profile.GENERATE_MINESHAFTS) { this.mineshaftGenerator.generate(this.worldObj, x, z, null); } if (profile.GENERATE_VILLAGES) { if (profile.PREVENT_VILLAGES_IN_CITIES) { if (!BuildingInfo.isCity(x, z, this)) { this.villageGenerator.generate(this.worldObj, x, z, null); } } else { this.villageGenerator.generate(this.worldObj, x, z, null); } } if (profile.GENERATE_STRONGHOLDS) { this.strongholdGenerator.generate(this.worldObj, x, z, null); } if (profile.GENERATE_SCATTERED) { this.scatteredFeatureGenerator.generate(this.worldObj, x, z, null); } if (profile.GENERATE_OCEANMONUMENTS) { this.oceanMonumentGenerator.generate(this.worldObj, x, z, null); } } @Override public ILostChunkInfo getChunkInfo(int chunkX, int chunkZ) { return BuildingInfo.getBuildingInfo(chunkX, chunkZ, this); } @Override public int getRealHeight(int level) { return profile.GROUNDLEVEL + level * 6; } }
Removed debug
src/main/java/mcjty/lostcities/dimensions/world/LostCityChunkGenerator.java
Removed debug
Java
mit
760faff1d570436112a75f2db6acf369263a521c
0
jurgendl/jhaws,jurgendl/jhaws,jurgendl/jhaws,jurgendl/jhaws
package org.jhaws.common.lang; import java.io.IOException; import java.io.Serializable; import java.io.UncheckedIOException; import java.lang.reflect.Array; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Deque; import java.util.EnumSet; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.NoSuchElementException; import java.util.Objects; import java.util.Optional; import java.util.Properties; import java.util.Queue; import java.util.Set; import java.util.SortedMap; import java.util.SortedSet; import java.util.Spliterator; import java.util.Spliterators; import java.util.Stack; import java.util.TreeMap; import java.util.TreeSet; import java.util.concurrent.BlockingDeque; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentSkipListMap; import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.LinkedTransferQueue; import java.util.concurrent.TransferQueue; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import java.util.function.BiConsumer; import java.util.function.BiFunction; import java.util.function.BiPredicate; import java.util.function.BinaryOperator; import java.util.function.BooleanSupplier; import java.util.function.Consumer; import java.util.function.DoubleSupplier; import java.util.function.Function; import java.util.function.IntFunction; import java.util.function.IntSupplier; import java.util.function.LongSupplier; import java.util.function.Predicate; import java.util.function.Supplier; import java.util.function.UnaryOperator; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collector; import java.util.stream.Collectors; import java.util.stream.DoubleStream; import java.util.stream.IntStream; import java.util.stream.LongStream; import java.util.stream.Stream; import java.util.stream.StreamSupport; import org.apache.commons.lang3.builder.CompareToBuilder; import org.apache.commons.lang3.builder.EqualsBuilder; import org.jhaws.common.lang.functions.EBiConsumer; import org.jhaws.common.lang.functions.EBooleanSupplier; import org.jhaws.common.lang.functions.EConsumer; import org.jhaws.common.lang.functions.EDoubleSupplier; import org.jhaws.common.lang.functions.EFunction; import org.jhaws.common.lang.functions.EIntSupplier; import org.jhaws.common.lang.functions.ELongSupplier; import org.jhaws.common.lang.functions.EPredicate; import org.jhaws.common.lang.functions.ERunnable; import org.jhaws.common.lang.functions.ESupplier; // http://infotechgems.blogspot.be/2011/11/java-collections-performance-time.html // TODO https://www.techempower.com/blog/2016/10/19/efficient-multiple-stream-concatenation-in-java/ /** * @see java.util.stream.Stream * @see java.util.stream.StreamSupport * @see java.util.stream.Collectors * @see java.util.stream.Collector * @since 1.8 * @see https://technology.amis.nl/2013/10/05/java-8-collection-enhancements- leveraging-lambda-expressions-or-how-java-emulates-sql/ */ public interface CollectionUtils8 { public static class Comparators { public static class CaseInsensitiveComparator implements Comparator<String> { @Override public int compare(String o1, String o2) { return (o1 == null ? "" : o1).compareToIgnoreCase((o2 == null ? "" : o2)); } } public static class MapEntryKVComparator<K, V> implements Comparator<Map.Entry<K, V>> { @Override public int compare(Entry<K, V> o1, Entry<K, V> o2) { return new CompareToBuilder().append(o1.getKey(), o2.getKey()).append(o1.getValue(), o2.getValue()).toComparison(); } } public static class MapEntryVKComparator<K, V> implements Comparator<Map.Entry<K, V>> { @Override public int compare(Entry<K, V> o1, Entry<K, V> o2) { return new CompareToBuilder().append(o1.getValue(), o2.getValue()).append(o1.getKey(), o2.getKey()).toComparison(); } } } public static class RegexIterator implements EnhancedIterator<String> { protected Pattern pattern; protected String regex; protected Matcher matcher; protected Boolean hasNext = null; public RegexIterator(String text, String regex) { this.pattern = Pattern.compile(regex); this.regex = regex; this.matcher = pattern.matcher(text); } public RegexIterator(String text, Pattern regex) { this.pattern = regex; this.regex = regex.toString(); this.matcher = pattern.matcher(text); } public RegexIterator(Pattern regex, String text) { this.pattern = regex; this.regex = regex.toString(); this.matcher = pattern.matcher(text); } @Override public boolean hasNext() { if (hasNext == null) { hasNext = matcher.find(); } return hasNext; } @Override public String next() { if (hasNext == null) { hasNext(); } if (hasNext) { hasNext = null; return matcher.group(); } return null; } } public static class PathIterator implements EnhancedIterator<Path> { protected Path path; public PathIterator(Path path) { this.path = path; } @Override public boolean hasNext() { Path parent = this.path.getParent(); return parent != null; } @Override public Path next() { this.path = this.path.getParent(); return this.path; } } public static class ProjectionIterator<T> implements EnhancedIterator<T> { protected T current; protected T next; protected Function<T, T> projection; public ProjectionIterator(T object, boolean include, Function<T, T> projection) { this.current = object; this.projection = projection; if (include) next = current; } @Override public boolean hasNext() { if (next == null) { next = projection.apply(current); } return next != null; } @Override public T next() { hasNext(); if (next == null) { throw new NoSuchElementException(); } current = next; next = null; return current; } } public static interface Opt<T> extends Supplier<T> { /** default vorig type */ <X> Opt<X> opt(Function<T, X> getter); /** default vorig type */ default <X> Opt<X> nest(Function<T, X> getter) { return opt(getter); } /** ga verder eager */ <X> OptEager<X> eager(Function<T, X> getter); /** ga verder reusable = lazy */ <X> OptReusable<T, X> reusable(Function<T, X> getter); /** ga verder reusable = lazy */ default <X> OptReusable<T, X> lazy(Function<T, X> getter) { return reusable(getter); } default <X> OptEager<X> map(Function<T, X> map) { T v = get(); return Opt.eager(/* v == null ? null : */ map.apply(v)); } default <X> OptEager<X> mapOrNull(Function<T, X> map) { return mapOr(map, (X) null); } default <X> OptEager<X> mapOr(Function<T, X> map, X value) { return mapOr(map, (Supplier<X>) () -> value); } default <X> OptEager<X> mapOr(Function<T, X> map, Supplier<X> value) { T v = get(); return Opt.eager(v == null ? value.get() : map.apply(v)); } /** default eager */ public static <T> Opt<T> optional(T value) { return eager(value); } /** start eager */ public static <T> OptEager<T> eager(T value) { return new OptEager<>(value); } /** start reusable = lazy */ public static <T> OptReusable<?, T> reusable(T value) { return new OptReusable<>(value); } /** start reusable = lazy */ public static <T> OptReusable<?, T> lazy(T value) { return reusable(value); } <X> X first(@SuppressWarnings("unchecked") Function<T, X>... getters); default boolean isNull() { return CollectionUtils8.isNull().test(get()); } default boolean isBlankOrNull() { return CollectionUtils8.isBlankOrNull().test(get()); } default boolean isNotNull() { return CollectionUtils8.isNotNull().test(get()); } default boolean isNotBlankAndNotNull() { return CollectionUtils8.isNotBlankAndNotNull().test(get()); } default void consume(Consumer<T> consumer) { T value = get(); if (value != null) { consumer.accept(value); } } /** geeft waarde terug */ @Override T get(); /** voert {@link #opt(Function)} uit en dan {@link #get()} */ default <X> X get(Function<T, X> get) { return opt(get).get(); } /** * voert {@link #get()} uit en wanneer null, voert {@link Supplier} uit en geeft die waarde */ default T or(Supplier<T> supplier) { return Optional.ofNullable(get()).orElseGet(supplier); } /** voert {@link #get()} uit en wanneer null, geeft meegegeven waarde */ default T or(T value) { return Optional.ofNullable(get()).orElse(value); } default T orNull() { return or((T) null); } default T or(Opt<T> supplier) { return or(supplier.get()); } /** wrap in Value */ default Value<T> getValue() { return new Value<>(get()); } /** wrap in Value */ default <X> Value<X> getValue(Function<T, X> get) { return new Value<>(get(get)); } /** wrap in Value */ default Value<T> orValue(Supplier<T> supplier) { return new Value<>(or(supplier)); } /** wrap in Value */ default Value<T> orValue(T value) { return new Value<>(or(value)); } /** wrap in Value */ default Value<T> orNullValue() { return new Value<>(orNull()); } /** wrap in Value */ default Value<T> orValue(Opt<T> supplier) { return new Value<>(or(supplier)); } } static class OptEager<T> implements Opt<T> { protected final T value; protected OptEager(T value) { this.value = value; } @Override public T get() { return value; } @Override public <P> OptEager<P> opt(Function<T, P> get) { return eager(get); } @Override public <P> OptEager<P> eager(Function<T, P> get) { return new OptEager<>(value == null ? null : get.apply(value)); } @Override public <P> OptReusable<T, P> reusable(Function<T, P> get) { return new OptReusable<>(get()).opt(get); } @Override public <X> X first(@SuppressWarnings("unchecked") Function<T, X>... getters) { return streamArray(getters).map(g -> get(g)).filter(CollectionUtils8.isNotBlankAndNotNull()).findFirst().orElse(null); } } static class OptReusable<P, T> implements Opt<T> { protected final OptReusable<P, T> parent; protected final Function<P, T> getter; protected final T value; protected OptReusable(T value) { this.value = value; this.parent = null; this.getter = null; } protected OptReusable(OptReusable<P, T> parent, Function<P, T> getter) { this.value = null; this.parent = parent; this.getter = getter; } @Override @SuppressWarnings({ "unchecked", "rawtypes" }) public T get() { if (value != null) return value; Stack<OptReusable> stack = new Stack<>(); stack.add(this); OptReusable current = this.parent; while (current != null) { stack.add(current); current = current.parent; } Object currentValue = stack.pop().value; while (!stack.isEmpty() && currentValue != null) { current = stack.pop(); currentValue = current.getter.apply(currentValue); } return (T) currentValue; } @Override public <X> OptReusable<T, X> opt(Function<T, X> get) { return reusable(get); } @Override public <X> OptEager<X> eager(Function<T, X> get) { return new OptEager<>(get()).opt(get); } @Override @SuppressWarnings("unchecked") public <X> OptReusable<T, X> reusable(Function<T, X> get) { return new OptReusable<>((OptReusable<T, X>) this, get); } @Override public <X> X first(@SuppressWarnings("unchecked") Function<T, X>... getters) { return streamArray(getters).map(g -> get(g)).filter(CollectionUtils8.isNotBlankAndNotNull()).findFirst().orElse(null); } } public static class CustomCollector<T, A, R> implements Collector<T, A, R> { protected Supplier<A> supplier; protected BiConsumer<A, T> accumulator; protected BinaryOperator<A> combiner; protected Function<A, R> finisher; protected Set<Characteristics> characteristics; public CustomCollector(Supplier<A> supplier, BiConsumer<A, T> accumulator, BinaryOperator<A> combiner, Function<A, R> finisher, Set<Characteristics> characteristics) { this.supplier = supplier; this.accumulator = accumulator; this.combiner = combiner; this.finisher = finisher; this.characteristics = characteristics; } @SuppressWarnings("unchecked") public CustomCollector(Supplier<A> supplier, BiConsumer<A, T> accumulator, BinaryOperator<A> combiner, Set<Characteristics> characteristics) { this(supplier, accumulator, combiner, x -> (R) x, characteristics); } @SuppressWarnings("unchecked") public CustomCollector(Supplier<A> supplier, BiConsumer<A, T> accumulator, BinaryOperator<A> combiner) { this(supplier, accumulator, combiner, x -> (R) x, Collections.unmodifiableSet(EnumSet.of(Collector.Characteristics.IDENTITY_FINISH))); } public CustomCollector() { super(); } @Override public Supplier<A> supplier() { return supplier; } @Override public BiConsumer<A, T> accumulator() { return accumulator; } @Override public BinaryOperator<A> combiner() { return combiner; } @Override public Function<A, R> finisher() { return finisher; } @Override public Set<Characteristics> characteristics() { return characteristics; } public Supplier<A> getSupplier() { return this.supplier; } public void setSupplier(Supplier<A> supplier) { this.supplier = supplier; } public BiConsumer<A, T> getAccumulator() { return this.accumulator; } public void setAccumulator(BiConsumer<A, T> accumulator) { this.accumulator = accumulator; } public BinaryOperator<A> getCombiner() { return this.combiner; } public void setCombiner(BinaryOperator<A> combiner) { this.combiner = combiner; } public Function<A, R> getFinisher() { return this.finisher; } public void setFinisher(Function<A, R> finisher) { this.finisher = finisher; } public Set<Characteristics> getCharacteristics() { return this.characteristics; } public void setCharacteristics(Set<Characteristics> characteristics) { this.characteristics = characteristics; } } public static class ListCollector<T> extends CustomCollector<T, List<T>, List<T>> { public ListCollector() { setSupplier(newList()); BiConsumer<List<T>, T> accumulator0 = elementsListAccumulator(); setAccumulator(accumulator0); setCombiner(elementsListCombiner(accumulator0)); setFinisher(CollectionUtils8.cast()); setCharacteristics(Collections.unmodifiableSet(EnumSet.of(Collector.Characteristics.IDENTITY_FINISH))); } } public static class ListUQCollector<T> extends ListCollector<T> { public ListUQCollector() { BiConsumer<List<T>, T> accumulator0 = uniqueElementsListAccumulator(); setAccumulator(accumulator0); setCombiner(elementsListCombiner(accumulator0)); } } /** * always use first value for key */ public static <T> BinaryOperator<T> keepFirst() { return (p1, p2) -> p1; } /** * always use last value for key */ public static <T> BinaryOperator<T> keepLast() { return (p1, p2) -> p2; } public static <T> T last(Stream<T> stream) { return stream.reduce(keepLast()).orElse(null); } public static <K, V> Entry<K, V> last(SortedMap<K, V> map) { return map.entrySet().stream().reduce(keepLast()).orElse(null); } /** * see {@link #keepLast()} */ public static <V> BinaryOperator<V> acceptDuplicateKeys() { return keepLast(); } /** * rejects !different! keys for the same value * * @throws IllegalArgumentException */ public static <V> BinaryOperator<V> rejectDuplicateKeys() throws IllegalArgumentException { return (a, b) -> { if (new EqualsBuilder().append(a, b).isEquals()) return a; throw new IllegalArgumentException("duplicate key: " + a + " <> " + b); }; } @SuppressWarnings("unchecked") public static <T> T[] array(T item, T... items) { if (item == null && (items == null || items.length == 0)) { return (T[]) new Object[0]; } if (items == null || items.length == 0) { return (T[]) new Object[] { item }; } if (item == null) { return items; } int length = items.length; // FIXME cheaper // operation T[] newarray = Arrays.copyOf(items, 1 + length); newarray[0] = item; System.arraycopy(items, 0, newarray, 1, length); return newarray; } @SuppressWarnings("unchecked") public static <T> T[] array(T[] items, T item) { if (item == null && (items == null || items.length == 0)) { return (T[]) new Object[0]; } if (items == null || items.length == 0) { return (T[]) new Object[] { item }; } if (item == null) { return items; } int length = items.length; T[] newarray = Arrays.copyOf(items, 1 + length); newarray[newarray.length - 1] = item; return newarray; } @SuppressWarnings("unchecked") public static <T> T[] array(T[] items1, T[] items2) { if ((items1 == null || items1.length == 0) && (items2 == null || items2.length == 0)) { return (T[]) new Object[0]; } if (items1 == null || items1.length == 0) { return items2; } if (items2 == null || items2.length == 0) { return items1; } int length1 = items1.length; int length2 = items2.length; T[] newarray = Arrays.copyOf(items1, length1 + length2); System.arraycopy(items2, 0, newarray, length1, length2); return newarray; } public static <T> T[] array(Class<T> componentType, Collection<T> collection) { return array(componentType, collection.stream()); } public static <T> T[] array(Class<T> componentType, Stream<T> stream) { return stream.toArray(newArray(componentType)); } @SuppressWarnings("unchecked") public static <T> IntFunction<T[]> newArray(Class<T> componentType) { return length -> (T[]) Array.newInstance(componentType, length); } public static <T> T[] newArray(Class<T> componentType, int size) { return CollectionUtils8.<T> newArray(componentType).apply(size); } @SuppressWarnings("unchecked") public static <K, V> Entry<K, V>[] array(Map<K, V> map) { return map.entrySet().toArray((Map.Entry<K, V>[]) new Map.Entry[0]); } @SuppressWarnings("unchecked") public static <X, T> Function<X, T> cast() { return x -> (T) x; } public static <T> Function<Object, T> cast(Class<T> type) { return o -> type.cast(o); } public static <T> T cast(Class<T> type, Object object) { return cast(type).apply(object); } @SuppressWarnings("unchecked") public static <T, C extends Collection<T>> Collector<T, ?, C> collector(C collection) { if (collection instanceof Deque) { return (Collector<T, ?, C>) CollectionUtils8.<T> collectDeque(); } if (collection instanceof Queue) { return (Collector<T, ?, C>) CollectionUtils8.<T> collectQueue(); } if (collection instanceof List) { return (Collector<T, ?, C>) CollectionUtils8.<T> collectList(); } if (collection instanceof SortedSet) { return (Collector<T, ?, C>) CollectionUtils8.<T> collectSortedSet(); } if (collection instanceof Set) { return (Collector<T, ?, C>) CollectionUtils8.<T> collectSet(); } throw new UnsupportedOperationException(collection.getClass().getName()); } @SafeVarargs public static <T, C extends Collection<T>> C filter(boolean parallel, C collection, Predicate<? super T>... predicates) { AtomicReference<Stream<T>> streamReference = new AtomicReference<>(stream(parallel, collection)); streamArray(predicates).forEach(predicate -> streamReference.set(streamReference.get().filter(predicate))); C collected = streamReference.get().collect(collector(collection)); return collected; } @SafeVarargs public static <T, C extends Collection<T>> C filter(C collection, Predicate<? super T>... predicates) { return filter(false, collection, predicates); } public static <T> T last(List<T> dd) { int size = dd.size(); return size == 0 ? null : dd.get(size - 1); } public static <K, V> EnhancedMap<K, V> map(Collection<Map.Entry<K, V>> entries) { return map(false, entries); } public static <K, V> EnhancedMap<K, V> map(boolean parallel, Collection<? extends Map.Entry<K, V>> entries) { return map(stream(parallel, entries)); } public static <K, V> EnhancedMap<K, V> map(Stream<? extends Map.Entry<K, V>> stream) { return map(stream, CollectionUtils8.<K, V> newLinkedMap()); } public static <K, V, M extends Map<K, V>> M map(Stream<? extends Map.Entry<K, V>> stream, Supplier<M> mapSupplier) { BinaryOperator<V> keepLast = CollectionUtils8.<V> keepLast(); return map(stream, mapSupplier, keepLast); } public static <K, V, M extends Map<K, V>> M map(Stream<? extends Map.Entry<K, V>> stream, Supplier<M> mapSupplier, BinaryOperator<V> choice) { Function<Entry<K, V>, K> keyMapper = CollectionUtils8.<K, V> keyMapper(); Function<Entry<K, V>, V> valueMapper = CollectionUtils8.<K, V> valueMapper(); Collector<Entry<K, V>, ?, M> c = Collectors.toMap(keyMapper, valueMapper, choice, mapSupplier); return stream.collect(c); } public static <K, V> Supplier<EnhancedLinkedHashMap<K, V>> newLinkedMap() { return EnhancedLinkedHashMap::new; } public static <K, V> Supplier<EnhancedMap<K, V>> newMap() { return EnhancedHashMap::new; } public static <K, V> Supplier<EnhancedSortedMap<K, V>> newSortedMap() { return EnhancedTreeMap::new; } public static <K, V> Supplier<EnhancedTreeMap<K, V>> newNavigableMap() { return EnhancedTreeMap::new; } public static <K, V> Supplier<ConcurrentSkipListMap<K, V>> newConcurrentNavigableMap() { return ConcurrentSkipListMap::new; } public static <K, V> Supplier<ConcurrentHashMap<K, V>> newConcurrentMap() { return ConcurrentHashMap::new; } public static <T> Supplier<Stack<T>> newStack() { return Stack::new; } public static <T> Supplier<Deque<T>> newDeque() { return EnhancedLinkedList::new; } public static <T> Supplier<List<T>> newList() { return EnhancedArrayList::new; } public static <T> Supplier<Queue<T>> newQueue() { return EnhancedLinkedList::new; } public static <T> Supplier<Set<T>> newSet() { return EnhancedHashSet::new; } public static <T> Supplier<SortedSet<T>> newSortedSet() { return EnhancedTreeSet::new; } public static <T> Supplier<BlockingQueue<T>> newBlockingQueue() { return LinkedBlockingDeque::new; } public static <T> Supplier<BlockingDeque<T>> newBlockingDeque() { return LinkedBlockingDeque::new; } public static <T> Supplier<TransferQueue<T>> newTransferQueue() { return LinkedTransferQueue::new; } public static <T, C extends Collection<T>> Collector<T, ?, C> toCollector(Supplier<C> supplier) { return Collectors.toCollection(supplier); } public static <T> Collector<T, ?, Stack<T>> collectStack() { return toCollector(newStack()); } public static <T> Collector<T, ?, Deque<T>> collectDeque() { return toCollector(newDeque()); } public static <T> Collector<T, ?, List<T>> collectList() { return toCollector(newList()); } public static <T, C extends Collection<T>> Collector<T, ?, C> collection(Supplier<C> newCollection) { return Collectors.toCollection(newCollection); } public static <T> ListCollector<T> collectListUQ() { return new ListUQCollector<>(); } public static <T> Collector<T, ?, Queue<T>> collectQueue() { return toCollector(newQueue()); } public static <T> Collector<T, ?, Set<T>> collectSet() { return Collectors.toSet(); } public static <T> Collector<T, ?, SortedSet<T>> collectSortedSet() { return toCollector(newSortedSet()); } public static <T extends Comparable<? super T>> List<T> sort(Collection<T> collection) { return sort(false, collection); } public static <T extends Comparable<? super T>> List<T> sort(boolean parallel, Collection<T> collection) { return stream(parallel, collection).sorted().collect(toCollector(newList())); } public static <T> List<T> sort(boolean parallel, Collection<T> collection, Comparator<? super T> comparator) { return stream(parallel, collection).sorted(comparator).collect(toCollector(newList())); } public static <T> List<T> sort(Collection<T> collection, Comparator<? super T> comparator) { return sort(false, collection, comparator); } public static <T, A> List<T> sortBy(Collection<T> collection, List<A> orderByMe, Function<T, A> map) { return collection.stream().sorted(comparator(orderByMe, map)).collect(collectList()); } public static <T, A> Comparator<T> comparator(List<A> orderByMe, Function<T, A> map) { return (x, y) -> Integer.valueOf(noNegIndex(orderByMe.indexOf(map.apply(x)))) .compareTo(Integer.valueOf(noNegIndex(orderByMe.indexOf(map.apply(y))))); } public static <T> Comparator<T> comparator(List<T> orderByMe) { return comparator(orderByMe, self()); } public static <T> List<T> sortBy(Collection<T> collection, List<T> orderByMe) { return sortBy(collection, orderByMe, self()); } public static <T, S extends Comparable<? super S>> Stream<T> sortBy(Stream<T> sortMe, Map<T, S> sortByMe) { return sortMe.sorted((x, y) -> sortByMe.get(x).compareTo(sortByMe.get(y))); } public static <T, A> Stream<T> sortBy(Stream<T> collection, List<A> orderByMe, Function<T, A> map) { return collection.sorted(comparator(orderByMe, map)); } public static <T> Stream<T> sortBy(Stream<T> collection, List<T> orderByMe) { return sortBy(collection, orderByMe, self()); } public static <T, S extends Comparable<? super S>> List<T> sortBy(Collection<T> sortMe, Map<T, S> sortByMe) { return sortMe.stream().sorted((x, y) -> sortByMe.get(x).compareTo(sortByMe.get(y))).collect(collectList()); } public static <T> Function<T, T> id() { return self(); } public static <T> Function<T, T> self() { return Function.identity(); } public static <T> UnaryOperator<T> idu() { return selfu(); } public static <T> UnaryOperator<T> selfu() { return t -> t; } public static int noNegIndex(int i) { return i == -1 ? Integer.MAX_VALUE : i; } public static <T> Stream<T> stream(Collection<T> collection) { return stream(false, collection); } public static <T> Stream<T> stream(boolean parallel, Collection<T> collection) { return collection == null ? Stream.empty() : StreamSupport.stream(collection.spliterator(), parallel); } public static <T> Stream<T> stream(Iterable<T> iterable) { return stream(false, iterable); } public static <T> Stream<T> stream(Iterator<T> iterator) { return stream(false, iterator); } public static <T> Stream<T> stream(Enumeration<T> enumeration) { return stream(false, enumeration); } public static <T> Stream<T> stream(boolean parallel, Iterable<T> iterable) { return iterable == null ? Stream.empty() : StreamSupport.stream(iterable.spliterator(), parallel); } public static <T> Stream<T> stream(boolean parallel, Iterator<T> iterator) { return iterator == null ? Stream.empty() : StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterator, 0), parallel); } public static <T> Stream<T> stream(boolean parallel, Enumeration<T> enumeration) { return enumeration == null ? Stream.empty() : StreamSupport.stream(Spliterators.spliteratorUnknownSize(asIterator(enumeration), 0), parallel); } public static <E> Iterator<E> asIterator(Enumeration<E> enumeration) { return new Iterator<E>() { @Override public boolean hasNext() { return enumeration.hasMoreElements(); } @Override public E next() { return enumeration.nextElement(); } }; } public static Stream<String> lines(Path path) { try { return Files.lines(path); } catch (IOException e) { throw new UncheckedIOException(e); } } public static <K, V> Stream<V> streamValues(Map<K, V> map) { return stream(map).map(valueMapper()); } public static <K, V> Stream<Stream<V>> streamDeepValues(Map<K, ? extends Collection<V>> map) { return stream(map).map(valueMapper()).map(collection -> stream(collection)); } public static <K, V> Stream<Map.Entry<K, V>> stream(Map<K, V> map) { return stream(false, map); } public static <K, V> Stream<Map.Entry<K, V>> stream(boolean parallel, Map<K, V> map) { return map == null ? Stream.empty() : StreamSupport.stream(map.entrySet().spliterator(), parallel); } public static Stream<Path> stream(Path path) { return stream(false, path); } public static Stream<Path> stream(boolean parallel, Path path) { return StreamSupport.stream(path.spliterator(), parallel); } @SafeVarargs public static <T> Stream<T> streamArray(T... array) { return streamArray(false, array); } @SafeVarargs public static <T> Stream<T> streamArray(boolean parallel, T... array) { if (array == null) return Stream.empty(); // StreamSupport.stream(Spliterators.spliterator(array, 0, array.length, // Spliterator.ORDERED | Spliterator.IMMUTABLE), parallel); Stream<T> stream = Arrays.stream(array); if (parallel) stream = stream.parallel(); return stream; } public static <T> Stream<T> streamDetached(Collection<T> collection) { return streamDetached(false, collection); } @SuppressWarnings("unchecked") public static <T> Stream<T> streamDetached(boolean parallel, Collection<T> collection) { return streamArray(parallel, array((Class<T>) Object.class, collection)); } public static <K, V> Stream<Map.Entry<K, V>> streamDetached(Map<K, V> map) { return streamDetached(false, map); } public static <K, V> Stream<Map.Entry<K, V>> streamDetached(boolean parallel, Map<K, V> map) { return streamArray(parallel, array(map)); } public static Stream<Path> streamFully(Path path) { return stream(new PathIterator(path)); } public static <T, U> Stream<U> stream(Collection<T> input, Function<T, Collection<U>> mapping) { return input.stream().map(mapping).map(Collection::stream).flatMap(id()); } public static <T> List<T> toList(Collection<T> collection) { return toList(true, collection); } public static <T> List<T> toList(boolean copy, Collection<T> collection) { return !copy && collection instanceof List ? (List<T>) collection : stream(collection).collect(collectList()); } public static <K, V> Map<K, V> toMap(Map<K, V> map) { return toMap(true, map); } public static <K, V> Map<K, V> toMap(boolean copy, Map<K, V> map) { return !copy /* && map instanceof Map */ ? (Map<K, V>) map : stream(map).collect(collectMap(Entry::getKey, Entry::getValue)); } public static <K, V> SortedMap<K, V> toSortedMap(Map<K, V> map) { return toSortedMap(true, map); } public static <K, V> SortedMap<K, V> toSortedMap(boolean copy, Map<K, V> map) { return !copy && map instanceof SortedMap ? (SortedMap<K, V>) map : stream(map).collect(collectSortedMap(Entry::getKey, Entry::getValue)); } @SafeVarargs public static <T> List<T> toList(T... array) { return streamArray(array).collect(collectList()); } public static <T> Set<T> toSet(Collection<T> collection) { return toSet(true, collection); } public static <T> Set<T> toSet(boolean copy, Collection<T> collection) { return !copy && collection instanceof Set ? (Set<T>) collection : stream(collection).collect(collectSet()); } @SafeVarargs public static <T> Set<T> toSet(T... array) { return streamArray(array).collect(collectSet()); } public static <T> SortedSet<T> toSortedSet(Collection<T> collection) { return toSortedSet(true, collection); } public static <T> SortedSet<T> toSortedSet(boolean copy, Collection<T> collection) { return !copy && collection instanceof SortedSet ? (SortedSet<T>) collection : stream(collection).collect(collectSortedSet()); } @SafeVarargs public static <T> SortedSet<T> toSortedSet(T... array) { return streamArray(array).collect(collectSortedSet()); } public static <T> Queue<T> toQueue(Collection<T> collection) { return stream(collection).collect(collectQueue()); } @SafeVarargs public static <T> Queue<T> toQueue(T... array) { return streamArray(array).collect(collectQueue()); } public static <T> Deque<T> toDeque(Collection<T> collection) { return stream(collection).collect(collectDeque()); } @SafeVarargs public static <T> Deque<T> toDeque(T... array) { return streamArray(array).collect(collectDeque()); } public static <T> Stack<T> toStack(Collection<T> collection) { return stream(collection).collect(collectStack()); } @SafeVarargs public static <T> Stack<T> toStack(T... array) { return streamArray(array).collect(collectStack()); } public static <T, C extends Collection<T>> C to(T[] array, Supplier<C> supplier) { return to(array, toCollector(supplier)); } public static <T, C extends Collection<T>> C to(T[] array, Collector<T, ?, C> collector) { return streamArray(array).collect(collector); } public static <T, C extends Collection<T>> C to(Collection<T> collection, Supplier<C> supplier) { return to(collection, toCollector(supplier)); } public static <T, C extends Collection<T>> C to(Collection<T> collection, Collector<T, ?, C> collector) { return stream(collection).collect(collector); } public static <T> boolean containedInAny(Collection<T> c1, Collection<T> c2) { return c1.stream().anyMatch(c2::contains); } public static <T> Predicate<T> not(Predicate<T> t) { return t.negate(); } public static <T> Predicate<T> isNotBlankAndNotNull() { return t -> t instanceof String ? isNotBlank().test(String.class.cast(t)) : isNotNull().test(t); } public static <T> Predicate<T> isBlankOrNull() { return t -> t instanceof String ? isBlank().test(String.class.cast(t)) : isNull().test(t); } public static Predicate<String> isNotBlank() { return org.apache.commons.lang3.StringUtils::isNotBlank; } public static Predicate<String> isBlank() { return org.apache.commons.lang3.StringUtils::isBlank; } public static <T> Predicate<T> isNotNull() { return Objects::nonNull; } public static <T> Predicate<T> isNull() { return Objects::isNull; } public static <T> Predicate<T> is(T x) { return t -> isEquals(t, x); } public static <T> Predicate<T> isNot(T x) { return not(is(x)); } public static <E> Predicate<E> containedIn(Collection<E> collection) { return collection::contains; } public static <T, E> Predicate<T> containedIn(Collection<E> collection, Function<T, E> converter) { return e -> collection.contains(converter.apply(e)); } public static <K> Predicate<K> keyContainedIn(Map<K, ?> map) { return map::containsKey; } public static <T, K> Predicate<T> keyContainedIn(Map<K, ?> map, Function<T, K> converter) { return e -> map.containsKey(converter.apply(e)); } public static <V> Predicate<V> valueContainedIn(Map<?, V> map) { return map::containsValue; } public static <T, V> Predicate<T> valueContainedIn(Map<?, V> map, Function<T, V> converter) { return e -> map.containsValue(converter.apply(e)); } public static <E> Predicate<E> notContainedIn(Collection<E> collection) { return not(containedIn(collection)); } public static <T, E> Predicate<T> notContainedIn(Collection<E> collection, Function<T, E> converter) { return not(containedIn(collection, converter)); } public static <K> Predicate<K> keyNotContainedIn(Map<K, ?> map) { return not(keyContainedIn(map)); } public static <T, K> Predicate<T> keyNotContainedIn(Map<K, ?> map, Function<T, K> converter) { return not(keyContainedIn(map, converter)); } public static <V> Predicate<V> valueNotContainedIn(Map<?, V> map) { return not(valueContainedIn(map)); } public static <T, V> Predicate<T> valueNotContainedIn(Map<?, V> map, Function<T, V> converter) { return not(valueContainedIn(map, converter)); } public static <X, Y> Function<X, Y> makeNull() { return x -> null; } public static <X> Supplier<X> supplyNull() { return () -> null; } public static <X> Predicate<X> always() { return x -> true; } public static <X> Predicate<X> always(boolean b) { return x -> b; } public static <X> Predicate<X> never() { return x -> false; } public static <X> Predicate<X> never(boolean b) { return x -> !b; } public static <X, Y> BiPredicate<X, Y> always2() { return (x, y) -> true; } public static <X, Y> BiPredicate<X, Y> always2(boolean b) { return (x, y) -> b; } public static <X, Y> BiPredicate<X, Y> never2() { return (x, y) -> false; } public static <X, Y> BiPredicate<X, Y> never2(boolean b) { return (x, y) -> !b; } public static IntStream streamp(String text) { return text.chars(); } public static Stream<Character> stream(String text) { return streamp(text).mapToObj(i -> (char) i); } public static Stream<Character> stream(char[] text) { return stream(new String(text)); } public static Stream<Boolean> stream(Boolean... b) { return IntStream.range(0, b.length).mapToObj(idx -> b[idx]); } public static Stream<Character> stream(Character[] text) { return Arrays.stream(text); } public static <T> List<Map.Entry<T, T>> match(List<T> keys, List<T> values) { return values.stream() .parallel() .filter(containedIn(keys)) .map(value -> new Pair<>(keys.get(keys.indexOf(value)), value)) .collect(collectList()); } public static <T> T optional(T value, Supplier<T> orElse) { return Optional.ofNullable(value).orElseGet(orElse); } public static <T> T optional(T oldValue, T newValue, Consumer<T> whenDifferent) { if (notEquals(oldValue, newValue)) { whenDifferent.accept(newValue); return newValue; } return oldValue; } public static <T> Consumer<T> consume() { return x -> { // }; } public static <T, U> BiConsumer<T, U> biconsume() { return (x, y) -> { return; }; } public static <T> String joinArray(String delimiter, T[] strings) { return join(delimiter, streamArray(strings)); } public static <T> String joinArray(T[] strings) { return join(" ", streamArray(strings)); } public static <T> String join(Collection<T> strings) { return join(" ", stream(strings)); } public static <T> String join(String delimiter, Collection<T> strings) { return join(delimiter, stream(strings)); } public static <T> String join(Stream<T> stream) { return join(" ", stream); } public static <T> String join(String delimiter, Stream<T> stream) { return stream// .filter(Objects::nonNull)// .map(String::valueOf)// .map(String::trim)// .filter(StringUtils::isNotBlank)// .collect(Collectors.joining(delimiter)); } public static <T> String join(String delimiter, boolean skipNull, boolean trim, Stream<T> stream) { if (skipNull) stream = stream.filter(Objects::nonNull); Stream<String> stream2 = stream.map(String::valueOf); if (trim) stream2 = stream2.map(String::trim); if (skipNull) stream2 = stream2.filter(StringUtils::isNotBlank); return stream2.collect(Collectors.joining(delimiter)); } public static Stream<String> split(String string, String delimiter) { return streamArray(string.split(delimiter)); } public static String joining(Stream<String> stream, String delimiter) { return stream.collect(Collectors.joining(delimiter)); } /** * !!!!!!!!!!! terminates source stream !!!!!!!!!!! <br> * !!!!!!!!!!! cannot be used on endless streams !!!!!!!!!!! * * stackoverflow.com/questions/24010109/java-8-stream-reverse-order */ @SuppressWarnings("unchecked") public static <T> Stream<T> reverse(Stream<T> input) { Object[] temp = input.toArray(); return (Stream<T>) IntStream.range(0, temp.length).mapToObj(i -> temp[temp.length - i - 1]); } public static boolean notEquals(Object first, Object second) { return !isEquals(first, second); } public static boolean isEquals(Object first, Object second) { if (first == second) return true; if (first == null && second == null) return true; if (first == null || second == null) return false; return first.equals(second); } /** * staat geen null values in keys toe (alhoewel een map dat wel toe laat) */ public static <V, K> Map<K, List<V>> groupBy(Stream<V> stream, Function<V, K> groupBy) { return stream.collect(Collectors.groupingBy(groupBy)); } /** * workaround om null values in key toe te laten * * @see https://stackoverflow.com/questions/22625065/collectors-groupingby-doesnt-accept-null-keys */ public static <V, K> Map<K, List<V>> groupByAcceptsNull(Stream<V> stream, Function<V, K> groupBy) { return stream// .collect(// Collectors.groupingBy(// Optional can contain null while // null itself throws exception v -> Optional.ofNullable(groupBy.apply(v))// , // order could be important, use LinkedHashMap newLinkedMap()// , // collectList()// )// )// .entrySet()// .stream()// .collect(// Collectors.toMap(// keymapper entry -> entry.getKey().orElse(null)// , // valuemapper entry -> entry.getValue()// , // merge function doesn't matter, key is // always unique keepFirst()// , // order could be important, use LinkedHashMap newLinkedMap()// )// ); } public static <T> Comparator<T> dummyComparator() { return (x, y) -> 0; } public static <K, V> Function<Entry<K, V>, V> valueMapper() { return Entry::getValue; } public static <K, V> Function<Entry<K, V>, K> keyMapper() { return Entry::getKey; } public static Stream<String> regex(String text, String regex) { return stream(new RegexIterator(text, regex)); } public static <T> T[] copy(T[] array) { return copy(array, array.length); } public static <T> T[] copy(T[] array, int length) { return Arrays.copyOf(array, length); } @SafeVarargs public static <K, V> Stream<Entry<K, V>> streamMaps(Map<K, V>... maps) { return Stream.of(maps).map(Map::entrySet).flatMap(Collection::stream); } @SafeVarargs public static <K, V> Stream<Entry<K, V>> streamMapsUnique(Map<K, V>... maps) { return stream(streamMaps(maps).collect(Collectors.toMap(Entry::getKey, Entry::getValue, keepLast(), newLinkedMap()))); } public static <K, V> Collector<Entry<K, V>, ?, EnhancedMap<K, V>> collectMapEntries(Function<Entry<K, V>, V> valueMapper) { return Collectors.toMap(Entry::getKey, valueMapper, rejectDuplicateKeys(), newMap()); } public static <K, V> Collector<Entry<K, V>, ?, EnhancedMap<K, V>> collectMapEntriesAlt(Function<Entry<K, V>, K> keyMapper) { return Collectors.toMap(keyMapper, Entry::getValue, rejectDuplicateKeys(), newMap()); } public static <K, V> Collector<Entry<K, V>, ?, EnhancedMap<K, V>> collectMapEntries() { return Collectors.toMap(Entry::getKey, Entry::getValue, rejectDuplicateKeys(), newMap()); } public static <T, K, V> Collector<T, ?, EnhancedMap<K, V>> collectMap(Function<T, K> keyMapper, Function<T, V> valueMapper) { return collectMap(keyMapper, valueMapper, rejectDuplicateKeys()); } public static <T, K, V> Collector<T, ?, EnhancedMap<K, V>> collectMap(Function<T, K> keyMapper, Function<T, V> valueMapper, BinaryOperator<V> duplicateValues) { return Collectors.toMap(keyMapper, valueMapper, duplicateValues, newMap()); } public static <T, K, V> Collector<T, ?, EnhancedMap<K, V>> collectMapAlt(Function<T, V> valueMapper, BinaryOperator<V> duplicateValues) { @SuppressWarnings("unchecked") Function<T, K> keyMapper = (Function<T, K>) id(); return Collectors.toMap(keyMapper, valueMapper, duplicateValues, newMap()); } public static <K, V> Collector<V, ?, EnhancedMap<K, V>> collectMap(Function<V, K> keyMapper, BinaryOperator<V> duplicateValues) { return collectMap(keyMapper, self(), duplicateValues); } public static <K, V> Collector<V, ?, EnhancedMap<K, V>> collectMap(Function<V, K> keyMapper) { return collectMap(keyMapper, rejectDuplicateKeys()); } public static <T, K, V> Collector<T, ?, EnhancedSortedMap<K, V>> collectSortedMap(Function<T, K> keyMapper, Function<T, V> valueMapper) { return collectSortedMap(keyMapper, valueMapper, rejectDuplicateKeys()); } public static <T, K, V> Collector<T, ?, EnhancedSortedMap<K, V>> collectSortedMap(Function<T, K> keyMapper, Function<T, V> valueMapper, BinaryOperator<V> duplicateValues) { return Collectors.toMap(keyMapper, valueMapper, duplicateValues, newSortedMap()); } public static <K, V> Collector<V, ?, EnhancedSortedMap<K, V>> collectSortedMap(Function<V, K> keyMapper, BinaryOperator<V> duplicateValues) { return collectSortedMap(keyMapper, self(), duplicateValues); } public static <K, V> Collector<V, ?, EnhancedSortedMap<K, V>> collectSortedMap(Function<V, K> keyMapper) { return collectSortedMap(keyMapper, rejectDuplicateKeys()); } public static <T extends Comparable<? super T>> Comparator<T> natural() { return Comparator.<T> naturalOrder(); } public static <T extends Comparable<? super T>> BinaryOperator<T> keepMin() { return keepMin(CollectionUtils8.<T> natural()); } public static <T> BinaryOperator<T> keepMin(Comparator<T> comparator) { return BinaryOperator.minBy(comparator); } public static <T extends Comparable<? super T>> BinaryOperator<T> keepMax() { return keepMax(CollectionUtils8.<T> natural()); } public static <T> BinaryOperator<T> keepMax(Comparator<T> comparator) { return BinaryOperator.maxBy(comparator); } public static IntStream streamInt(int max) { return streamInt(0, 1, max); } public static LongStream streamLong(long max) { return streamLong(0, 1, max); } public static DoubleStream streamDouble(double max) { return streamDouble(0.0, 1.0, max); } public static IntStream streamInt(int start, int max) { return streamInt(start, 1, max); } public static LongStream streamLong(long start, long max) { return streamLong(start, 1, max); } public static DoubleStream streamDouble(double start, double max) { return streamDouble(start, 1.0, max); } public static IntStream streamInt(int start, int step, int max) { return IntStream.iterate(start, i -> i + step).limit(max - start); } public static LongStream streamLong(long start, long step, long max) { return LongStream.iterate(start, i -> i + step).limit(max - start); } public static DoubleStream streamDouble(double start, double step, double max) { return DoubleStream.iterate(start, i -> i + step).limit((long) (max - start)); } @SuppressWarnings("unchecked") public static <T> T[] toArray(Collection<T> collection) { return (T[]) collection.toArray(); } @SuppressWarnings("unchecked") public static <T> T[] toArray(Stream<T> stream, Class<T> type) { return stream.toArray(size -> (T[]) Array.newInstance(type, size)); } public static <T> Stream<T> flatMapCollections(Collection<? extends Collection<T>> collectionOfCollections) { return flatMapStreams(collectionOfCollections.stream().map(Collection::stream)); } public static <T> Stream<T> flatMap(Stream<? extends Collection<T>> streamOfCollections) { return flatMapStreams(streamOfCollections.map(Collection::stream)); } public static <T> Stream<T> flatMap(Collection<Stream<T>> collentionOfStreams) { return flatMapStreams(collentionOfStreams.stream()); } public static <T> Stream<T> flatMapStreams(Stream<Stream<T>> streamOfStreams) { return streamOfStreams.flatMap(id()); } public static <T> Stream<T> flatMapArrays(T[][] streamOfStreams) { Stream<Stream<T>> b = streamArray(streamOfStreams).map(a -> streamArray(a)); return flatMapStreams(b); } public static <T> Opt<T> eager(T value) { return Opt.eager(value); } public static <T> Opt<T> reusable(T value) { return Opt.reusable(value); } /** * c1 - c2, does not change input collections, returns new collection (list) */ public static <T> List<T> subtract(Collection<T> c1, Collection<T> c2) { if (c1 == null) { return Collections.emptyList(); } List<T> tmp = new ArrayList<>(c1); if (c2 != null) { tmp.removeAll(c2); } return tmp; } /** * intersection of c1 and c2, does not change input collections, returns new collection (list) */ public static <T> List<T> intersection(Collection<T> c1, Collection<T> c2) { if (c1 == null || c2 == null) { return Collections.emptyList(); } return c1.stream().filter(c2::contains).collect(collectList()); } /** * intersection of c1 and c2, does not change input collections, returns new collection (list) */ public static <T> List<T> union(Collection<T> c1, Collection<T> c2) { if (c1 == null && c2 == null) { return Collections.emptyList(); } if (c1 == null) { return new ArrayList<>(c2); } if (c2 == null) { return new ArrayList<>(c1); } List<T> tmp = new ArrayList<>(c1.size() + c2.size()); tmp.addAll(c1); tmp.addAll(c2); return tmp; } /** * @see https://stackoverflow.com/questions/42214519/java-intersection-of-multiple-collections-using-stream-lambdas */ public static <T, S extends Collection<T>> Collector<S, ?, Set<T>> intersecting() { class IntersectAcc { Set<T> result; void accept(S s) { if (result == null) result = new HashSet<>(s); else result.retainAll(s); } IntersectAcc combine(IntersectAcc other) { if (result == null) return other; if (other.result != null) result.retainAll(other.result); return this; } } return Collector.of(IntersectAcc::new, IntersectAcc::accept, IntersectAcc::combine, acc -> acc.result == null ? Collections.emptySet() : acc.result, Collector.Characteristics.UNORDERED); } /** * aanTeMakenAct roept teBewaren op met als nieuw object aangeboden door param constructor, constructor en teBewaren zijn niet nullable * * @see #sync(Map, Map, BiConsumer, BiConsumer, BiConsumer) */ public static <K, N, B> void sync(// Map<K, N> nieuwe, // Map<K, B> bestaande, // BiConsumer<K, B> teVerwijderenAct, // Supplier<B> constructor, // BiConsumer<N, B> teBewaren// ) { if (constructor == null || teBewaren == null) throw new NullPointerException(); sync(nieuwe, bestaande, teVerwijderenAct, (k, i) -> teBewaren.accept(i, constructor.get()), teBewaren); } /** * synchroniseer een nieuwe collectie met een bestaande collecte * * @param nieuwe nieuwe collectie vooraf gemapt op key, zie {@link #getMap(Collection, Function)} * @param bestaande bestaande collectie vooraf gemapt op key, zie {@link #getMap(Collection, Function)} * @param teVerwijderenAct nullable, actie op te roepen indien verwijderen, krijgt key en bestaand object binnen * @param aanTeMakenAct nullable, actie op te roepen indien nieuw object aan te maken, krijgt key en nieuw object binnen * @param teBewaren nullable, actie op te roepen indien overeenkomst, krijgt key en nieuw en bestaand object binnen * * @param <K> key waarop vergeleken moet worden * @param <N> nieuwe object * @param <B> bestaand object */ public static <K, N, B> void sync(// Map<K, N> nieuwe, // Map<K, B> bestaande, // BiConsumer<K, B> teVerwijderenAct, // BiConsumer<K, N> aanTeMakenAct, // BiConsumer<N, B> teBewaren// ) { Map<K, B> teVerwijderen = subtract(bestaande.keySet(), nieuwe.keySet()).stream().collect(Collectors.toMap(id(), bestaande::get)); Map<K, N> aanTeMaken = subtract(nieuwe.keySet(), bestaande.keySet()).stream().collect(Collectors.toMap(id(), nieuwe::get)); Map<N, B> overeenkomst = intersection(nieuwe.keySet(), bestaande.keySet()).stream().collect(Collectors.toMap(nieuwe::get, bestaande::get)); if (teBewaren != null) overeenkomst.forEach(teBewaren); if (aanTeMakenAct != null) aanTeMaken.forEach(aanTeMakenAct); if (teVerwijderenAct != null) teVerwijderen.forEach(teVerwijderenAct); } public static <K, V> Map<K, V> getMap(Stream<V> values, Function<V, K> keyMapper) { return values.collect(Collectors.toMap(keyMapper, self())); } public static <K, V> Map<K, V> getMap(Collection<V> values, Function<V, K> keyMapper) { return getMap(values.stream(), keyMapper); } public static <K, V> Map<K, V> getMap(Stream<V> values, Supplier<K> keyMapper) { return values.collect(Collectors.toMap(supplierToFunction(keyMapper), self())); } public static <K, V> Map<K, V> getMap(Collection<V> values, Supplier<K> keyMapper) { return getMap(values.stream(), keyMapper); } public static <K, V> Map<K, V> getKeyMap(Collection<K> values, Function<K, V> valueMapper) { return values.stream().collect(Collectors.toMap(self(), valueMapper)); } public static <K, V> Map<K, V> getKeyMap(Collection<K> values, Supplier<V> valueMapper) { return values.stream().collect(Collectors.toMap(self(), supplierToFunction(valueMapper))); } public static <S, X> Function<X, S> supplierToFunction(Supplier<S> supplier) { return any -> supplier.get(); } public static <T> Supplier<T> supplyAny(T object) { return () -> object; } public static <T> BiConsumer<List<T>, T> elementsListAccumulator() { return (List<T> a, T t) -> a.add(t); } public static <T> BiConsumer<List<T>, T> uniqueElementsListAccumulator() { return (List<T> a, T t) -> { if (!a.contains(t)) a.add(t); }; } public static <T> BinaryOperator<List<T>> elementsListCombiner(BiConsumer<List<T>, T> elementsListAccumulator) { return (List<T> a1, List<T> a2) -> { a2.stream().forEach(a2e -> elementsListAccumulator.accept(a1, a2e)); return a1; }; } public static <T> Consumer<T> when(Predicate<T> restriction, Consumer<T> whenTrue, Consumer<T> whenFalse) { return t -> (restriction.test(t) ? whenTrue : whenFalse).accept(t); } public static <T> Consumer<T> when(boolean restriction, Consumer<T> whenTrue, Consumer<T> whenFalse) { return when(always(restriction), whenTrue, whenFalse); } public static <T> void when(Predicate<T> restriction, Consumer<T> whenTrue, Consumer<T> whenFalse, T subject) { when(restriction, whenTrue, whenFalse).accept(subject); } public static <T> void when(boolean restriction, Consumer<T> whenTrue, Consumer<T> whenFalse, T subject) { when(restriction, whenTrue, whenFalse).accept(subject); } public static <T> Collection<Collection<T>> split(Collection<T> all, int maxSize) { if (maxSize < 1) throw new IllegalArgumentException("maxSize<1"); if (all.size() <= maxSize) return Arrays.asList(all); int totalSize = all.size(); AtomicInteger ai = new AtomicInteger(0); int groups = (totalSize / maxSize) + (totalSize % maxSize > 0 ? 1 : 0); Map<Integer, List<T>> g = all.stream().parallel().collect(Collectors.groupingBy(s -> ai.addAndGet(1) % groups)); return stream(g).map(valueMapper()).collect(collectList()); } public static <T> Stream<List<T>> split(List<T> elements, int count) { return elements.stream().collect(Collectors.groupingBy(c -> elements.indexOf(c) / count)).values().stream(); } public static <T> Function<List<T>, T> first() { return list -> list.isEmpty() ? null : list.get(0); } public static <T> T first(List<T> list) { return list.get(0); } public static <T> T first(LinkedBlockingDeque<T> dq) { return dq.iterator().next(); } public static <T> T first(LinkedBlockingQueue<T> q) { return q.iterator().next(); } public static <T> T first(LinkedHashSet<T> set) { return set.iterator().next(); } public static <K, V> Entry<K, V> first(LinkedHashMap<K, V> map) { return map.entrySet().iterator().next(); } @SafeVarargs public static <T> List<T> sortBy(Collection<T> collection, Function<T, ? extends Comparable<?>> map, Function<T, ? extends Comparable<?>>... mapAdditional) { return collection.stream().sorted(comparator(map, mapAdditional)).collect(collectList()); } @SuppressWarnings({ "rawtypes", "unchecked" }) public static <T extends Comparable<? super T>> List<T> sortInPlace(List<T> list) { Collections.sort((List<? extends Comparable>) list); return list; } @SafeVarargs public static <T> List<T> sortInPlace(List<T> list, Function<T, ? extends Comparable<?>> map, Function<T, ? extends Comparable<?>>... mapAdditional) { list.sort(comparator(map, mapAdditional)); return list; } @SafeVarargs public static <T> Comparator<T> comparator(Function<T, ? extends Comparable<?>> compare, Function<T, ? extends Comparable<?>>... compareAdditional) { return (t1, t2) -> { CompareToBuilder cb = new CompareToBuilder(); cb.append(compare.apply(t1), compare.apply(t2)); streamArray(compareAdditional).forEach(compareThisEl -> cb.append(compareThisEl.apply(t1), compareThisEl.apply(t2))); return cb.toComparison(); }; } public static <T, U> Stream<U> filterClass(Stream<T> stream, Class<U> type) { return stream.filter(t -> type.isAssignableFrom(t.getClass())).map(t -> type.cast(t)); } public static Stream<Map.Entry<String, String>> stream(Properties properties) { return stream(false, properties).map(entry -> new Pair<>(String.valueOf(entry.getKey()), String.valueOf(entry.getValue()))); } public static <K, V> Function<Entry<K, V>, K> mapKey() { return Entry::getKey; } public static <K, V> Function<Entry<K, V>, V> mapValue() { return Entry::getValue; } public static <K, V, T> Map<K, T> map(Map<K, V> map, Function<V, T> valueMapper) { return stream(map).collect(collectMap(mapKey(), e -> valueMapper.apply(e.getValue()))); } public static <K, V, T> Map<T, V> mapKey(Map<K, V> map, Function<K, T> keyMapper) { return stream(map).collect(collectMap(e -> keyMapper.apply(e.getKey()), mapValue())); } public static <T> Comparator<T> comparatorCaseInsensitive(Function<T, String> compare) { Comparators.CaseInsensitiveComparator comparator = new Comparators.CaseInsensitiveComparator(); return (t1, t2) -> { return comparator.compare(compare.apply(t1), compare.apply(t2)); }; } @SuppressWarnings({ "unchecked", "rawtypes" }) public static EnhancedMap<String, List<String>> groupByValue(Properties properties) { return groupByValue((Map<String, String>) (Map) properties); } public static <K, V> EnhancedMap<V, List<K>> groupByValue(Map<K, V> map) { return stream(map.entrySet()) .collect(Collectors.groupingBy(e -> e.getValue(), newMap(), Collectors.mapping(e -> e.getKey(), Collectors.toList()))); } @SuppressWarnings("unchecked") public static <X, Y> Function<X, Y> functions(Function<X, Y>... functions) { Value<Function<X, Y>> returningFunction = new Value<>(functions[0]); Arrays.stream(functions).skip(1).forEach(f -> returningFunction.set(returningFunction.get().andThen(Function.class.cast(f)))); return returningFunction.get(); } public static <X> X nn(X nullable, X defaultValue) { return nullable == null ? defaultValue : nullable; } public static <S, T> Function<S, T> getDefaulted(Function<S, T> getter, T defaultValue) { return ((Function<S, T>) s -> getter.apply(s)).andThen(e -> nn(e, defaultValue)); } public static <X, Y> Y getMapValue(Map<? extends Predicate<X>, Y> map, X in) { return map.entrySet().stream().filter(entry -> entry.getKey().test(in)).map(Map.Entry::getValue).findFirst().orElse(null); } public static <T> List<T> emptyList() { return Collections.emptyList(); } public static <T> Stream<T> emptyStream() { return Stream.empty(); } public static <T, U> Map<T, U> emptyMap() { return Collections.emptyMap(); } public static <T> Set<T> emptySet() { return Collections.emptySet(); } public static String toString(IntStream s) { return s.mapToObj(String::valueOf).collect(Collectors.joining()); } @SafeVarargs public static <T> BiPredicate<T, T> equals(Function<T, ?>... methods) { return (a, b) -> { EqualsBuilder eb = new EqualsBuilder(); Arrays.asList(methods).forEach(g -> eb.append(g.apply(a), g.apply(b))); return eb.isEquals(); }; } @SafeVarargs public static <T> BiFunction<T, T, Integer> bifunction(Function<T, ?>... methods) { return (a, b) -> { if (methods == null || methods.length == 0) { return 0; } CompareToBuilder ctb = new CompareToBuilder(); Arrays.asList(methods).forEach(g -> ctb.append(g.apply(a), g.apply(b))); return ctb.toComparison(); }; } @SafeVarargs public static <T> Comparator<T> comparatorFor(Function<T, ?>... methods) { return comparatorFor(bifunction(methods)); } public static <T> Comparator<T> comparatorFor(BiFunction<T, T, Integer> method) { return method::apply; } public static <T> Collection<T> toUnmodifiableCollection(Collection<T> collection) { return Collections.unmodifiableCollection(toList(true, collection)); } public static <T> List<T> toUnmodifiableList(Collection<T> collection) { return Collections.unmodifiableList(toList(true, collection)); } public static <K, V> Map<K, V> toUnmodifiableMap(Map<K, V> map) { return Collections.unmodifiableMap(toMap(true, map)); } public static <T> Set<T> toUnmodifiableSet(Collection<T> collection) { return Collections.unmodifiableSet(toSet(true, collection)); } public static <K, V> SortedMap<K, V> toUnmodifiableSortedMap(SortedMap<K, V> map) { return Collections.unmodifiableSortedMap(toSortedMap(true, map)); } public static <T> SortedSet<T> toUnmodifiableSortedSet(Collection<T> collection) { return Collections.unmodifiableSortedSet(toSortedSet(true, collection)); } public static <T> Collection<T> toSynchronizedCollection(Collection<T> collection) { return Collections.synchronizedCollection(toList(true, collection)); } public static <T> List<T> toSynchronizedList(Collection<T> collection) { return Collections.synchronizedList(toList(true, collection)); } public static <K, V> Map<K, V> toSynchronizedMap(Map<K, V> map) { return Collections.synchronizedMap(toMap(true, map)); } public static <T> Set<T> toSynchronizedSet(Collection<T> collection) { return Collections.synchronizedSet(toSet(true, collection)); } public static <K, V> SortedMap<K, V> toSynchronizedSortedMap(SortedMap<K, V> map) { return Collections.synchronizedSortedMap(toSortedMap(true, map)); } public static <T> SortedSet<T> toSynchronizedSortedSet(Collection<T> collection) { return Collections.synchronizedSortedSet(toSortedSet(true, collection)); } public static <T> Stream<KeyValue<Integer, T>> index(Stream<T> stream) { IntegerValue index = new IntegerValue(-1); return stream.map(t -> new KeyValue<>(index.add().get(), t)); } public static <T> Map<T, Long> countBy(Stream<T> stream) { return stream.collect(Collectors.groupingBy(Function.identity(), Collectors.counting())); } /** * @see http://stackoverflow.com/questions/26403319/skip-last-x-elements-in-streamt */ public static <T> Stream<T> skip(Stream<T> s, int first, int last) { if (last <= 0 && first <= 0) { return s; } if (last <= 0) { return s.skip(first); } if (first > 0) { s = s.skip(first); } ArrayDeque<T> pending = new ArrayDeque<>(last + 1); Spliterator<T> src = s.spliterator(); return StreamSupport.stream(new Spliterator<T>() { @Override public boolean tryAdvance(Consumer<? super T> action) { while (pending.size() <= last && src.tryAdvance(pending::add)) ; if (pending.size() > last) { action.accept(pending.remove()); return true; } return false; } @Override public Spliterator<T> trySplit() { return null; } @Override public long estimateSize() { return src.estimateSize() - last; } @Override public int characteristics() { return src.characteristics(); } }, false); } public static <T> Stream<T> skip(Integer first, Integer last, Stream<T> s) { return skip(s, first == null ? 0 : first, last == null ? 0 : last); } public static <T> T merge(List<T> list, int index, T object, BinaryOperator<T> operate) { return list.set(index, operate.apply(list.get(index), object)); } public static String append(List<String> list, int index, String string, String seperator) { return merge(list, index, string, (a, b) -> StringUtils.isBlank(a) ? b : a + seperator + b); } public static String firstNotBlank(String... strings) { return streamArray(strings).filter(isNotBlank()).findFirst().orElse(null); } @SafeVarargs public static <T> T firstNotBlankAndNotNull(T... o) { return streamArray(o).filter(isNotBlankAndNotNull()).findFirst().orElse(null); } @SafeVarargs public static <T> T firstNotNull(T... o) { return streamArray(o).filter(isNotNull()).findFirst().orElse(null); } public static <T> List<T> copy(List<T> list, int maxSize) { if (list.size() <= maxSize) return list; return list.stream().limit(maxSize).collect(collectList()); } public static <T> List<T> listLI(List<T> list, T item) { list.add(item); return list; } public static <T> List<T> listIL(T item, List<T> list) { list.add(0, item); return list; } public static <T> List<T> listLL(List<T> list1, List<T> list2) { list1.addAll(list2); return list1; } public static <T> List<T> listCLI(List<T> list, T item) { List<T> tmp = new ArrayList<>(); tmp.addAll(list); tmp.add(item); return tmp; } public static <T> List<T> listCIL(T item, List<T> list) { List<T> tmp = new ArrayList<>(); tmp.add(item); tmp.addAll(list); return tmp; } public static <T> List<T> listCLL(List<T> list1, List<T> list2) { List<T> tmp = new ArrayList<>(); tmp.addAll(list1); tmp.addAll(list2); return tmp; } public static <R, K, V> List<R> flatten(Collection<R> records, Function<R, K> toKey, Function<R, V> toValue, BinaryOperator<V> mergeValue, BiFunction<K, V, R> mergeToRecord) { Map<K, List<R>> map = records.stream().collect(Collectors.groupingBy(toKey)); return map.entrySet().stream().map(entry -> { return new KeyValue<>(entry.getKey(), entry.getValue().stream().map(toValue).reduce(mergeValue).get()); }).map(entry -> { return mergeToRecord.apply(entry.getKey(), entry.getValue()); }).collect(Collectors.toList()); } public static <T> Collector<T, ?, EnhancedMap<T, Integer>> groupingByCount() { return Collectors.groupingBy(id(), newMap(), Collectors.reducing(0, e -> 1, Integer::sum)); } public static <T> Collector<T, ?, EnhancedMap<T, Long>> groupingByCountMany() { return Collectors.groupingBy(id(), newMap(), Collectors.counting()); } public static Comparator<Float> ascFloat() { return (a, b) -> new CompareToBuilder().append(a, b).toComparison(); } public static Comparator<Float> descFloat() { return (a, b) -> -new CompareToBuilder().append(a, b).toComparison(); } public static Comparator<Double> ascDouble() { return (a, b) -> new CompareToBuilder().append(a, b).toComparison(); } public static Comparator<Double> descDouble() { return (a, b) -> -new CompareToBuilder().append(a, b).toComparison(); } public static Comparator<Byte> ascByte() { return (a, b) -> a - b; } public static Comparator<Byte> descByte() { return (a, b) -> b - a; } public static Comparator<Short> ascShort() { return (a, b) -> a - b; } public static Comparator<Short> descShort() { return (a, b) -> b - a; } public static Comparator<Integer> ascInt() { return (a, b) -> a - b; } public static Comparator<Integer> descInt() { return (a, b) -> b - a; } public static Comparator<Long> ascLong() { return (a, b) -> new CompareToBuilder().append(a, b).toComparison(); } public static Comparator<Long> descLong() { return (a, b) -> -new CompareToBuilder().append(a, b).toComparison(); } public static <K, V> LinkedHashMap<K, V> sortByValue(Map<K, V> map, Comparator<V> comparator) { return map.entrySet() .stream() .sorted(Map.Entry.comparingByValue(comparator)) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new)); } public static <T> List<T> repeat(int times, T object) { return IntStream.range(0, times).mapToObj(i -> object).collect(Collectors.toList()); } public static <T> Stream<T> stream(Optional<T> optional) { return optional.isPresent() ? Stream.of(optional.get()) : Stream.empty(); } public static <T extends Serializable> List<T> serializable(List<T> list) { return list instanceof Serializable ? list : new ArrayList<>(list); } public static <T extends Serializable> Set<T> serializable(Set<T> set) { return set instanceof Serializable ? set : new HashSet<>(set); } public static <T extends Serializable> SortedSet<T> serializable(SortedSet<T> set) { return set instanceof Serializable ? set : new TreeSet<>(set); } public static <K extends Serializable, V extends Serializable> Map<K, V> serializable(Map<K, V> set) { return set instanceof Serializable ? set : new HashMap<>(set); } public static <K extends Serializable, V extends Serializable> SortedMap<K, V> serializable(SortedMap<K, V> set) { return set instanceof Serializable ? set : new TreeMap<>(set); } public static IntStream stream(byte[] bytes) { return IntStream.range(0, bytes.length).map(idx -> bytes[idx]); } public static IntStream stream(Byte[] bytes) { return IntStream.range(0, bytes.length).map(idx -> bytes[idx]); } public static <A> Predicate<A> notNullPredicate() { return a -> a instanceof String ? StringUtils.isNotBlank((String) a) : a != null; } public static <A, B> BiPredicate<A, B> notNullBiPredicate() { return (a, b) -> notNullPredicate().test(a) || notNullPredicate().test(b); } public static <A, B, C> TriplePredicate<A, B, C> notNullTriplePredicate() { return (a, b, c) -> notNullPredicate().test(a) || notNullPredicate().test(b) || notNullPredicate().test(c); } public static <A, B, C, D> QuadruplePredicate<A, B, C, D> notNullQuadruplePredicate() { return (a, b, c, d) -> notNullPredicate().test(a) || notNullPredicate().test(b) || notNullPredicate().test(c) || notNullPredicate().test(d); } public static <A, B, C, D, E> QuintuplePredicate<A, B, C, D, E> notNullQuintuplePredicate() { return (a, b, c, d, e) -> notNullPredicate().test(a) || notNullPredicate().test(b) || notNullPredicate().test(c) || notNullPredicate().test(d) || notNullPredicate().test(e); } public static <T> List<T> replaceOrAdd(List<T> list, T object) { if (list == null || object == null) return list; int i = list.indexOf(object); if (i != -1) { list.remove(object); list.add(i, object); } else { list.add(object); } return list; } public static <T> Consumer<T> throwing(Supplier<RuntimeException> exception) { return t -> { throw exception.get(); }; } public static <T> Consumer<T> throwing(RuntimeException exception) { return t -> { throw exception; }; } public static <T> Consumer<T> throwing(Function<T, RuntimeException> exception) { return t -> { throw exception.apply(t); }; } public static BooleanSupplier enhanceBooleanSupplier(EBooleanSupplier supplier) { return EBooleanSupplier.enhance(supplier); } public static <T> Consumer<T> enhanceConsumer(EConsumer<T> consumer) { return EConsumer.enhance(consumer); } public static <T, U> BiConsumer<T, U> enhanceBiConsumer(EBiConsumer<T, U> consumer) { return EBiConsumer.enhance(consumer); } public static DoubleSupplier enhanceDoubleSupplier(EDoubleSupplier supplier) { return EDoubleSupplier.enhance(supplier); } public static <T, R> Function<T, R> enhanceFunction(EFunction<T, R> function) { return EFunction.enhance(function); } public static IntSupplier enhanceIntegerSupplier(EIntSupplier supplier) { return EIntSupplier.enhance(supplier); } public static LongSupplier enhanceLongSupplier(ELongSupplier supplier) { return ELongSupplier.enhance(supplier); } public static <T> Predicate<T> enhancePredicate(EPredicate<T> predicate) { return EPredicate.enhance(predicate); } public static Runnable enhanceRunnable(ERunnable runnable) { return ERunnable.enhance(runnable); } public static <T> Supplier<T> enhanceSupplier(ESupplier<T> predicate) { return ESupplier.enhance(predicate); } public static <K, V> List<KeyValue<K, V>> entryList(Map<K, V> map) { return map.entrySet().stream().map(KeyValue::new).collect(collectList()); } public static <T> T[] merge(T[] a, T[] b) { int aLen = a.length; int bLen = b.length; @SuppressWarnings("unchecked") T[] c = (T[]) Array.newInstance(a.getClass().getComponentType(), aLen + bLen); System.arraycopy(a, 0, c, 0, aLen); System.arraycopy(b, 0, c, aLen, bLen); return c; } public static <T> T[] append(T[] a, @SuppressWarnings("unchecked") T... b) { return merge(a, b); } public static <T> T[] prepend(T[] a, @SuppressWarnings("unchecked") T... b) { return merge(b, a); } public static <T> UnaryOperator<T> unaryOperator(Consumer<T> consumer) { UnaryOperator<T> a = b -> { consumer.accept(b); return b; }; return a; } public static <T> Stream<List<T>> ofSubLists(List<T> source, int length) { if (length <= 0) throw new IllegalArgumentException("length = " + length); int size = source.size(); if (size <= 0) return Stream.empty(); int fullChunks = (size - 1) / length; return IntStream.range(0, fullChunks + 1).mapToObj(n -> source.subList(n * length, n == fullChunks ? size : (n + 1) * length)); } }
jhaws/lang/src/main/java/org/jhaws/common/lang/CollectionUtils8.java
package org.jhaws.common.lang; import java.io.IOException; import java.io.Serializable; import java.io.UncheckedIOException; import java.lang.reflect.Array; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Deque; import java.util.EnumSet; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.NoSuchElementException; import java.util.Objects; import java.util.Optional; import java.util.Properties; import java.util.Queue; import java.util.Set; import java.util.SortedMap; import java.util.SortedSet; import java.util.Spliterator; import java.util.Spliterators; import java.util.Stack; import java.util.TreeMap; import java.util.TreeSet; import java.util.concurrent.BlockingDeque; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentSkipListMap; import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.LinkedTransferQueue; import java.util.concurrent.TransferQueue; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import java.util.function.BiConsumer; import java.util.function.BiFunction; import java.util.function.BiPredicate; import java.util.function.BinaryOperator; import java.util.function.BooleanSupplier; import java.util.function.Consumer; import java.util.function.DoubleSupplier; import java.util.function.Function; import java.util.function.IntFunction; import java.util.function.IntSupplier; import java.util.function.LongSupplier; import java.util.function.Predicate; import java.util.function.Supplier; import java.util.function.UnaryOperator; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collector; import java.util.stream.Collectors; import java.util.stream.DoubleStream; import java.util.stream.IntStream; import java.util.stream.LongStream; import java.util.stream.Stream; import java.util.stream.StreamSupport; import org.apache.commons.lang3.builder.CompareToBuilder; import org.apache.commons.lang3.builder.EqualsBuilder; import org.jhaws.common.lang.functions.EBiConsumer; import org.jhaws.common.lang.functions.EBooleanSupplier; import org.jhaws.common.lang.functions.EConsumer; import org.jhaws.common.lang.functions.EDoubleSupplier; import org.jhaws.common.lang.functions.EFunction; import org.jhaws.common.lang.functions.EIntSupplier; import org.jhaws.common.lang.functions.ELongSupplier; import org.jhaws.common.lang.functions.EPredicate; import org.jhaws.common.lang.functions.ERunnable; import org.jhaws.common.lang.functions.ESupplier; // http://infotechgems.blogspot.be/2011/11/java-collections-performance-time.html // TODO https://www.techempower.com/blog/2016/10/19/efficient-multiple-stream-concatenation-in-java/ /** * @see java.util.stream.Stream * @see java.util.stream.StreamSupport * @see java.util.stream.Collectors * @see java.util.stream.Collector * @since 1.8 * @see https://technology.amis.nl/2013/10/05/java-8-collection-enhancements- leveraging-lambda-expressions-or-how-java-emulates-sql/ */ public interface CollectionUtils8 { public static class Comparators { public static class CaseInsensitiveComparator implements Comparator<String> { @Override public int compare(String o1, String o2) { return (o1 == null ? "" : o1).compareToIgnoreCase((o2 == null ? "" : o2)); } } public static class MapEntryKVComparator<K, V> implements Comparator<Map.Entry<K, V>> { @Override public int compare(Entry<K, V> o1, Entry<K, V> o2) { return new CompareToBuilder().append(o1.getKey(), o2.getKey()).append(o1.getValue(), o2.getValue()).toComparison(); } } public static class MapEntryVKComparator<K, V> implements Comparator<Map.Entry<K, V>> { @Override public int compare(Entry<K, V> o1, Entry<K, V> o2) { return new CompareToBuilder().append(o1.getValue(), o2.getValue()).append(o1.getKey(), o2.getKey()).toComparison(); } } } public static class RegexIterator implements EnhancedIterator<String> { protected Pattern pattern; protected String regex; protected Matcher matcher; protected Boolean hasNext = null; public RegexIterator(String text, String regex) { this.pattern = Pattern.compile(regex); this.regex = regex; this.matcher = pattern.matcher(text); } public RegexIterator(String text, Pattern regex) { this.pattern = regex; this.regex = regex.toString(); this.matcher = pattern.matcher(text); } public RegexIterator(Pattern regex, String text) { this.pattern = regex; this.regex = regex.toString(); this.matcher = pattern.matcher(text); } @Override public boolean hasNext() { if (hasNext == null) { hasNext = matcher.find(); } return hasNext; } @Override public String next() { if (hasNext == null) { hasNext(); } if (hasNext) { hasNext = null; return matcher.group(); } return null; } } public static class PathIterator implements EnhancedIterator<Path> { protected Path path; public PathIterator(Path path) { this.path = path; } @Override public boolean hasNext() { Path parent = this.path.getParent(); return parent != null; } @Override public Path next() { this.path = this.path.getParent(); return this.path; } } public static class ProjectionIterator<T> implements EnhancedIterator<T> { protected T current; protected T next; protected Function<T, T> projection; public ProjectionIterator(T object, boolean include, Function<T, T> projection) { this.current = object; this.projection = projection; if (include) next = current; } @Override public boolean hasNext() { if (next == null) { next = projection.apply(current); } return next != null; } @Override public T next() { hasNext(); if (next == null) { throw new NoSuchElementException(); } current = next; next = null; return current; } } public static interface Opt<T> extends Supplier<T> { /** default vorig type */ <X> Opt<X> opt(Function<T, X> getter); /** default vorig type */ default <X> Opt<X> nest(Function<T, X> getter) { return opt(getter); } /** ga verder eager */ <X> OptEager<X> eager(Function<T, X> getter); /** ga verder reusable = lazy */ <X> OptReusable<T, X> reusable(Function<T, X> getter); /** ga verder reusable = lazy */ default <X> OptReusable<T, X> lazy(Function<T, X> getter) { return reusable(getter); } default <X> OptEager<X> map(Function<T, X> map) { T v = get(); return Opt.eager(/* v == null ? null : */ map.apply(v)); } default <X> OptEager<X> mapOrNull(Function<T, X> map) { return mapOr(map, (X) null); } default <X> OptEager<X> mapOr(Function<T, X> map, X value) { return mapOr(map, (Supplier<X>) () -> value); } default <X> OptEager<X> mapOr(Function<T, X> map, Supplier<X> value) { T v = get(); return Opt.eager(v == null ? value.get() : map.apply(v)); } /** default eager */ public static <T> Opt<T> optional(T value) { return eager(value); } /** start eager */ public static <T> OptEager<T> eager(T value) { return new OptEager<>(value); } /** start reusable = lazy */ public static <T> OptReusable<?, T> reusable(T value) { return new OptReusable<>(value); } /** start reusable = lazy */ public static <T> OptReusable<?, T> lazy(T value) { return reusable(value); } <X> X first(@SuppressWarnings("unchecked") Function<T, X>... getters); default boolean isNull() { return CollectionUtils8.isNull().test(get()); } default boolean isBlankOrNull() { return CollectionUtils8.isBlankOrNull().test(get()); } default boolean isNotNull() { return CollectionUtils8.isNotNull().test(get()); } default boolean isNotBlankAndNotNull() { return CollectionUtils8.isNotBlankAndNotNull().test(get()); } default void consume(Consumer<T> consumer) { T value = get(); if (value != null) { consumer.accept(value); } } /** geeft waarde terug */ @Override T get(); /** voert {@link #opt(Function)} uit en dan {@link #get()} */ default <X> X get(Function<T, X> get) { return opt(get).get(); } /** * voert {@link #get()} uit en wanneer null, voert {@link Supplier} uit en geeft die waarde */ default T or(Supplier<T> supplier) { return Optional.ofNullable(get()).orElseGet(supplier); } /** voert {@link #get()} uit en wanneer null, geeft meegegeven waarde */ default T or(T value) { return Optional.ofNullable(get()).orElse(value); } default T orNull() { return or((T) null); } default T or(Opt<T> supplier) { return or(supplier.get()); } /** wrap in Value */ default Value<T> getValue() { return new Value<>(get()); } /** wrap in Value */ default <X> Value<X> getValue(Function<T, X> get) { return new Value<>(get(get)); } /** wrap in Value */ default Value<T> orValue(Supplier<T> supplier) { return new Value<>(or(supplier)); } /** wrap in Value */ default Value<T> orValue(T value) { return new Value<>(or(value)); } /** wrap in Value */ default Value<T> orNullValue() { return new Value<>(orNull()); } /** wrap in Value */ default Value<T> orValue(Opt<T> supplier) { return new Value<>(or(supplier)); } } static class OptEager<T> implements Opt<T> { protected final T value; protected OptEager(T value) { this.value = value; } @Override public T get() { return value; } @Override public <P> OptEager<P> opt(Function<T, P> get) { return eager(get); } @Override public <P> OptEager<P> eager(Function<T, P> get) { return new OptEager<>(value == null ? null : get.apply(value)); } @Override public <P> OptReusable<T, P> reusable(Function<T, P> get) { return new OptReusable<>(get()).opt(get); } @Override public <X> X first(@SuppressWarnings("unchecked") Function<T, X>... getters) { return streamArray(getters).map(g -> get(g)).filter(CollectionUtils8.isNotBlankAndNotNull()).findFirst().orElse(null); } } static class OptReusable<P, T> implements Opt<T> { protected final OptReusable<P, T> parent; protected final Function<P, T> getter; protected final T value; protected OptReusable(T value) { this.value = value; this.parent = null; this.getter = null; } protected OptReusable(OptReusable<P, T> parent, Function<P, T> getter) { this.value = null; this.parent = parent; this.getter = getter; } @Override @SuppressWarnings({ "unchecked", "rawtypes" }) public T get() { if (value != null) return value; Stack<OptReusable> stack = new Stack<>(); stack.add(this); OptReusable current = this.parent; while (current != null) { stack.add(current); current = current.parent; } Object currentValue = stack.pop().value; while (!stack.isEmpty() && currentValue != null) { current = stack.pop(); currentValue = current.getter.apply(currentValue); } return (T) currentValue; } @Override public <X> OptReusable<T, X> opt(Function<T, X> get) { return reusable(get); } @Override public <X> OptEager<X> eager(Function<T, X> get) { return new OptEager<>(get()).opt(get); } @Override @SuppressWarnings("unchecked") public <X> OptReusable<T, X> reusable(Function<T, X> get) { return new OptReusable<>((OptReusable<T, X>) this, get); } @Override public <X> X first(@SuppressWarnings("unchecked") Function<T, X>... getters) { return streamArray(getters).map(g -> get(g)).filter(CollectionUtils8.isNotBlankAndNotNull()).findFirst().orElse(null); } } public static class CustomCollector<T, A, R> implements Collector<T, A, R> { protected Supplier<A> supplier; protected BiConsumer<A, T> accumulator; protected BinaryOperator<A> combiner; protected Function<A, R> finisher; protected Set<Characteristics> characteristics; public CustomCollector(Supplier<A> supplier, BiConsumer<A, T> accumulator, BinaryOperator<A> combiner, Function<A, R> finisher, Set<Characteristics> characteristics) { this.supplier = supplier; this.accumulator = accumulator; this.combiner = combiner; this.finisher = finisher; this.characteristics = characteristics; } @SuppressWarnings("unchecked") public CustomCollector(Supplier<A> supplier, BiConsumer<A, T> accumulator, BinaryOperator<A> combiner, Set<Characteristics> characteristics) { this(supplier, accumulator, combiner, x -> (R) x, characteristics); } @SuppressWarnings("unchecked") public CustomCollector(Supplier<A> supplier, BiConsumer<A, T> accumulator, BinaryOperator<A> combiner) { this(supplier, accumulator, combiner, x -> (R) x, Collections.unmodifiableSet(EnumSet.of(Collector.Characteristics.IDENTITY_FINISH))); } public CustomCollector() { super(); } @Override public Supplier<A> supplier() { return supplier; } @Override public BiConsumer<A, T> accumulator() { return accumulator; } @Override public BinaryOperator<A> combiner() { return combiner; } @Override public Function<A, R> finisher() { return finisher; } @Override public Set<Characteristics> characteristics() { return characteristics; } public Supplier<A> getSupplier() { return this.supplier; } public void setSupplier(Supplier<A> supplier) { this.supplier = supplier; } public BiConsumer<A, T> getAccumulator() { return this.accumulator; } public void setAccumulator(BiConsumer<A, T> accumulator) { this.accumulator = accumulator; } public BinaryOperator<A> getCombiner() { return this.combiner; } public void setCombiner(BinaryOperator<A> combiner) { this.combiner = combiner; } public Function<A, R> getFinisher() { return this.finisher; } public void setFinisher(Function<A, R> finisher) { this.finisher = finisher; } public Set<Characteristics> getCharacteristics() { return this.characteristics; } public void setCharacteristics(Set<Characteristics> characteristics) { this.characteristics = characteristics; } } public static class ListCollector<T> extends CustomCollector<T, List<T>, List<T>> { public ListCollector() { setSupplier(newList()); BiConsumer<List<T>, T> accumulator0 = elementsListAccumulator(); setAccumulator(accumulator0); setCombiner(elementsListCombiner(accumulator0)); setFinisher(CollectionUtils8.cast()); setCharacteristics(Collections.unmodifiableSet(EnumSet.of(Collector.Characteristics.IDENTITY_FINISH))); } } public static class ListUQCollector<T> extends ListCollector<T> { public ListUQCollector() { BiConsumer<List<T>, T> accumulator0 = uniqueElementsListAccumulator(); setAccumulator(accumulator0); setCombiner(elementsListCombiner(accumulator0)); } } /** * always use first value for key */ public static <T> BinaryOperator<T> keepFirst() { return (p1, p2) -> p1; } /** * always use last value for key */ public static <T> BinaryOperator<T> keepLast() { return (p1, p2) -> p2; } public static <T> T last(Stream<T> stream) { return stream.reduce(keepLast()).orElse(null); } public static <K, V> Entry<K, V> last(SortedMap<K, V> map) { return map.entrySet().stream().reduce(keepLast()).orElse(null); } /** * see {@link #keepLast()} */ public static <V> BinaryOperator<V> acceptDuplicateKeys() { return keepLast(); } /** * rejects !different! keys for the same value * * @throws IllegalArgumentException */ public static <V> BinaryOperator<V> rejectDuplicateKeys() throws IllegalArgumentException { return (a, b) -> { if (new EqualsBuilder().append(a, b).isEquals()) return a; throw new IllegalArgumentException("duplicate key: " + a + " <> " + b); }; } @SuppressWarnings("unchecked") public static <T> T[] array(T item, T... items) { if (item == null && (items == null || items.length == 0)) { return (T[]) new Object[0]; } if (items == null || items.length == 0) { return (T[]) new Object[] { item }; } if (item == null) { return items; } int length = items.length; // FIXME cheaper // operation T[] newarray = Arrays.copyOf(items, 1 + length); newarray[0] = item; System.arraycopy(items, 0, newarray, 1, length); return newarray; } @SuppressWarnings("unchecked") public static <T> T[] array(T[] items, T item) { if (item == null && (items == null || items.length == 0)) { return (T[]) new Object[0]; } if (items == null || items.length == 0) { return (T[]) new Object[] { item }; } if (item == null) { return items; } int length = items.length; T[] newarray = Arrays.copyOf(items, 1 + length); newarray[newarray.length - 1] = item; return newarray; } @SuppressWarnings("unchecked") public static <T> T[] array(T[] items1, T[] items2) { if ((items1 == null || items1.length == 0) && (items2 == null || items2.length == 0)) { return (T[]) new Object[0]; } if (items1 == null || items1.length == 0) { return items2; } if (items2 == null || items2.length == 0) { return items1; } int length1 = items1.length; int length2 = items2.length; T[] newarray = Arrays.copyOf(items1, length1 + length2); System.arraycopy(items2, 0, newarray, length1, length2); return newarray; } public static <T> T[] array(Class<T> componentType, Collection<T> collection) { return array(componentType, collection.stream()); } public static <T> T[] array(Class<T> componentType, Stream<T> stream) { return stream.toArray(newArray(componentType)); } @SuppressWarnings("unchecked") public static <T> IntFunction<T[]> newArray(Class<T> componentType) { return length -> (T[]) Array.newInstance(componentType, length); } public static <T> T[] newArray(Class<T> componentType, int size) { return CollectionUtils8.<T> newArray(componentType).apply(size); } @SuppressWarnings("unchecked") public static <K, V> Entry<K, V>[] array(Map<K, V> map) { return map.entrySet().toArray((Map.Entry<K, V>[]) new Map.Entry[0]); } @SuppressWarnings("unchecked") public static <X, T> Function<X, T> cast() { return x -> (T) x; } public static <T> Function<Object, T> cast(Class<T> type) { return o -> type.cast(o); } public static <T> T cast(Class<T> type, Object object) { return cast(type).apply(object); } @SuppressWarnings("unchecked") public static <T, C extends Collection<T>> Collector<T, ?, C> collector(C collection) { if (collection instanceof Deque) { return (Collector<T, ?, C>) CollectionUtils8.<T> collectDeque(); } if (collection instanceof Queue) { return (Collector<T, ?, C>) CollectionUtils8.<T> collectQueue(); } if (collection instanceof List) { return (Collector<T, ?, C>) CollectionUtils8.<T> collectList(); } if (collection instanceof SortedSet) { return (Collector<T, ?, C>) CollectionUtils8.<T> collectSortedSet(); } if (collection instanceof Set) { return (Collector<T, ?, C>) CollectionUtils8.<T> collectSet(); } throw new UnsupportedOperationException(collection.getClass().getName()); } @SafeVarargs public static <T, C extends Collection<T>> C filter(boolean parallel, C collection, Predicate<? super T>... predicates) { AtomicReference<Stream<T>> streamReference = new AtomicReference<>(stream(parallel, collection)); streamArray(predicates).forEach(predicate -> streamReference.set(streamReference.get().filter(predicate))); C collected = streamReference.get().collect(collector(collection)); return collected; } @SafeVarargs public static <T, C extends Collection<T>> C filter(C collection, Predicate<? super T>... predicates) { return filter(false, collection, predicates); } public static <T> T last(List<T> dd) { int size = dd.size(); return size == 0 ? null : dd.get(size - 1); } public static <K, V> EnhancedMap<K, V> map(Collection<Map.Entry<K, V>> entries) { return map(false, entries); } public static <K, V> EnhancedMap<K, V> map(boolean parallel, Collection<? extends Map.Entry<K, V>> entries) { return map(stream(parallel, entries)); } public static <K, V> EnhancedMap<K, V> map(Stream<? extends Map.Entry<K, V>> stream) { return map(stream, CollectionUtils8.<K, V> newLinkedMap()); } public static <K, V, M extends Map<K, V>> M map(Stream<? extends Map.Entry<K, V>> stream, Supplier<M> mapSupplier) { BinaryOperator<V> keepLast = CollectionUtils8.<V> keepLast(); return map(stream, mapSupplier, keepLast); } public static <K, V, M extends Map<K, V>> M map(Stream<? extends Map.Entry<K, V>> stream, Supplier<M> mapSupplier, BinaryOperator<V> choice) { Function<Entry<K, V>, K> keyMapper = CollectionUtils8.<K, V> keyMapper(); Function<Entry<K, V>, V> valueMapper = CollectionUtils8.<K, V> valueMapper(); Collector<Entry<K, V>, ?, M> c = Collectors.toMap(keyMapper, valueMapper, choice, mapSupplier); return stream.collect(c); } public static <K, V> Supplier<EnhancedLinkedHashMap<K, V>> newLinkedMap() { return EnhancedLinkedHashMap::new; } public static <K, V> Supplier<EnhancedMap<K, V>> newMap() { return EnhancedHashMap::new; } public static <K, V> Supplier<EnhancedSortedMap<K, V>> newSortedMap() { return EnhancedTreeMap::new; } public static <K, V> Supplier<EnhancedTreeMap<K, V>> newNavigableMap() { return EnhancedTreeMap::new; } public static <K, V> Supplier<ConcurrentSkipListMap<K, V>> newConcurrentNavigableMap() { return ConcurrentSkipListMap::new; } public static <K, V> Supplier<ConcurrentHashMap<K, V>> newConcurrentMap() { return ConcurrentHashMap::new; } public static <T> Supplier<Stack<T>> newStack() { return Stack::new; } public static <T> Supplier<Deque<T>> newDeque() { return EnhancedLinkedList::new; } public static <T> Supplier<List<T>> newList() { return EnhancedArrayList::new; } public static <T> Supplier<Queue<T>> newQueue() { return EnhancedLinkedList::new; } public static <T> Supplier<Set<T>> newSet() { return EnhancedHashSet::new; } public static <T> Supplier<SortedSet<T>> newSortedSet() { return EnhancedTreeSet::new; } public static <T> Supplier<BlockingQueue<T>> newBlockingQueue() { return LinkedBlockingDeque::new; } public static <T> Supplier<BlockingDeque<T>> newBlockingDeque() { return LinkedBlockingDeque::new; } public static <T> Supplier<TransferQueue<T>> newTransferQueue() { return LinkedTransferQueue::new; } public static <T, C extends Collection<T>> Collector<T, ?, C> toCollector(Supplier<C> supplier) { return Collectors.toCollection(supplier); } public static <T> Collector<T, ?, Stack<T>> collectStack() { return toCollector(newStack()); } public static <T> Collector<T, ?, Deque<T>> collectDeque() { return toCollector(newDeque()); } public static <T> Collector<T, ?, List<T>> collectList() { return toCollector(newList()); } public static <T, C extends Collection<T>> Collector<T, ?, C> collection(Supplier<C> newCollection) { return Collectors.toCollection(newCollection); } public static <T> ListCollector<T> collectListUQ() { return new ListUQCollector<>(); } public static <T> Collector<T, ?, Queue<T>> collectQueue() { return toCollector(newQueue()); } public static <T> Collector<T, ?, Set<T>> collectSet() { return Collectors.toSet(); } public static <T> Collector<T, ?, SortedSet<T>> collectSortedSet() { return toCollector(newSortedSet()); } public static <T extends Comparable<? super T>> List<T> sort(Collection<T> collection) { return sort(false, collection); } public static <T extends Comparable<? super T>> List<T> sort(boolean parallel, Collection<T> collection) { return stream(parallel, collection).sorted().collect(toCollector(newList())); } public static <T> List<T> sort(boolean parallel, Collection<T> collection, Comparator<? super T> comparator) { return stream(parallel, collection).sorted(comparator).collect(toCollector(newList())); } public static <T> List<T> sort(Collection<T> collection, Comparator<? super T> comparator) { return sort(false, collection, comparator); } public static <T, A> List<T> sortBy(Collection<T> collection, List<A> orderByMe, Function<T, A> map) { return collection.stream().sorted(comparator(orderByMe, map)).collect(collectList()); } public static <T, A> Comparator<T> comparator(List<A> orderByMe, Function<T, A> map) { return (x, y) -> Integer.valueOf(noNegIndex(orderByMe.indexOf(map.apply(x)))) .compareTo(Integer.valueOf(noNegIndex(orderByMe.indexOf(map.apply(y))))); } public static <T> Comparator<T> comparator(List<T> orderByMe) { return comparator(orderByMe, self()); } public static <T> List<T> sortBy(Collection<T> collection, List<T> orderByMe) { return sortBy(collection, orderByMe, self()); } public static <T, S extends Comparable<? super S>> Stream<T> sortBy(Stream<T> sortMe, Map<T, S> sortByMe) { return sortMe.sorted((x, y) -> sortByMe.get(x).compareTo(sortByMe.get(y))); } public static <T, A> Stream<T> sortBy(Stream<T> collection, List<A> orderByMe, Function<T, A> map) { return collection.sorted(comparator(orderByMe, map)); } public static <T> Stream<T> sortBy(Stream<T> collection, List<T> orderByMe) { return sortBy(collection, orderByMe, self()); } public static <T, S extends Comparable<? super S>> List<T> sortBy(Collection<T> sortMe, Map<T, S> sortByMe) { return sortMe.stream().sorted((x, y) -> sortByMe.get(x).compareTo(sortByMe.get(y))).collect(collectList()); } public static <T> Function<T, T> id() { return self(); } public static <T> Function<T, T> self() { return Function.identity(); } public static <T> UnaryOperator<T> idu() { return selfu(); } public static <T> UnaryOperator<T> selfu() { return t -> t; } public static int noNegIndex(int i) { return i == -1 ? Integer.MAX_VALUE : i; } public static <T> Stream<T> stream(Collection<T> collection) { return stream(false, collection); } public static <T> Stream<T> stream(boolean parallel, Collection<T> collection) { return collection == null ? Stream.empty() : StreamSupport.stream(collection.spliterator(), parallel); } public static <T> Stream<T> stream(Iterable<T> iterable) { return stream(false, iterable); } public static <T> Stream<T> stream(Iterator<T> iterator) { return stream(false, iterator); } public static <T> Stream<T> stream(Enumeration<T> enumeration) { return stream(false, enumeration); } public static <T> Stream<T> stream(boolean parallel, Iterable<T> iterable) { return iterable == null ? Stream.empty() : StreamSupport.stream(iterable.spliterator(), parallel); } public static <T> Stream<T> stream(boolean parallel, Iterator<T> iterator) { return iterator == null ? Stream.empty() : StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterator, 0), parallel); } public static <T> Stream<T> stream(boolean parallel, Enumeration<T> enumeration) { return enumeration == null ? Stream.empty() : StreamSupport.stream(Spliterators.spliteratorUnknownSize(enumeration.asIterator(), 0), parallel); } public static Stream<String> lines(Path path) { try { return Files.lines(path); } catch (IOException e) { throw new UncheckedIOException(e); } } public static <K, V> Stream<V> streamValues(Map<K, V> map) { return stream(map).map(valueMapper()); } public static <K, V> Stream<Stream<V>> streamDeepValues(Map<K, ? extends Collection<V>> map) { return stream(map).map(valueMapper()).map(collection -> stream(collection)); } public static <K, V> Stream<Map.Entry<K, V>> stream(Map<K, V> map) { return stream(false, map); } public static <K, V> Stream<Map.Entry<K, V>> stream(boolean parallel, Map<K, V> map) { return map == null ? Stream.empty() : StreamSupport.stream(map.entrySet().spliterator(), parallel); } public static Stream<Path> stream(Path path) { return stream(false, path); } public static Stream<Path> stream(boolean parallel, Path path) { return StreamSupport.stream(path.spliterator(), parallel); } @SafeVarargs public static <T> Stream<T> streamArray(T... array) { return streamArray(false, array); } @SafeVarargs public static <T> Stream<T> streamArray(boolean parallel, T... array) { if (array == null) return Stream.empty(); // StreamSupport.stream(Spliterators.spliterator(array, 0, array.length, // Spliterator.ORDERED | Spliterator.IMMUTABLE), parallel); Stream<T> stream = Arrays.stream(array); if (parallel) stream = stream.parallel(); return stream; } public static <T> Stream<T> streamDetached(Collection<T> collection) { return streamDetached(false, collection); } @SuppressWarnings("unchecked") public static <T> Stream<T> streamDetached(boolean parallel, Collection<T> collection) { return streamArray(parallel, array((Class<T>) Object.class, collection)); } public static <K, V> Stream<Map.Entry<K, V>> streamDetached(Map<K, V> map) { return streamDetached(false, map); } public static <K, V> Stream<Map.Entry<K, V>> streamDetached(boolean parallel, Map<K, V> map) { return streamArray(parallel, array(map)); } public static Stream<Path> streamFully(Path path) { return stream(new PathIterator(path)); } public static <T, U> Stream<U> stream(Collection<T> input, Function<T, Collection<U>> mapping) { return input.stream().map(mapping).map(Collection::stream).flatMap(id()); } public static <T> List<T> toList(Collection<T> collection) { return toList(true, collection); } public static <T> List<T> toList(boolean copy, Collection<T> collection) { return !copy && collection instanceof List ? (List<T>) collection : stream(collection).collect(collectList()); } public static <K, V> Map<K, V> toMap(Map<K, V> map) { return toMap(true, map); } public static <K, V> Map<K, V> toMap(boolean copy, Map<K, V> map) { return !copy /* && map instanceof Map */ ? (Map<K, V>) map : stream(map).collect(collectMap(Entry::getKey, Entry::getValue)); } public static <K, V> SortedMap<K, V> toSortedMap(Map<K, V> map) { return toSortedMap(true, map); } public static <K, V> SortedMap<K, V> toSortedMap(boolean copy, Map<K, V> map) { return !copy && map instanceof SortedMap ? (SortedMap<K, V>) map : stream(map).collect(collectSortedMap(Entry::getKey, Entry::getValue)); } @SafeVarargs public static <T> List<T> toList(T... array) { return streamArray(array).collect(collectList()); } public static <T> Set<T> toSet(Collection<T> collection) { return toSet(true, collection); } public static <T> Set<T> toSet(boolean copy, Collection<T> collection) { return !copy && collection instanceof Set ? (Set<T>) collection : stream(collection).collect(collectSet()); } @SafeVarargs public static <T> Set<T> toSet(T... array) { return streamArray(array).collect(collectSet()); } public static <T> SortedSet<T> toSortedSet(Collection<T> collection) { return toSortedSet(true, collection); } public static <T> SortedSet<T> toSortedSet(boolean copy, Collection<T> collection) { return !copy && collection instanceof SortedSet ? (SortedSet<T>) collection : stream(collection).collect(collectSortedSet()); } @SafeVarargs public static <T> SortedSet<T> toSortedSet(T... array) { return streamArray(array).collect(collectSortedSet()); } public static <T> Queue<T> toQueue(Collection<T> collection) { return stream(collection).collect(collectQueue()); } @SafeVarargs public static <T> Queue<T> toQueue(T... array) { return streamArray(array).collect(collectQueue()); } public static <T> Deque<T> toDeque(Collection<T> collection) { return stream(collection).collect(collectDeque()); } @SafeVarargs public static <T> Deque<T> toDeque(T... array) { return streamArray(array).collect(collectDeque()); } public static <T> Stack<T> toStack(Collection<T> collection) { return stream(collection).collect(collectStack()); } @SafeVarargs public static <T> Stack<T> toStack(T... array) { return streamArray(array).collect(collectStack()); } public static <T, C extends Collection<T>> C to(T[] array, Supplier<C> supplier) { return to(array, toCollector(supplier)); } public static <T, C extends Collection<T>> C to(T[] array, Collector<T, ?, C> collector) { return streamArray(array).collect(collector); } public static <T, C extends Collection<T>> C to(Collection<T> collection, Supplier<C> supplier) { return to(collection, toCollector(supplier)); } public static <T, C extends Collection<T>> C to(Collection<T> collection, Collector<T, ?, C> collector) { return stream(collection).collect(collector); } public static <T> boolean containedInAny(Collection<T> c1, Collection<T> c2) { return c1.stream().anyMatch(c2::contains); } public static <T> Predicate<T> not(Predicate<T> t) { return t.negate(); } public static <T> Predicate<T> isNotBlankAndNotNull() { return t -> t instanceof String ? isNotBlank().test(String.class.cast(t)) : isNotNull().test(t); } public static <T> Predicate<T> isBlankOrNull() { return t -> t instanceof String ? isBlank().test(String.class.cast(t)) : isNull().test(t); } public static Predicate<String> isNotBlank() { return org.apache.commons.lang3.StringUtils::isNotBlank; } public static Predicate<String> isBlank() { return org.apache.commons.lang3.StringUtils::isBlank; } public static <T> Predicate<T> isNotNull() { return Objects::nonNull; } public static <T> Predicate<T> isNull() { return Objects::isNull; } public static <T> Predicate<T> is(T x) { return t -> isEquals(t, x); } public static <T> Predicate<T> isNot(T x) { return not(is(x)); } public static <E> Predicate<E> containedIn(Collection<E> collection) { return collection::contains; } public static <T, E> Predicate<T> containedIn(Collection<E> collection, Function<T, E> converter) { return e -> collection.contains(converter.apply(e)); } public static <K> Predicate<K> keyContainedIn(Map<K, ?> map) { return map::containsKey; } public static <T, K> Predicate<T> keyContainedIn(Map<K, ?> map, Function<T, K> converter) { return e -> map.containsKey(converter.apply(e)); } public static <V> Predicate<V> valueContainedIn(Map<?, V> map) { return map::containsValue; } public static <T, V> Predicate<T> valueContainedIn(Map<?, V> map, Function<T, V> converter) { return e -> map.containsValue(converter.apply(e)); } public static <E> Predicate<E> notContainedIn(Collection<E> collection) { return not(containedIn(collection)); } public static <T, E> Predicate<T> notContainedIn(Collection<E> collection, Function<T, E> converter) { return not(containedIn(collection, converter)); } public static <K> Predicate<K> keyNotContainedIn(Map<K, ?> map) { return not(keyContainedIn(map)); } public static <T, K> Predicate<T> keyNotContainedIn(Map<K, ?> map, Function<T, K> converter) { return not(keyContainedIn(map, converter)); } public static <V> Predicate<V> valueNotContainedIn(Map<?, V> map) { return not(valueContainedIn(map)); } public static <T, V> Predicate<T> valueNotContainedIn(Map<?, V> map, Function<T, V> converter) { return not(valueContainedIn(map, converter)); } public static <X, Y> Function<X, Y> makeNull() { return x -> null; } public static <X> Supplier<X> supplyNull() { return () -> null; } public static <X> Predicate<X> always() { return x -> true; } public static <X> Predicate<X> always(boolean b) { return x -> b; } public static <X> Predicate<X> never() { return x -> false; } public static <X> Predicate<X> never(boolean b) { return x -> !b; } public static <X, Y> BiPredicate<X, Y> always2() { return (x, y) -> true; } public static <X, Y> BiPredicate<X, Y> always2(boolean b) { return (x, y) -> b; } public static <X, Y> BiPredicate<X, Y> never2() { return (x, y) -> false; } public static <X, Y> BiPredicate<X, Y> never2(boolean b) { return (x, y) -> !b; } public static IntStream streamp(String text) { return text.chars(); } public static Stream<Character> stream(String text) { return streamp(text).mapToObj(i -> (char) i); } public static Stream<Character> stream(char[] text) { return stream(new String(text)); } public static Stream<Boolean> stream(Boolean... b) { return IntStream.range(0, b.length).mapToObj(idx -> b[idx]); } public static Stream<Character> stream(Character[] text) { return Arrays.stream(text); } public static <T> List<Map.Entry<T, T>> match(List<T> keys, List<T> values) { return values.stream() .parallel() .filter(containedIn(keys)) .map(value -> new Pair<>(keys.get(keys.indexOf(value)), value)) .collect(collectList()); } public static <T> T optional(T value, Supplier<T> orElse) { return Optional.ofNullable(value).orElseGet(orElse); } public static <T> T optional(T oldValue, T newValue, Consumer<T> whenDifferent) { if (notEquals(oldValue, newValue)) { whenDifferent.accept(newValue); return newValue; } return oldValue; } public static <T> Consumer<T> consume() { return x -> { // }; } public static <T, U> BiConsumer<T, U> biconsume() { return (x, y) -> { return; }; } public static <T> String joinArray(String delimiter, T[] strings) { return join(delimiter, streamArray(strings)); } public static <T> String joinArray(T[] strings) { return join(" ", streamArray(strings)); } public static <T> String join(Collection<T> strings) { return join(" ", stream(strings)); } public static <T> String join(String delimiter, Collection<T> strings) { return join(delimiter, stream(strings)); } public static <T> String join(Stream<T> stream) { return join(" ", stream); } public static <T> String join(String delimiter, Stream<T> stream) { return stream// .filter(Objects::nonNull)// .map(String::valueOf)// .map(String::trim)// .filter(StringUtils::isNotBlank)// .collect(Collectors.joining(delimiter)); } public static <T> String join(String delimiter, boolean skipNull, boolean trim, Stream<T> stream) { if (skipNull) stream = stream.filter(Objects::nonNull); Stream<String> stream2 = stream.map(String::valueOf); if (trim) stream2 = stream2.map(String::trim); if (skipNull) stream2 = stream2.filter(StringUtils::isNotBlank); return stream2.collect(Collectors.joining(delimiter)); } public static Stream<String> split(String string, String delimiter) { return streamArray(string.split(delimiter)); } public static String joining(Stream<String> stream, String delimiter) { return stream.collect(Collectors.joining(delimiter)); } /** * !!!!!!!!!!! terminates source stream !!!!!!!!!!! <br> * !!!!!!!!!!! cannot be used on endless streams !!!!!!!!!!! * * stackoverflow.com/questions/24010109/java-8-stream-reverse-order */ @SuppressWarnings("unchecked") public static <T> Stream<T> reverse(Stream<T> input) { Object[] temp = input.toArray(); return (Stream<T>) IntStream.range(0, temp.length).mapToObj(i -> temp[temp.length - i - 1]); } public static boolean notEquals(Object first, Object second) { return !isEquals(first, second); } public static boolean isEquals(Object first, Object second) { if (first == second) return true; if (first == null && second == null) return true; if (first == null || second == null) return false; return first.equals(second); } /** * staat geen null values in keys toe (alhoewel een map dat wel toe laat) */ public static <V, K> Map<K, List<V>> groupBy(Stream<V> stream, Function<V, K> groupBy) { return stream.collect(Collectors.groupingBy(groupBy)); } /** * workaround om null values in key toe te laten * * @see https://stackoverflow.com/questions/22625065/collectors-groupingby-doesnt-accept-null-keys */ public static <V, K> Map<K, List<V>> groupByAcceptsNull(Stream<V> stream, Function<V, K> groupBy) { return stream// .collect(// Collectors.groupingBy(// Optional can contain null while // null itself throws exception v -> Optional.ofNullable(groupBy.apply(v))// , // order could be important, use LinkedHashMap newLinkedMap()// , // collectList()// )// )// .entrySet()// .stream()// .collect(// Collectors.toMap(// keymapper entry -> entry.getKey().orElse(null)// , // valuemapper entry -> entry.getValue()// , // merge function doesn't matter, key is // always unique keepFirst()// , // order could be important, use LinkedHashMap newLinkedMap()// )// ); } public static <T> Comparator<T> dummyComparator() { return (x, y) -> 0; } public static <K, V> Function<Entry<K, V>, V> valueMapper() { return Entry::getValue; } public static <K, V> Function<Entry<K, V>, K> keyMapper() { return Entry::getKey; } public static Stream<String> regex(String text, String regex) { return stream(new RegexIterator(text, regex)); } public static <T> T[] copy(T[] array) { return copy(array, array.length); } public static <T> T[] copy(T[] array, int length) { return Arrays.copyOf(array, length); } @SafeVarargs public static <K, V> Stream<Entry<K, V>> streamMaps(Map<K, V>... maps) { return Stream.of(maps).map(Map::entrySet).flatMap(Collection::stream); } @SafeVarargs public static <K, V> Stream<Entry<K, V>> streamMapsUnique(Map<K, V>... maps) { return stream(streamMaps(maps).collect(Collectors.toMap(Entry::getKey, Entry::getValue, keepLast(), newLinkedMap()))); } public static <K, V> Collector<Entry<K, V>, ?, EnhancedMap<K, V>> collectMapEntries(Function<Entry<K, V>, V> valueMapper) { return Collectors.toMap(Entry::getKey, valueMapper, rejectDuplicateKeys(), newMap()); } public static <K, V> Collector<Entry<K, V>, ?, EnhancedMap<K, V>> collectMapEntriesAlt(Function<Entry<K, V>, K> keyMapper) { return Collectors.toMap(keyMapper, Entry::getValue, rejectDuplicateKeys(), newMap()); } public static <K, V> Collector<Entry<K, V>, ?, EnhancedMap<K, V>> collectMapEntries() { return Collectors.toMap(Entry::getKey, Entry::getValue, rejectDuplicateKeys(), newMap()); } public static <T, K, V> Collector<T, ?, EnhancedMap<K, V>> collectMap(Function<T, K> keyMapper, Function<T, V> valueMapper) { return collectMap(keyMapper, valueMapper, rejectDuplicateKeys()); } public static <T, K, V> Collector<T, ?, EnhancedMap<K, V>> collectMap(Function<T, K> keyMapper, Function<T, V> valueMapper, BinaryOperator<V> duplicateValues) { return Collectors.toMap(keyMapper, valueMapper, duplicateValues, newMap()); } public static <T, K, V> Collector<T, ?, EnhancedMap<K, V>> collectMapAlt(Function<T, V> valueMapper, BinaryOperator<V> duplicateValues) { @SuppressWarnings("unchecked") Function<T, K> keyMapper = (Function<T, K>) id(); return Collectors.toMap(keyMapper, valueMapper, duplicateValues, newMap()); } public static <K, V> Collector<V, ?, EnhancedMap<K, V>> collectMap(Function<V, K> keyMapper, BinaryOperator<V> duplicateValues) { return collectMap(keyMapper, self(), duplicateValues); } public static <K, V> Collector<V, ?, EnhancedMap<K, V>> collectMap(Function<V, K> keyMapper) { return collectMap(keyMapper, rejectDuplicateKeys()); } public static <T, K, V> Collector<T, ?, EnhancedSortedMap<K, V>> collectSortedMap(Function<T, K> keyMapper, Function<T, V> valueMapper) { return collectSortedMap(keyMapper, valueMapper, rejectDuplicateKeys()); } public static <T, K, V> Collector<T, ?, EnhancedSortedMap<K, V>> collectSortedMap(Function<T, K> keyMapper, Function<T, V> valueMapper, BinaryOperator<V> duplicateValues) { return Collectors.toMap(keyMapper, valueMapper, duplicateValues, newSortedMap()); } public static <K, V> Collector<V, ?, EnhancedSortedMap<K, V>> collectSortedMap(Function<V, K> keyMapper, BinaryOperator<V> duplicateValues) { return collectSortedMap(keyMapper, self(), duplicateValues); } public static <K, V> Collector<V, ?, EnhancedSortedMap<K, V>> collectSortedMap(Function<V, K> keyMapper) { return collectSortedMap(keyMapper, rejectDuplicateKeys()); } public static <T extends Comparable<? super T>> Comparator<T> natural() { return Comparator.<T> naturalOrder(); } public static <T extends Comparable<? super T>> BinaryOperator<T> keepMin() { return keepMin(CollectionUtils8.<T> natural()); } public static <T> BinaryOperator<T> keepMin(Comparator<T> comparator) { return BinaryOperator.minBy(comparator); } public static <T extends Comparable<? super T>> BinaryOperator<T> keepMax() { return keepMax(CollectionUtils8.<T> natural()); } public static <T> BinaryOperator<T> keepMax(Comparator<T> comparator) { return BinaryOperator.maxBy(comparator); } public static IntStream streamInt(int max) { return streamInt(0, 1, max); } public static LongStream streamLong(long max) { return streamLong(0, 1, max); } public static DoubleStream streamDouble(double max) { return streamDouble(0.0, 1.0, max); } public static IntStream streamInt(int start, int max) { return streamInt(start, 1, max); } public static LongStream streamLong(long start, long max) { return streamLong(start, 1, max); } public static DoubleStream streamDouble(double start, double max) { return streamDouble(start, 1.0, max); } public static IntStream streamInt(int start, int step, int max) { return IntStream.iterate(start, i -> i + step).limit(max - start); } public static LongStream streamLong(long start, long step, long max) { return LongStream.iterate(start, i -> i + step).limit(max - start); } public static DoubleStream streamDouble(double start, double step, double max) { return DoubleStream.iterate(start, i -> i + step).limit((long) (max - start)); } @SuppressWarnings("unchecked") public static <T> T[] toArray(Collection<T> collection) { return (T[]) collection.toArray(); } @SuppressWarnings("unchecked") public static <T> T[] toArray(Stream<T> stream, Class<T> type) { return stream.toArray(size -> (T[]) Array.newInstance(type, size)); } public static <T> Stream<T> flatMapCollections(Collection<? extends Collection<T>> collectionOfCollections) { return flatMapStreams(collectionOfCollections.stream().map(Collection::stream)); } public static <T> Stream<T> flatMap(Stream<? extends Collection<T>> streamOfCollections) { return flatMapStreams(streamOfCollections.map(Collection::stream)); } public static <T> Stream<T> flatMap(Collection<Stream<T>> collentionOfStreams) { return flatMapStreams(collentionOfStreams.stream()); } public static <T> Stream<T> flatMapStreams(Stream<Stream<T>> streamOfStreams) { return streamOfStreams.flatMap(id()); } public static <T> Stream<T> flatMapArrays(T[][] streamOfStreams) { Stream<Stream<T>> b = streamArray(streamOfStreams).map(a -> streamArray(a)); return flatMapStreams(b); } public static <T> Opt<T> eager(T value) { return Opt.eager(value); } public static <T> Opt<T> reusable(T value) { return Opt.reusable(value); } /** * c1 - c2, does not change input collections, returns new collection (list) */ public static <T> List<T> subtract(Collection<T> c1, Collection<T> c2) { if (c1 == null) { return Collections.emptyList(); } List<T> tmp = new ArrayList<>(c1); if (c2 != null) { tmp.removeAll(c2); } return tmp; } /** * intersection of c1 and c2, does not change input collections, returns new collection (list) */ public static <T> List<T> intersection(Collection<T> c1, Collection<T> c2) { if (c1 == null || c2 == null) { return Collections.emptyList(); } return c1.stream().filter(c2::contains).collect(collectList()); } /** * intersection of c1 and c2, does not change input collections, returns new collection (list) */ public static <T> List<T> union(Collection<T> c1, Collection<T> c2) { if (c1 == null && c2 == null) { return Collections.emptyList(); } if (c1 == null) { return new ArrayList<>(c2); } if (c2 == null) { return new ArrayList<>(c1); } List<T> tmp = new ArrayList<>(c1.size() + c2.size()); tmp.addAll(c1); tmp.addAll(c2); return tmp; } /** * @see https://stackoverflow.com/questions/42214519/java-intersection-of-multiple-collections-using-stream-lambdas */ public static <T, S extends Collection<T>> Collector<S, ?, Set<T>> intersecting() { class IntersectAcc { Set<T> result; void accept(S s) { if (result == null) result = new HashSet<>(s); else result.retainAll(s); } IntersectAcc combine(IntersectAcc other) { if (result == null) return other; if (other.result != null) result.retainAll(other.result); return this; } } return Collector.of(IntersectAcc::new, IntersectAcc::accept, IntersectAcc::combine, acc -> acc.result == null ? Collections.emptySet() : acc.result, Collector.Characteristics.UNORDERED); } /** * aanTeMakenAct roept teBewaren op met als nieuw object aangeboden door param constructor, constructor en teBewaren zijn niet nullable * * @see #sync(Map, Map, BiConsumer, BiConsumer, BiConsumer) */ public static <K, N, B> void sync(// Map<K, N> nieuwe, // Map<K, B> bestaande, // BiConsumer<K, B> teVerwijderenAct, // Supplier<B> constructor, // BiConsumer<N, B> teBewaren// ) { if (constructor == null || teBewaren == null) throw new NullPointerException(); sync(nieuwe, bestaande, teVerwijderenAct, (k, i) -> teBewaren.accept(i, constructor.get()), teBewaren); } /** * synchroniseer een nieuwe collectie met een bestaande collecte * * @param nieuwe nieuwe collectie vooraf gemapt op key, zie {@link #getMap(Collection, Function)} * @param bestaande bestaande collectie vooraf gemapt op key, zie {@link #getMap(Collection, Function)} * @param teVerwijderenAct nullable, actie op te roepen indien verwijderen, krijgt key en bestaand object binnen * @param aanTeMakenAct nullable, actie op te roepen indien nieuw object aan te maken, krijgt key en nieuw object binnen * @param teBewaren nullable, actie op te roepen indien overeenkomst, krijgt key en nieuw en bestaand object binnen * * @param <K> key waarop vergeleken moet worden * @param <N> nieuwe object * @param <B> bestaand object */ public static <K, N, B> void sync(// Map<K, N> nieuwe, // Map<K, B> bestaande, // BiConsumer<K, B> teVerwijderenAct, // BiConsumer<K, N> aanTeMakenAct, // BiConsumer<N, B> teBewaren// ) { Map<K, B> teVerwijderen = subtract(bestaande.keySet(), nieuwe.keySet()).stream().collect(Collectors.toMap(id(), bestaande::get)); Map<K, N> aanTeMaken = subtract(nieuwe.keySet(), bestaande.keySet()).stream().collect(Collectors.toMap(id(), nieuwe::get)); Map<N, B> overeenkomst = intersection(nieuwe.keySet(), bestaande.keySet()).stream().collect(Collectors.toMap(nieuwe::get, bestaande::get)); if (teBewaren != null) overeenkomst.forEach(teBewaren); if (aanTeMakenAct != null) aanTeMaken.forEach(aanTeMakenAct); if (teVerwijderenAct != null) teVerwijderen.forEach(teVerwijderenAct); } public static <K, V> Map<K, V> getMap(Stream<V> values, Function<V, K> keyMapper) { return values.collect(Collectors.toMap(keyMapper, self())); } public static <K, V> Map<K, V> getMap(Collection<V> values, Function<V, K> keyMapper) { return getMap(values.stream(), keyMapper); } public static <K, V> Map<K, V> getMap(Stream<V> values, Supplier<K> keyMapper) { return values.collect(Collectors.toMap(supplierToFunction(keyMapper), self())); } public static <K, V> Map<K, V> getMap(Collection<V> values, Supplier<K> keyMapper) { return getMap(values.stream(), keyMapper); } public static <K, V> Map<K, V> getKeyMap(Collection<K> values, Function<K, V> valueMapper) { return values.stream().collect(Collectors.toMap(self(), valueMapper)); } public static <K, V> Map<K, V> getKeyMap(Collection<K> values, Supplier<V> valueMapper) { return values.stream().collect(Collectors.toMap(self(), supplierToFunction(valueMapper))); } public static <S, X> Function<X, S> supplierToFunction(Supplier<S> supplier) { return any -> supplier.get(); } public static <T> Supplier<T> supplyAny(T object) { return () -> object; } public static <T> BiConsumer<List<T>, T> elementsListAccumulator() { return (List<T> a, T t) -> a.add(t); } public static <T> BiConsumer<List<T>, T> uniqueElementsListAccumulator() { return (List<T> a, T t) -> { if (!a.contains(t)) a.add(t); }; } public static <T> BinaryOperator<List<T>> elementsListCombiner(BiConsumer<List<T>, T> elementsListAccumulator) { return (List<T> a1, List<T> a2) -> { a2.stream().forEach(a2e -> elementsListAccumulator.accept(a1, a2e)); return a1; }; } public static <T> Consumer<T> when(Predicate<T> restriction, Consumer<T> whenTrue, Consumer<T> whenFalse) { return t -> (restriction.test(t) ? whenTrue : whenFalse).accept(t); } public static <T> Consumer<T> when(boolean restriction, Consumer<T> whenTrue, Consumer<T> whenFalse) { return when(always(restriction), whenTrue, whenFalse); } public static <T> void when(Predicate<T> restriction, Consumer<T> whenTrue, Consumer<T> whenFalse, T subject) { when(restriction, whenTrue, whenFalse).accept(subject); } public static <T> void when(boolean restriction, Consumer<T> whenTrue, Consumer<T> whenFalse, T subject) { when(restriction, whenTrue, whenFalse).accept(subject); } public static <T> Collection<Collection<T>> split(Collection<T> all, int maxSize) { if (maxSize < 1) throw new IllegalArgumentException("maxSize<1"); if (all.size() <= maxSize) return Arrays.asList(all); int totalSize = all.size(); AtomicInteger ai = new AtomicInteger(0); int groups = (totalSize / maxSize) + (totalSize % maxSize > 0 ? 1 : 0); Map<Integer, List<T>> g = all.stream().parallel().collect(Collectors.groupingBy(s -> ai.addAndGet(1) % groups)); return stream(g).map(valueMapper()).collect(collectList()); } public static <T> Stream<List<T>> split(List<T> elements, int count) { return elements.stream().collect(Collectors.groupingBy(c -> elements.indexOf(c) / count)).values().stream(); } public static <T> Function<List<T>, T> first() { return list -> list.isEmpty() ? null : list.get(0); } public static <T> T first(List<T> list) { return list.get(0); } public static <T> T first(LinkedBlockingDeque<T> dq) { return dq.iterator().next(); } public static <T> T first(LinkedBlockingQueue<T> q) { return q.iterator().next(); } public static <T> T first(LinkedHashSet<T> set) { return set.iterator().next(); } public static <K, V> Entry<K, V> first(LinkedHashMap<K, V> map) { return map.entrySet().iterator().next(); } @SafeVarargs public static <T> List<T> sortBy(Collection<T> collection, Function<T, ? extends Comparable<?>> map, Function<T, ? extends Comparable<?>>... mapAdditional) { return collection.stream().sorted(comparator(map, mapAdditional)).collect(collectList()); } @SuppressWarnings({ "rawtypes", "unchecked" }) public static <T extends Comparable<? super T>> List<T> sortInPlace(List<T> list) { Collections.sort((List<? extends Comparable>) list); return list; } @SafeVarargs public static <T> List<T> sortInPlace(List<T> list, Function<T, ? extends Comparable<?>> map, Function<T, ? extends Comparable<?>>... mapAdditional) { list.sort(comparator(map, mapAdditional)); return list; } @SafeVarargs public static <T> Comparator<T> comparator(Function<T, ? extends Comparable<?>> compare, Function<T, ? extends Comparable<?>>... compareAdditional) { return (t1, t2) -> { CompareToBuilder cb = new CompareToBuilder(); cb.append(compare.apply(t1), compare.apply(t2)); streamArray(compareAdditional).forEach(compareThisEl -> cb.append(compareThisEl.apply(t1), compareThisEl.apply(t2))); return cb.toComparison(); }; } public static <T, U> Stream<U> filterClass(Stream<T> stream, Class<U> type) { return stream.filter(t -> type.isAssignableFrom(t.getClass())).map(t -> type.cast(t)); } public static Stream<Map.Entry<String, String>> stream(Properties properties) { return stream(false, properties).map(entry -> new Pair<>(String.valueOf(entry.getKey()), String.valueOf(entry.getValue()))); } public static <K, V> Function<Entry<K, V>, K> mapKey() { return Entry::getKey; } public static <K, V> Function<Entry<K, V>, V> mapValue() { return Entry::getValue; } public static <K, V, T> Map<K, T> map(Map<K, V> map, Function<V, T> valueMapper) { return stream(map).collect(collectMap(mapKey(), e -> valueMapper.apply(e.getValue()))); } public static <K, V, T> Map<T, V> mapKey(Map<K, V> map, Function<K, T> keyMapper) { return stream(map).collect(collectMap(e -> keyMapper.apply(e.getKey()), mapValue())); } public static <T> Comparator<T> comparatorCaseInsensitive(Function<T, String> compare) { Comparators.CaseInsensitiveComparator comparator = new Comparators.CaseInsensitiveComparator(); return (t1, t2) -> { return comparator.compare(compare.apply(t1), compare.apply(t2)); }; } @SuppressWarnings({ "unchecked", "rawtypes" }) public static EnhancedMap<String, List<String>> groupByValue(Properties properties) { return groupByValue((Map<String, String>) (Map) properties); } public static <K, V> EnhancedMap<V, List<K>> groupByValue(Map<K, V> map) { return stream(map.entrySet()) .collect(Collectors.groupingBy(e -> e.getValue(), newMap(), Collectors.mapping(e -> e.getKey(), Collectors.toList()))); } @SuppressWarnings("unchecked") public static <X, Y> Function<X, Y> functions(Function<X, Y>... functions) { Value<Function<X, Y>> returningFunction = new Value<>(functions[0]); Arrays.stream(functions).skip(1).forEach(f -> returningFunction.set(returningFunction.get().andThen(Function.class.cast(f)))); return returningFunction.get(); } public static <X> X nn(X nullable, X defaultValue) { return nullable == null ? defaultValue : nullable; } public static <S, T> Function<S, T> getDefaulted(Function<S, T> getter, T defaultValue) { return ((Function<S, T>) s -> getter.apply(s)).andThen(e -> nn(e, defaultValue)); } public static <X, Y> Y getMapValue(Map<? extends Predicate<X>, Y> map, X in) { return map.entrySet().stream().filter(entry -> entry.getKey().test(in)).map(Map.Entry::getValue).findFirst().orElse(null); } public static <T> List<T> emptyList() { return Collections.emptyList(); } public static <T> Stream<T> emptyStream() { return Stream.empty(); } public static <T, U> Map<T, U> emptyMap() { return Collections.emptyMap(); } public static <T> Set<T> emptySet() { return Collections.emptySet(); } public static String toString(IntStream s) { return s.mapToObj(String::valueOf).collect(Collectors.joining()); } @SafeVarargs public static <T> BiPredicate<T, T> equals(Function<T, ?>... methods) { return (a, b) -> { EqualsBuilder eb = new EqualsBuilder(); Arrays.asList(methods).forEach(g -> eb.append(g.apply(a), g.apply(b))); return eb.isEquals(); }; } @SafeVarargs public static <T> BiFunction<T, T, Integer> bifunction(Function<T, ?>... methods) { return (a, b) -> { if (methods == null || methods.length == 0) { return 0; } CompareToBuilder ctb = new CompareToBuilder(); Arrays.asList(methods).forEach(g -> ctb.append(g.apply(a), g.apply(b))); return ctb.toComparison(); }; } @SafeVarargs public static <T> Comparator<T> comparatorFor(Function<T, ?>... methods) { return comparatorFor(bifunction(methods)); } public static <T> Comparator<T> comparatorFor(BiFunction<T, T, Integer> method) { return method::apply; } public static <T> Collection<T> toUnmodifiableCollection(Collection<T> collection) { return Collections.unmodifiableCollection(toList(true, collection)); } public static <T> List<T> toUnmodifiableList(Collection<T> collection) { return Collections.unmodifiableList(toList(true, collection)); } public static <K, V> Map<K, V> toUnmodifiableMap(Map<K, V> map) { return Collections.unmodifiableMap(toMap(true, map)); } public static <T> Set<T> toUnmodifiableSet(Collection<T> collection) { return Collections.unmodifiableSet(toSet(true, collection)); } public static <K, V> SortedMap<K, V> toUnmodifiableSortedMap(SortedMap<K, V> map) { return Collections.unmodifiableSortedMap(toSortedMap(true, map)); } public static <T> SortedSet<T> toUnmodifiableSortedSet(Collection<T> collection) { return Collections.unmodifiableSortedSet(toSortedSet(true, collection)); } public static <T> Collection<T> toSynchronizedCollection(Collection<T> collection) { return Collections.synchronizedCollection(toList(true, collection)); } public static <T> List<T> toSynchronizedList(Collection<T> collection) { return Collections.synchronizedList(toList(true, collection)); } public static <K, V> Map<K, V> toSynchronizedMap(Map<K, V> map) { return Collections.synchronizedMap(toMap(true, map)); } public static <T> Set<T> toSynchronizedSet(Collection<T> collection) { return Collections.synchronizedSet(toSet(true, collection)); } public static <K, V> SortedMap<K, V> toSynchronizedSortedMap(SortedMap<K, V> map) { return Collections.synchronizedSortedMap(toSortedMap(true, map)); } public static <T> SortedSet<T> toSynchronizedSortedSet(Collection<T> collection) { return Collections.synchronizedSortedSet(toSortedSet(true, collection)); } public static <T> Stream<KeyValue<Integer, T>> index(Stream<T> stream) { IntegerValue index = new IntegerValue(-1); return stream.map(t -> new KeyValue<>(index.add().get(), t)); } public static <T> Map<T, Long> countBy(Stream<T> stream) { return stream.collect(Collectors.groupingBy(Function.identity(), Collectors.counting())); } /** * @see http://stackoverflow.com/questions/26403319/skip-last-x-elements-in-streamt */ public static <T> Stream<T> skip(Stream<T> s, int first, int last) { if (last <= 0 && first <= 0) { return s; } if (last <= 0) { return s.skip(first); } if (first > 0) { s = s.skip(first); } ArrayDeque<T> pending = new ArrayDeque<>(last + 1); Spliterator<T> src = s.spliterator(); return StreamSupport.stream(new Spliterator<T>() { @Override public boolean tryAdvance(Consumer<? super T> action) { while (pending.size() <= last && src.tryAdvance(pending::add)) ; if (pending.size() > last) { action.accept(pending.remove()); return true; } return false; } @Override public Spliterator<T> trySplit() { return null; } @Override public long estimateSize() { return src.estimateSize() - last; } @Override public int characteristics() { return src.characteristics(); } }, false); } public static <T> Stream<T> skip(Integer first, Integer last, Stream<T> s) { return skip(s, first == null ? 0 : first, last == null ? 0 : last); } public static <T> T merge(List<T> list, int index, T object, BinaryOperator<T> operate) { return list.set(index, operate.apply(list.get(index), object)); } public static String append(List<String> list, int index, String string, String seperator) { return merge(list, index, string, (a, b) -> StringUtils.isBlank(a) ? b : a + seperator + b); } public static String firstNotBlank(String... strings) { return streamArray(strings).filter(isNotBlank()).findFirst().orElse(null); } @SafeVarargs public static <T> T firstNotBlankAndNotNull(T... o) { return streamArray(o).filter(isNotBlankAndNotNull()).findFirst().orElse(null); } @SafeVarargs public static <T> T firstNotNull(T... o) { return streamArray(o).filter(isNotNull()).findFirst().orElse(null); } public static <T> List<T> copy(List<T> list, int maxSize) { if (list.size() <= maxSize) return list; return list.stream().limit(maxSize).collect(collectList()); } public static <T> List<T> listLI(List<T> list, T item) { list.add(item); return list; } public static <T> List<T> listIL(T item, List<T> list) { list.add(0, item); return list; } public static <T> List<T> listLL(List<T> list1, List<T> list2) { list1.addAll(list2); return list1; } public static <T> List<T> listCLI(List<T> list, T item) { List<T> tmp = new ArrayList<>(); tmp.addAll(list); tmp.add(item); return tmp; } public static <T> List<T> listCIL(T item, List<T> list) { List<T> tmp = new ArrayList<>(); tmp.add(item); tmp.addAll(list); return tmp; } public static <T> List<T> listCLL(List<T> list1, List<T> list2) { List<T> tmp = new ArrayList<>(); tmp.addAll(list1); tmp.addAll(list2); return tmp; } public static <R, K, V> List<R> flatten(Collection<R> records, Function<R, K> toKey, Function<R, V> toValue, BinaryOperator<V> mergeValue, BiFunction<K, V, R> mergeToRecord) { Map<K, List<R>> map = records.stream().collect(Collectors.groupingBy(toKey)); return map.entrySet().stream().map(entry -> { return new KeyValue<>(entry.getKey(), entry.getValue().stream().map(toValue).reduce(mergeValue).get()); }).map(entry -> { return mergeToRecord.apply(entry.getKey(), entry.getValue()); }).collect(Collectors.toList()); } public static <T> Collector<T, ?, EnhancedMap<T, Integer>> groupingByCount() { return Collectors.groupingBy(id(), newMap(), Collectors.reducing(0, e -> 1, Integer::sum)); } public static <T> Collector<T, ?, EnhancedMap<T, Long>> groupingByCountMany() { return Collectors.groupingBy(id(), newMap(), Collectors.counting()); } public static Comparator<Float> ascFloat() { return (a, b) -> new CompareToBuilder().append(a, b).toComparison(); } public static Comparator<Float> descFloat() { return (a, b) -> -new CompareToBuilder().append(a, b).toComparison(); } public static Comparator<Double> ascDouble() { return (a, b) -> new CompareToBuilder().append(a, b).toComparison(); } public static Comparator<Double> descDouble() { return (a, b) -> -new CompareToBuilder().append(a, b).toComparison(); } public static Comparator<Byte> ascByte() { return (a, b) -> a - b; } public static Comparator<Byte> descByte() { return (a, b) -> b - a; } public static Comparator<Short> ascShort() { return (a, b) -> a - b; } public static Comparator<Short> descShort() { return (a, b) -> b - a; } public static Comparator<Integer> ascInt() { return (a, b) -> a - b; } public static Comparator<Integer> descInt() { return (a, b) -> b - a; } public static Comparator<Long> ascLong() { return (a, b) -> new CompareToBuilder().append(a, b).toComparison(); } public static Comparator<Long> descLong() { return (a, b) -> -new CompareToBuilder().append(a, b).toComparison(); } public static <K, V> LinkedHashMap<K, V> sortByValue(Map<K, V> map, Comparator<V> comparator) { return map.entrySet() .stream() .sorted(Map.Entry.comparingByValue(comparator)) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new)); } public static <T> List<T> repeat(int times, T object) { return IntStream.range(0, times).mapToObj(i -> object).collect(Collectors.toList()); } public static <T> Stream<T> stream(Optional<T> optional) { return optional.isPresent() ? Stream.of(optional.get()) : Stream.empty(); } public static <T extends Serializable> List<T> serializable(List<T> list) { return list instanceof Serializable ? list : new ArrayList<>(list); } public static <T extends Serializable> Set<T> serializable(Set<T> set) { return set instanceof Serializable ? set : new HashSet<>(set); } public static <T extends Serializable> SortedSet<T> serializable(SortedSet<T> set) { return set instanceof Serializable ? set : new TreeSet<>(set); } public static <K extends Serializable, V extends Serializable> Map<K, V> serializable(Map<K, V> set) { return set instanceof Serializable ? set : new HashMap<>(set); } public static <K extends Serializable, V extends Serializable> SortedMap<K, V> serializable(SortedMap<K, V> set) { return set instanceof Serializable ? set : new TreeMap<>(set); } public static IntStream stream(byte[] bytes) { return IntStream.range(0, bytes.length).map(idx -> bytes[idx]); } public static IntStream stream(Byte[] bytes) { return IntStream.range(0, bytes.length).map(idx -> bytes[idx]); } public static <A> Predicate<A> notNullPredicate() { return a -> a instanceof String ? StringUtils.isNotBlank((String) a) : a != null; } public static <A, B> BiPredicate<A, B> notNullBiPredicate() { return (a, b) -> notNullPredicate().test(a) || notNullPredicate().test(b); } public static <A, B, C> TriplePredicate<A, B, C> notNullTriplePredicate() { return (a, b, c) -> notNullPredicate().test(a) || notNullPredicate().test(b) || notNullPredicate().test(c); } public static <A, B, C, D> QuadruplePredicate<A, B, C, D> notNullQuadruplePredicate() { return (a, b, c, d) -> notNullPredicate().test(a) || notNullPredicate().test(b) || notNullPredicate().test(c) || notNullPredicate().test(d); } public static <A, B, C, D, E> QuintuplePredicate<A, B, C, D, E> notNullQuintuplePredicate() { return (a, b, c, d, e) -> notNullPredicate().test(a) || notNullPredicate().test(b) || notNullPredicate().test(c) || notNullPredicate().test(d) || notNullPredicate().test(e); } public static <T> List<T> replaceOrAdd(List<T> list, T object) { if (list == null || object == null) return list; int i = list.indexOf(object); if (i != -1) { list.remove(object); list.add(i, object); } else { list.add(object); } return list; } public static <T> Consumer<T> throwing(Supplier<RuntimeException> exception) { return t -> { throw exception.get(); }; } public static <T> Consumer<T> throwing(RuntimeException exception) { return t -> { throw exception; }; } public static <T> Consumer<T> throwing(Function<T, RuntimeException> exception) { return t -> { throw exception.apply(t); }; } public static BooleanSupplier enhanceBooleanSupplier(EBooleanSupplier supplier) { return EBooleanSupplier.enhance(supplier); } public static <T> Consumer<T> enhanceConsumer(EConsumer<T> consumer) { return EConsumer.enhance(consumer); } public static <T, U> BiConsumer<T, U> enhanceBiConsumer(EBiConsumer<T, U> consumer) { return EBiConsumer.enhance(consumer); } public static DoubleSupplier enhanceDoubleSupplier(EDoubleSupplier supplier) { return EDoubleSupplier.enhance(supplier); } public static <T, R> Function<T, R> enhanceFunction(EFunction<T, R> function) { return EFunction.enhance(function); } public static IntSupplier enhanceIntegerSupplier(EIntSupplier supplier) { return EIntSupplier.enhance(supplier); } public static LongSupplier enhanceLongSupplier(ELongSupplier supplier) { return ELongSupplier.enhance(supplier); } public static <T> Predicate<T> enhancePredicate(EPredicate<T> predicate) { return EPredicate.enhance(predicate); } public static Runnable enhanceRunnable(ERunnable runnable) { return ERunnable.enhance(runnable); } public static <T> Supplier<T> enhanceSupplier(ESupplier<T> predicate) { return ESupplier.enhance(predicate); } public static <K, V> List<KeyValue<K, V>> entryList(Map<K, V> map) { return map.entrySet().stream().map(KeyValue::new).collect(collectList()); } public static <T> T[] merge(T[] a, T[] b) { int aLen = a.length; int bLen = b.length; @SuppressWarnings("unchecked") T[] c = (T[]) Array.newInstance(a.getClass().getComponentType(), aLen + bLen); System.arraycopy(a, 0, c, 0, aLen); System.arraycopy(b, 0, c, aLen, bLen); return c; } public static <T> T[] append(T[] a, @SuppressWarnings("unchecked") T... b) { return merge(a, b); } public static <T> T[] prepend(T[] a, @SuppressWarnings("unchecked") T... b) { return merge(b, a); } public static <T> UnaryOperator<T> unaryOperator(Consumer<T> consumer) { UnaryOperator<T> a = b -> { consumer.accept(b); return b; }; return a; } public static <T> Stream<List<T>> ofSubLists(List<T> source, int length) { if (length <= 0) throw new IllegalArgumentException("length = " + length); int size = source.size(); if (size <= 0) return Stream.empty(); int fullChunks = (size - 1) / length; return IntStream.range(0, fullChunks + 1).mapToObj(n -> source.subList(n * length, n == fullChunks ? size : (n + 1) * length)); } }
backwards compatibility
jhaws/lang/src/main/java/org/jhaws/common/lang/CollectionUtils8.java
backwards compatibility
Java
mit
34a809f4a9e7ae9b58372f09fdb9bd82627d0809
0
testpress/android,testpress/android,testpress/android,testpress/android,testpress/android
package in.testpress.testpress.ui.adapters; import android.app.Activity; import android.content.Context; import android.graphics.Color; import androidx.recyclerview.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.TextView; import com.nostra13.universalimageloader.core.DisplayImageOptions; import com.nostra13.universalimageloader.core.ImageLoader; import java.util.ArrayList; import java.util.List; import in.testpress.core.TestpressSdk; import in.testpress.core.TestpressSession; import in.testpress.course.TestpressCourse; import in.testpress.models.greendao.Chapter; import in.testpress.models.greendao.Content; import in.testpress.models.greendao.CourseAttempt; import in.testpress.models.greendao.Exam; import in.testpress.models.greendao.HtmlContent; import in.testpress.models.greendao.VideoAttempt; import in.testpress.models.greendao.Video; import in.testpress.testpress.R; import in.testpress.testpress.models.pojo.DashboardResponse; import in.testpress.testpress.models.pojo.DashboardSection; import in.testpress.testpress.util.UIUtils; import in.testpress.testpress.util.ImageUtils; import in.testpress.util.IntegerList; public class ContentsCarouselAdapter extends RecyclerView.Adapter<ContentsCarouselAdapter.ItemViewHolder> { private DashboardResponse response; private DashboardSection section; private List<Content> contents = new ArrayList<>(); private ImageLoader imageLoader; private DisplayImageOptions options; private Context context; public ContentsCarouselAdapter(DashboardResponse response, DashboardSection currentSection, Context context) { this.response = response; this.section = currentSection; populateContents(); this.context = context; imageLoader = in.testpress.util.ImageUtils.initImageLoader(context); options = ImageUtils.getPlaceholdersOption(); } private void populateContents() { IntegerList items = section.getItems(); if (section.getContentType().equals("chapter_content")) { for (Integer item : items) { this.contents.add(this.response.getContentHashMap().get(Long.valueOf(item))); } } else { for (Integer item : items) { CourseAttempt attempt = this.response.getContentAttemptHashMap().get(Long.valueOf(item)); this.contents.add(this.response.getContentHashMap().get(attempt.getChapterContentId())); } } } @Override public ItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.content_carousel_item, parent, false); return new ItemViewHolder(view); } @Override public void onBindViewHolder(ItemViewHolder holder, final int position) { final Content content = contents.get(position); showThumbnail(content, holder); setIconAndChapterTitle(content, holder); showOrHideVideoAccessories(content, holder); showOrHideExamAccessories(content, holder); showReadTimeForHtmlContent(content, holder); showIconForAttachmentContent(content, holder); showProgressBarForResumeVideos(position, holder); holder.title.setText(content.getName()); holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Activity activity = (Activity) context; TestpressSession session = TestpressSdk.getTestpressSession(context); TestpressCourse.showContentDetail(activity, content.getId().toString(), session); } }); } private void showThumbnail(Content content, ItemViewHolder holder) { if (content.getCoverImageMedium() != null) { imageLoader.displayImage(content.getCoverImageMedium(), holder.image, options); } else { showThumbnailForVideo(content, holder); } holder.image.setColorFilter(Color.parseColor("#22000000")); } private void showThumbnailForVideo(Content content, ItemViewHolder holder) { imageLoader.displayImage(null, holder.image, options); if (content.getVideoId() != null) { Video video = response.getVideoHashMap().get(content.getVideoId()); if (video.getThumbnailMedium() != null) { imageLoader.displayImage(video.getThumbnailMedium(), holder.image, options); } else { holder.image.setBackgroundColor(Color.parseColor("#77000000")); } } } private void showIconForAttachmentContent(Content content, ItemViewHolder holder) { if (content.getAttachmentId() != null) { holder.playIcon.setImageResource(R.drawable.ic_attachment); holder.playIcon.setVisibility(View.VISIBLE); } } private void showReadTimeForHtmlContent(Content content, ItemViewHolder holder) { if (content.getHtmlId() != null) { HtmlContent htmlContent = response.getHtmlContentHashMap().get(content.getHtmlId()); holder.infoLayout.setVisibility(View.VISIBLE); holder.numberOfQuestions.setText(htmlContent.getReadTime()); holder.infoSubtitle.setVisibility(View.GONE); } } private void showProgressBarForResumeVideos(int position, ItemViewHolder holder) { holder.videoProgressLayout.setVisibility(View.GONE); if (section.getSlug().equals("resume")) { Long attemptId = Long.valueOf(section.getItems().get(position)); CourseAttempt attempt = this.response.getContentAttemptHashMap().get(attemptId); if (attempt.getUserVideoId() != null) { VideoAttempt userVideo = response.getUserVideoHashMap().get(attempt.getUserVideoId()); if (userVideo != null && userVideo.getRawVideoContent() != null && userVideo.getRawVideoContent().getDuration() != null) { float lastPosition = Float.parseFloat(userVideo.getLastPosition()); float totalDuration = Float.parseFloat(userVideo.getRawVideoContent().getDuration()); float watchPercentage = (lastPosition / totalDuration) * 100; holder.videoProgress.setProgress((int) watchPercentage); holder.videoProgressLayout.setVisibility(View.VISIBLE); } } } else { holder.videoProgressLayout.setVisibility(View.GONE); } } private void setIconAndChapterTitle(Content content, ItemViewHolder holder) { if (response.getChapterHashMap().get(content.getChapterId()) != null) { Chapter chapter = response.getChapterHashMap().get(content.getChapterId()); holder.subtitle.setText(chapter.getName()); } switch (content.getContentType().toLowerCase()) { case "video": holder.contentTypeIcon.setImageResource(R.drawable.ic_video_white); break; case "exam": holder.contentTypeIcon.setImageResource(R.drawable.ic_exam_white); break; case "notes": holder.contentTypeIcon.setImageResource(R.drawable.ic_news_white); break; case "attachment": holder.contentTypeIcon.setImageResource(R.drawable.ic_attachment); break; } } private void showOrHideVideoAccessories(Content content, ItemViewHolder holder) { if (content.getVideoId() != null) { holder.playIcon.setVisibility(View.VISIBLE); holder.playIcon.setImageResource(R.drawable.play); } else { holder.playIcon.setVisibility(View.GONE); } } private void showOrHideExamAccessories(Content content, ItemViewHolder holder) { if (content.getExamId() != null) { Exam exam = response.getExamHashMap().get(content.getExamId()); holder.infoLayout.setVisibility(View.VISIBLE); holder.infoSubtitle.setVisibility(View.VISIBLE); holder.numberOfQuestions.setText(exam.getNumberOfQuestions().toString()); } else { holder.infoLayout.setVisibility(View.GONE); } } @Override public int getItemCount() { return contents.size(); } public class ItemViewHolder extends RecyclerView.ViewHolder { ImageView image, playIcon, contentTypeIcon; TextView title, numberOfQuestions, subtitle, infoSubtitle; LinearLayout infoLayout, videoProgressLayout; ProgressBar videoProgress; public ItemViewHolder(View itemView) { super(itemView); image = (ImageView) itemView.findViewById(R.id.image_view); playIcon = (ImageView) itemView.findViewById(R.id.play_icon); contentTypeIcon = (ImageView) itemView.findViewById(R.id.content_type_icon); infoLayout = (LinearLayout) itemView.findViewById(R.id.info_layout); videoProgressLayout = (LinearLayout) itemView.findViewById(R.id.video_progress_layout); title = (TextView) itemView.findViewById(R.id.title); subtitle = (TextView) itemView.findViewById(R.id.subtitle); numberOfQuestions = (TextView) itemView.findViewById(R.id.number_of_questions); numberOfQuestions.setTypeface(TestpressSdk.getRubikMediumFont(context)); infoSubtitle = (TextView) itemView.findViewById(R.id.info_subtitle); videoProgress = (ProgressBar) itemView.findViewById(R.id.video_progress); title.setTypeface(UIUtils.getLatoSemiBoldFont(context)); } } }
app/src/main/java/in/testpress/testpress/ui/adapters/ContentsCarouselAdapter.java
package in.testpress.testpress.ui.adapters; import android.app.Activity; import android.content.Context; import android.graphics.Color; import androidx.recyclerview.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.TextView; import com.nostra13.universalimageloader.core.DisplayImageOptions; import com.nostra13.universalimageloader.core.ImageLoader; import java.util.ArrayList; import java.util.List; import in.testpress.core.TestpressSdk; import in.testpress.core.TestpressSession; import in.testpress.course.TestpressCourse; import in.testpress.models.greendao.Chapter; import in.testpress.models.greendao.Content; import in.testpress.models.greendao.CourseAttempt; import in.testpress.models.greendao.Exam; import in.testpress.models.greendao.HtmlContent; import in.testpress.models.greendao.VideoAttempt; import in.testpress.models.greendao.Video; import in.testpress.testpress.R; import in.testpress.testpress.models.pojo.DashboardResponse; import in.testpress.testpress.models.pojo.DashboardSection; import in.testpress.testpress.util.UIUtils; import in.testpress.testpress.util.ImageUtils; import in.testpress.util.IntegerList; public class ContentsCarouselAdapter extends RecyclerView.Adapter<ContentsCarouselAdapter.ItemViewHolder> { private DashboardResponse response; private DashboardSection section; private List<Content> contents = new ArrayList<>(); private ImageLoader imageLoader; private DisplayImageOptions options; private Context context; public ContentsCarouselAdapter(DashboardResponse response, DashboardSection currentSection, Context context) { this.response = response; this.section = currentSection; populateContents(); this.context = context; imageLoader = in.testpress.util.ImageUtils.initImageLoader(context); options = ImageUtils.getPlaceholdersOption(); } private void populateContents() { IntegerList items = section.getItems(); if (section.getContentType().equals("chapter_content")) { for (Integer item : items) { this.contents.add(this.response.getContentHashMap().get(Long.valueOf(item))); } } else { for (Integer item : items) { CourseAttempt attempt = this.response.getContentAttemptHashMap().get(Long.valueOf(item)); this.contents.add(this.response.getContentHashMap().get(attempt.getChapterContentId())); } } } @Override public ItemViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.content_carousel_item, parent, false); return new ItemViewHolder(view); } @Override public void onBindViewHolder(ItemViewHolder holder, final int position) { final Content content = contents.get(position); showThumbnail(content, holder); setIconAndChapterTitle(content, holder); showOrHideVideoAccessories(content, holder); showOrHideExamAccessories(content, holder); showReadTimeForHtmlContent(content, holder); showIconForAttachmentContent(content, holder); showProgressBarForResumeVideos(position, holder); holder.title.setText(content.getName()); holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Activity activity = (Activity) context; TestpressSession session = TestpressSdk.getTestpressSession(context); TestpressCourse.showContentDetail(activity, content.getId().toString(), session); } }); } private void showThumbnail(Content content, ItemViewHolder holder) { if (content.getCoverImageMedium() != null) { imageLoader.displayImage(content.getCoverImageMedium(), holder.image, options); } else { showThumbnailForVideo(content, holder); } holder.image.setColorFilter(Color.parseColor("#22000000")); } private void showThumbnailForVideo(Content content, ItemViewHolder holder) { imageLoader.displayImage(null, holder.image, options); if (content.getVideoId() != null) { Video video = response.getVideoHashMap().get(content.getVideoId()); if (video.getThumbnailMedium() != null) { imageLoader.displayImage(video.getThumbnailMedium(), holder.image, options); } else { holder.image.setBackgroundColor(Color.parseColor("#77000000")); } } } private void showIconForAttachmentContent(Content content, ItemViewHolder holder) { if (content.getAttachmentId() != null) { holder.playIcon.setImageResource(R.drawable.ic_attachment); holder.playIcon.setVisibility(View.VISIBLE); } } private void showReadTimeForHtmlContent(Content content, ItemViewHolder holder) { if (content.getHtmlId() != null) { HtmlContent htmlContent = response.getHtmlContentHashMap().get(content.getHtmlId()); holder.infoLayout.setVisibility(View.VISIBLE); holder.numberOfQuestions.setText(htmlContent.getReadTime()); holder.infoSubtitle.setVisibility(View.GONE); } } private void showProgressBarForResumeVideos(int position, ItemViewHolder holder) { holder.videoProgressLayout.setVisibility(View.GONE); if (section.getSlug().equals("resume")) { Long attemptId = Long.valueOf(section.getItems().get(position)); CourseAttempt attempt = this.response.getContentAttemptHashMap().get(attemptId); if (attempt.getUserVideoId() != null) { VideoAttempt userVideo = response.getUserVideoHashMap().get(attempt.getUserVideoId()); if (userVideo.getRawVideoContent() != null && userVideo.getRawVideoContent().getDuration() != null) { float lastPosition = Float.parseFloat(userVideo.getLastPosition()); float totalDuration = Float.parseFloat(userVideo.getRawVideoContent().getDuration()); float watchPercentage = (lastPosition / totalDuration) * 100; holder.videoProgress.setProgress((int) watchPercentage); holder.videoProgressLayout.setVisibility(View.VISIBLE); } } } else { holder.videoProgressLayout.setVisibility(View.GONE); } } private void setIconAndChapterTitle(Content content, ItemViewHolder holder) { if (response.getChapterHashMap().get(content.getChapterId()) != null) { Chapter chapter = response.getChapterHashMap().get(content.getChapterId()); holder.subtitle.setText(chapter.getName()); } switch (content.getContentType().toLowerCase()) { case "video": holder.contentTypeIcon.setImageResource(R.drawable.ic_video_white); break; case "exam": holder.contentTypeIcon.setImageResource(R.drawable.ic_exam_white); break; case "notes": holder.contentTypeIcon.setImageResource(R.drawable.ic_news_white); break; case "attachment": holder.contentTypeIcon.setImageResource(R.drawable.ic_attachment); break; } } private void showOrHideVideoAccessories(Content content, ItemViewHolder holder) { if (content.getVideoId() != null) { holder.playIcon.setVisibility(View.VISIBLE); holder.playIcon.setImageResource(R.drawable.play); } else { holder.playIcon.setVisibility(View.GONE); } } private void showOrHideExamAccessories(Content content, ItemViewHolder holder) { if (content.getExamId() != null) { Exam exam = response.getExamHashMap().get(content.getExamId()); holder.infoLayout.setVisibility(View.VISIBLE); holder.infoSubtitle.setVisibility(View.VISIBLE); holder.numberOfQuestions.setText(exam.getNumberOfQuestions().toString()); } else { holder.infoLayout.setVisibility(View.GONE); } } @Override public int getItemCount() { return contents.size(); } public class ItemViewHolder extends RecyclerView.ViewHolder { ImageView image, playIcon, contentTypeIcon; TextView title, numberOfQuestions, subtitle, infoSubtitle; LinearLayout infoLayout, videoProgressLayout; ProgressBar videoProgress; public ItemViewHolder(View itemView) { super(itemView); image = (ImageView) itemView.findViewById(R.id.image_view); playIcon = (ImageView) itemView.findViewById(R.id.play_icon); contentTypeIcon = (ImageView) itemView.findViewById(R.id.content_type_icon); infoLayout = (LinearLayout) itemView.findViewById(R.id.info_layout); videoProgressLayout = (LinearLayout) itemView.findViewById(R.id.video_progress_layout); title = (TextView) itemView.findViewById(R.id.title); subtitle = (TextView) itemView.findViewById(R.id.subtitle); numberOfQuestions = (TextView) itemView.findViewById(R.id.number_of_questions); numberOfQuestions.setTypeface(TestpressSdk.getRubikMediumFont(context)); infoSubtitle = (TextView) itemView.findViewById(R.id.info_subtitle); videoProgress = (ProgressBar) itemView.findViewById(R.id.video_progress); title.setTypeface(UIUtils.getLatoSemiBoldFont(context)); } } }
Fix app crash on incomplete dashboard data If dashboard data does not have user video app will crash. This is fixed by checking is uservideo is present or not
app/src/main/java/in/testpress/testpress/ui/adapters/ContentsCarouselAdapter.java
Fix app crash on incomplete dashboard data
Java
mit
d4de09c4a3f2fcb60c635afe3b618a935d524894
0
ThorbenKuck/NetCom2
package com.github.thorbenkuck.netcom2.auto.annotations.processor; import javax.annotation.processing.AbstractProcessor; import javax.annotation.processing.Filer; import javax.annotation.processing.ProcessingEnvironment; import javax.annotation.processing.RoundEnvironment; import javax.lang.model.SourceVersion; import javax.lang.model.element.Element; import javax.lang.model.element.TypeElement; import javax.lang.model.util.Elements; import javax.lang.model.util.Types; import java.lang.annotation.Annotation; import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; public abstract class AnnotationProcessor extends AbstractProcessor { private final List<Element> alreadyProcessed = new ArrayList<>(); protected Types types; protected Elements elements; protected Filer filer; protected CompilationLogger logger; private List<? extends Element> filter(Set<? extends Element> input) { List<Element> value = new ArrayList<>(); for (Element element : input) { if (!alreadyProcessed.contains(element)) { logger.log("Will process " + element.getSimpleName(), element); alreadyProcessed.add(element); value.add(element); } } return value; } protected abstract void pre(); protected abstract Class<? extends Annotation> supported(); protected abstract boolean process(Element element); protected void post(List<Element> handled) { } @Override public final Set<String> getSupportedAnnotationTypes() { Set<String> annotations = new LinkedHashSet<>(); annotations.add(supported().getCanonicalName()); return annotations; } @Override public final SourceVersion getSupportedSourceVersion() { return SourceVersion.latestSupported(); } @Override public final synchronized void init(ProcessingEnvironment processingEnv) { super.init(processingEnv); types = processingEnv.getTypeUtils(); elements = processingEnv.getElementUtils(); filer = processingEnv.getFiler(); logger = new CompilationLogger(processingEnv.getMessager()); } @Override public final boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { pre(); boolean error = false; List<? extends Element> toProcess = filter(roundEnv.getElementsAnnotatedWith(supported())); for (Element element : toProcess) { boolean success; try { success = process(element); } catch (Throwable throwable) { logger.error(throwable.getMessage(), element); throwable.printStackTrace(); success = false; } if (!success) { error = true; } } post(alreadyProcessed); return !error; } }
auto/src/main/java/com/github/thorbenkuck/netcom2/auto/annotations/processor/AnnotationProcessor.java
package com.github.thorbenkuck.netcom2.auto.annotations.processor; import javax.annotation.processing.AbstractProcessor; import javax.annotation.processing.Filer; import javax.annotation.processing.ProcessingEnvironment; import javax.annotation.processing.RoundEnvironment; import javax.lang.model.SourceVersion; import javax.lang.model.element.Element; import javax.lang.model.element.TypeElement; import javax.lang.model.util.Elements; import javax.lang.model.util.Types; import java.lang.annotation.Annotation; import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; public abstract class AnnotationProcessor extends AbstractProcessor { private final List<? super Element> alreadyProcessed = new ArrayList<>(); protected Types types; protected Elements elements; protected Filer filer; protected CompilationLogger logger; private List<? extends Element> filter(Set<? extends Element> input) { List<Element> value = new ArrayList<>(); for (Element element : input) { if (!alreadyProcessed.contains(element)) { logger.log("Will process " + element.getSimpleName(), element); alreadyProcessed.add(element); value.add(element); } } return value; } protected abstract void pre(); protected abstract Class<? extends Annotation> supported(); protected abstract boolean process(Element element); @Override public final Set<String> getSupportedAnnotationTypes() { Set<String> annotations = new LinkedHashSet<>(); annotations.add(supported().getCanonicalName()); return annotations; } @Override public final SourceVersion getSupportedSourceVersion() { return SourceVersion.latestSupported(); } @Override public final synchronized void init(ProcessingEnvironment processingEnv) { super.init(processingEnv); types = processingEnv.getTypeUtils(); elements = processingEnv.getElementUtils(); filer = processingEnv.getFiler(); logger = new CompilationLogger(processingEnv.getMessager()); } @Override public final boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { pre(); boolean error = false; List<? extends Element> toProcess = filter(roundEnv.getElementsAnnotatedWith(supported())); for (Element element : toProcess) { boolean success; try { success = process(element); } catch (Throwable throwable) { logger.error(throwable.getMessage(), element); throwable.printStackTrace(); success = false; } if (!success) { error = true; } } return !error; } }
added post method to abstract AnnotationProcessor
auto/src/main/java/com/github/thorbenkuck/netcom2/auto/annotations/processor/AnnotationProcessor.java
added post method to abstract AnnotationProcessor
Java
mpl-2.0
e675ab3596da2255df864b44aaed33c55b51822b
0
powsybl/powsybl-core,itesla/ipst-core,powsybl/powsybl-core,itesla/ipst-core,itesla/ipst-core,itesla/ipst-core,powsybl/powsybl-core
/** * Copyright (c) 2016, RTE (http://www.rte-france.com) * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package eu.itesla_project.iidm.network.impl; import eu.itesla_project.iidm.network.*; import org.junit.Test; import static org.junit.Assert.assertEquals; /** * ArrayIndexOutOfBoundsException fix test * @author Geoffroy Jamgotchian <geoffroy.jamgotchian at rte-france.com> */ public class EmptyCalculatedBusBugTest { private Network createNetwork(boolean retainded) { Network network = NetworkFactory.create("test", "test"); Substation s = network.newSubstation() .setId("S") .setCountry(Country.FR) .add(); VoltageLevel vl = s.newVoltageLevel() .setId("VL") .setNominalV(400f) .setTopologyKind(TopologyKind.NODE_BREAKER) .add(); vl.getNodeBreakerView().setNodeCount(2); vl.getNodeBreakerView().newBreaker() .setId("SW1") .setNode1(0) .setNode2(1) .setOpen(false) .setRetained(retainded) .add(); return network; } @Test public void test() { Network network = createNetwork(false); assertEquals(1, network.getVoltageLevel("VL").getBusBreakerView().getBusStream().count()); network = createNetwork(true); assertEquals(2, network.getVoltageLevel("VL").getBusBreakerView().getBusStream().count()); } }
iidm-network-impl/src/test/java/eu/itesla_project/iidm/network/impl/EmptyCalculatedBusBugTest.java
/** * Copyright (c) 2016, RTE (http://www.rte-france.com) * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package eu.itesla_project.iidm.network.impl; import eu.itesla_project.iidm.network.*; import org.junit.Test; import static org.junit.Assert.assertEquals; /** * ArrayIndexOutOfBoundsException fix test * @author Geoffroy Jamgotchian <geoffroy.jamgotchian at rte-france.com> */ public class EmptyCalculatedBusBugTest { @Test public void test() { Network network = NetworkFactory.create("test", "test"); Substation s = network.newSubstation() .setId("S") .setCountry(Country.FR) .add(); VoltageLevel vl = s.newVoltageLevel() .setId("VL") .setNominalV(400f) .setTopologyKind(TopologyKind.NODE_BREAKER) .add(); vl.getNodeBreakerView().setNodeCount(2); vl.getNodeBreakerView().newBreaker() .setId("SW1") .setNode1(0) .setNode2(1) .setOpen(false) .setRetained(false) .add(); assertEquals(2, vl.getBusBreakerView().getBusStream().count()); } }
Fix compilation and add another test
iidm-network-impl/src/test/java/eu/itesla_project/iidm/network/impl/EmptyCalculatedBusBugTest.java
Fix compilation and add another test
Java
agpl-3.0
107954a67ba0dd167b25e07c18e82838631ed6b0
0
aihua/opennms,tdefilip/opennms,rdkgit/opennms,rdkgit/opennms,rdkgit/opennms,tdefilip/opennms,roskens/opennms-pre-github,tdefilip/opennms,roskens/opennms-pre-github,rdkgit/opennms,rdkgit/opennms,aihua/opennms,tdefilip/opennms,aihua/opennms,tdefilip/opennms,aihua/opennms,roskens/opennms-pre-github,roskens/opennms-pre-github,aihua/opennms,rdkgit/opennms,roskens/opennms-pre-github,roskens/opennms-pre-github,roskens/opennms-pre-github,aihua/opennms,rdkgit/opennms,aihua/opennms,roskens/opennms-pre-github,roskens/opennms-pre-github,roskens/opennms-pre-github,rdkgit/opennms,aihua/opennms,tdefilip/opennms,roskens/opennms-pre-github,tdefilip/opennms,aihua/opennms,tdefilip/opennms,tdefilip/opennms,rdkgit/opennms,rdkgit/opennms
/* * This file is part of the OpenNMS(R) Application. * * OpenNMS(R) is Copyright (C) 2009 The OpenNMS Group, Inc. All rights reserved. * OpenNMS(R) is a derivative work, containing both original code, included code and modified * code that was published under the GNU General Public License. Copyrights for modified * and included code are below. * * OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc. * * Modifications: * * Created: January 7, 2009 * * Copyright (C) 2009 The OpenNMS Group, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * For more information contact: * OpenNMS Licensing <[email protected]> * http://www.opennms.org/ * http://www.opennms.com/ */ package org.opennms.netmgt.ackd; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Properties; import java.util.Set; import junit.framework.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.opennms.netmgt.EventConstants; import org.opennms.netmgt.dao.AcknowledgmentDao; import org.opennms.netmgt.dao.AlarmDao; import org.opennms.netmgt.dao.DatabasePopulator; import org.opennms.netmgt.dao.EventDao; import org.opennms.netmgt.dao.JavaMailConfigurationDao; import org.opennms.netmgt.dao.NodeDao; import org.opennms.netmgt.dao.NotificationDao; import org.opennms.netmgt.dao.UserNotificationDao; import org.opennms.netmgt.dao.db.JUnitTemporaryDatabase; import org.opennms.netmgt.dao.db.OpenNMSConfigurationExecutionListener; import org.opennms.netmgt.dao.db.TemporaryDatabaseExecutionListener; import org.opennms.netmgt.mock.MockEventIpcManager; import org.opennms.netmgt.model.AckType; import org.opennms.netmgt.model.OnmsAcknowledgment; import org.opennms.netmgt.model.OnmsAlarm; import org.opennms.netmgt.model.OnmsEvent; import org.opennms.netmgt.model.OnmsNode; import org.opennms.netmgt.model.OnmsNotification; import org.opennms.netmgt.model.OnmsSeverity; import org.opennms.netmgt.model.OnmsUserNotification; import org.opennms.netmgt.model.events.EventBuilder; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; import org.springframework.test.context.support.DirtiesContextTestExecutionListener; import org.springframework.test.context.transaction.TransactionalTestExecutionListener; import org.springframework.transaction.annotation.Transactional; @RunWith(SpringJUnit4ClassRunner.class) @TestExecutionListeners({ OpenNMSConfigurationExecutionListener.class, TemporaryDatabaseExecutionListener.class, DependencyInjectionTestExecutionListener.class, DirtiesContextTestExecutionListener.class, TransactionalTestExecutionListener.class }) @ContextConfiguration(locations={ "classpath:/META-INF/opennms/applicationContext-dao.xml", "classpath:/META-INF/opennms/applicationContext-daemon.xml", "classpath:/META-INF/opennms/mockEventIpcManager.xml", "classpath:/META-INF/opennms/applicationContext-setupIpLike-enabled.xml", "classpath:/META-INF/opennms/applicationContext-ackd.xml", "classpath:/META-INF/opennms/applicationContext-databasePopulator.xml" }) /** * Acknowledgment Daemon tests * * @author <a href="mailto:[email protected]">David Hustace</a> */ @JUnitTemporaryDatabase(populate=true) @Transactional public class AckdTest { @Autowired private AckService m_ackService; @Autowired private MockEventIpcManager m_mockEventIpcManager; @Autowired private AlarmDao m_alarmDao; @Autowired private EventDao m_eventDao; @Autowired private Ackd m_daemon; @Autowired private AcknowledgmentDao m_ackDao; @Autowired private NodeDao m_nodeDao; @Autowired private DatabasePopulator m_populator; @Autowired private NotificationDao m_notificationDao; @Autowired private UserNotificationDao m_userNotificationDao; @Autowired private JavaMailConfigurationDao m_jmConfigDao; @Before public void setUp() throws Exception { Properties props = new Properties(); props.setProperty("log4j.logger.org.hibernate", "INFO"); props.setProperty("log4j.logger.org.springframework", "INFO"); props.setProperty("log4j.logger.org.hibernate.SQL", "DEBUG"); m_populator.populateDatabase(); } @Test public void testWiring() { Assert.assertNotNull(m_ackDao); Assert.assertNotNull(m_alarmDao); Assert.assertNotNull(m_eventDao); Assert.assertNotNull(m_nodeDao); Assert.assertNotNull(m_notificationDao); Assert.assertNotNull(m_userNotificationDao); Assert.assertNotNull(m_mockEventIpcManager); Assert.assertNotNull(m_ackService); Assert.assertNotNull(m_daemon); Assert.assertNotNull(m_populator); Assert.assertNotNull(m_jmConfigDao); Assert.assertSame("dao from populator should refer to same dao from local properties", m_populator.getAcknowledgmentDao(), m_ackDao); } /** * Make sure the DB is not empty */ @Test public void testDbState() { Assert.assertFalse(m_nodeDao.findAll().isEmpty()); } /** * This tests the acknowledgment of an alarm and any related notifications. */ @Test public void testAcknowledgeAlarm() { VerificationObject vo = createAckStructure(); Assert.assertTrue(vo.m_nodeId > 0); Assert.assertTrue(vo.m_alarmId > 0); Assert.assertTrue(vo.m_eventID > 0); Assert.assertTrue(vo.m_userNotifId > 0); OnmsAlarm alarm = m_alarmDao.get(vo.m_alarmId); OnmsAcknowledgment ack = new OnmsAcknowledgment(m_alarmDao.get(vo.m_alarmId)); m_ackDao.save(ack); m_ackDao.flush(); m_ackService.processAck(ack); alarm = m_alarmDao.get(ack.getRefId()); Assert.assertNotNull(alarm.getAlarmAckUser()); Assert.assertEquals("admin", alarm.getAlarmAckUser()); OnmsNotification notif = m_notificationDao.get(vo.m_notifId); Assert.assertNotNull(notif); Assert.assertEquals("admin", notif.getAnsweredBy()); Assert.assertEquals(alarm.getAlarmAckTime(), notif.getRespondTime()); } /** * This tests acknowledging a notification and a related alarm. If events are being deduplicated * they should all have the same alarm ID. */ @Test public void testAcknowledgeNotification() { VerificationObject vo = createAckStructure(); Assert.assertTrue(vo.m_nodeId > 0); Assert.assertTrue(vo.m_alarmId > 0); Assert.assertTrue(vo.m_eventID > 0); Assert.assertTrue(vo.m_userNotifId > 0); OnmsAcknowledgment ack = new OnmsAcknowledgment(m_notificationDao.get(vo.m_notifId)); m_ackDao.save(ack); m_ackDao.flush(); m_ackService.processAck(ack); OnmsNotification notif = m_notificationDao.get(ack.getRefId()); Assert.assertNotNull(notif.getAnsweredBy()); Assert.assertEquals("admin", notif.getAnsweredBy()); OnmsAlarm alarm = m_alarmDao.get(vo.m_alarmId); Assert.assertNotNull(alarm); Assert.assertEquals("admin", alarm.getAlarmAckUser()); Assert.assertEquals(alarm.getAlarmAckTime(), notif.getRespondTime()); } @Test public void testHandelEvent() throws InterruptedException { VerificationObject vo = createAckStructure(); EventBuilder bldr = new EventBuilder("uei.opennms.org/internal/ackd/Acknowledge", "AckdTest"); bldr.addParam("ackType", String.valueOf(AckType.ALARM)); bldr.addParam("refId", vo.m_alarmId); final String user = "ackd-test-user"; bldr.addParam("user", user); m_daemon.handleAckEvent(bldr.getEvent()); OnmsNotification notif = m_notificationDao.get(vo.m_notifId); Assert.assertEquals(notif.getAckUser(), user); // Assert.assertEquals(notif.getAckTime(), bldr.getEvent().getTime()); OnmsAlarm alarm = m_alarmDao.get(vo.m_alarmId); Assert.assertEquals(alarm.getAckUser(), user); // Assert.assertEquals(alarm.getAckTime(), bldr.getEvent().getTime()); } class VerificationObject { int m_eventID; int m_alarmId; int m_nodeId; int m_notifId; int m_userNotifId; } private VerificationObject createAckStructure() { final Date time = new Date(); VerificationObject vo = new VerificationObject(); List<OnmsNode> nodes = m_nodeDao.findAll(); Assert.assertTrue("List of nodes should not be empty", nodes.size() > 0); OnmsNode node = m_nodeDao.get(nodes.get(0).getId()); vo.m_nodeId = node.getId(); OnmsEvent event = new OnmsEvent(); event.setDistPoller(node.getDistPoller()); event.setNode(node); event.setEventCreateTime(time); event.setEventDescr("Test node down event."); event.setEventSeverity(6); event.setEventSource("AckdTest"); event.setEventTime(time); event.setEventUei(EventConstants.NODE_DOWN_EVENT_UEI); event.setIpAddr(node.getPrimaryInterface().getIpAddress()); event.setEventLog("Y"); event.setEventDisplay("Y"); event.setEventLogMsg("Testing node down event from AckdTest."); m_eventDao.save(event); vo.m_eventID = event.getId(); OnmsAlarm alarm = new OnmsAlarm(); alarm.setAlarmType(1); alarm.setClearKey("abc"); alarm.setClearUei(EventConstants.NODE_UP_EVENT_UEI); alarm.setCounter(1); alarm.setDescription(event.getEventDescr()); alarm.setDistPoller(event.getDistPoller()); alarm.setFirstEventTime(event.getEventTime()); alarm.setIpAddr(event.getIpAddr()); alarm.setLastEvent(event); alarm.setLastEventTime(event.getEventTime()); alarm.setLogMsg("Some Log Message"); alarm.setNode(event.getNode()); alarm.setReductionKey("xyz"); alarm.setServiceType(event.getServiceType()); alarm.setSeverity(OnmsSeverity.get(event.getEventSeverity())); alarm.setUei(event.getEventUei()); m_alarmDao.save(alarm); vo.m_alarmId = alarm.getId(); event.setAlarm(alarm); OnmsNotification notif = new OnmsNotification(); notif.setEvent(event); notif.setEventUei(event.getEventUei()); notif.setIpAddress(event.getIpAddr()); notif.setNode(event.getNode()); notif.setNotifConfigName("abc"); notif.setNumericMsg(event.getEventLogMsg()); notif.setPageTime(event.getEventTime()); notif.setServiceType(event.getServiceType()); notif.setSubject("notifyid: 1, node down"); notif.setTextMsg(event.getEventLogMsg()); m_notificationDao.save(notif); vo.m_notifId = notif.getNotifyId(); OnmsUserNotification userNotif = new OnmsUserNotification(); userNotif.setAutoNotify("Y"); userNotif.setContactInfo("[email protected]"); userNotif.setMedia("page"); userNotif.setNotification(notif); userNotif.setNotifyTime(event.getEventTime()); userNotif.setUserId("me"); Set<OnmsUserNotification> usersnotifieds = new HashSet<OnmsUserNotification>(); usersnotifieds.add(userNotif); m_userNotificationDao.save(userNotif); vo.m_userNotifId = userNotif.getId(); notif.setUsersNotified(usersnotifieds); m_notificationDao.update(notif); m_eventDao.update(event); m_eventDao.flush(); return vo; } }
opennms-ackd/src/test/java/org/opennms/netmgt/ackd/AckdTest.java
/* * This file is part of the OpenNMS(R) Application. * * OpenNMS(R) is Copyright (C) 2009 The OpenNMS Group, Inc. All rights reserved. * OpenNMS(R) is a derivative work, containing both original code, included code and modified * code that was published under the GNU General Public License. Copyrights for modified * and included code are below. * * OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc. * * Modifications: * * Created: January 7, 2009 * * Copyright (C) 2009 The OpenNMS Group, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * For more information contact: * OpenNMS Licensing <[email protected]> * http://www.opennms.org/ * http://www.opennms.com/ */ package org.opennms.netmgt.ackd; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Properties; import java.util.Set; import junit.framework.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.opennms.netmgt.EventConstants; import org.opennms.netmgt.dao.AcknowledgmentDao; import org.opennms.netmgt.dao.AlarmDao; import org.opennms.netmgt.dao.DatabasePopulator; import org.opennms.netmgt.dao.EventDao; import org.opennms.netmgt.dao.JavaMailConfigurationDao; import org.opennms.netmgt.dao.NodeDao; import org.opennms.netmgt.dao.NotificationDao; import org.opennms.netmgt.dao.UserNotificationDao; import org.opennms.netmgt.dao.db.JUnitTemporaryDatabase; import org.opennms.netmgt.dao.db.OpenNMSConfigurationExecutionListener; import org.opennms.netmgt.dao.db.TemporaryDatabaseExecutionListener; import org.opennms.netmgt.mock.MockEventIpcManager; import org.opennms.netmgt.model.AckType; import org.opennms.netmgt.model.OnmsAcknowledgment; import org.opennms.netmgt.model.OnmsAlarm; import org.opennms.netmgt.model.OnmsEvent; import org.opennms.netmgt.model.OnmsNode; import org.opennms.netmgt.model.OnmsNotification; import org.opennms.netmgt.model.OnmsSeverity; import org.opennms.netmgt.model.OnmsUserNotification; import org.opennms.netmgt.model.events.EventBuilder; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; import org.springframework.test.context.support.DirtiesContextTestExecutionListener; import org.springframework.test.context.transaction.TransactionalTestExecutionListener; import org.springframework.transaction.annotation.Transactional; @RunWith(SpringJUnit4ClassRunner.class) @TestExecutionListeners({ OpenNMSConfigurationExecutionListener.class, TemporaryDatabaseExecutionListener.class, DependencyInjectionTestExecutionListener.class, DirtiesContextTestExecutionListener.class, TransactionalTestExecutionListener.class }) @ContextConfiguration(locations={ "classpath:/META-INF/opennms/applicationContext-dao.xml", "classpath:/META-INF/opennms/applicationContext-daemon.xml", "classpath:/META-INF/opennms/mockEventIpcManager.xml", "classpath:/META-INF/opennms/applicationContext-setupIpLike-enabled.xml", "classpath:/META-INF/opennms/applicationContext-ackd.xml", "classpath:/META-INF/opennms/applicationContext-databasePopulator.xml" }) /** * Acknowledgment Daemon tests * * @author <a href="mailto:[email protected]">David Hustace</a> */ @JUnitTemporaryDatabase(populate=true) public class AckdTest { @Autowired private AckService m_ackService; @Autowired private MockEventIpcManager m_mockEventIpcManager; @Autowired private AlarmDao m_alarmDao; @Autowired private EventDao m_eventDao; @Autowired private Ackd m_daemon; @Autowired private AcknowledgmentDao m_ackDao; @Autowired private NodeDao m_nodeDao; @Autowired private DatabasePopulator m_populator; @Autowired private NotificationDao m_notificationDao; @Autowired private UserNotificationDao m_userNotificationDao; @Autowired private JavaMailConfigurationDao m_jmConfigDao; @Before public void setUp() throws Exception { Properties props = new Properties(); props.setProperty("log4j.logger.org.hibernate", "INFO"); props.setProperty("log4j.logger.org.springframework", "INFO"); props.setProperty("log4j.logger.org.hibernate.SQL", "DEBUG"); m_populator.populateDatabase(); } @Transactional @Test public void testWiring() { Assert.assertNotNull(m_ackDao); Assert.assertNotNull(m_alarmDao); Assert.assertNotNull(m_eventDao); Assert.assertNotNull(m_nodeDao); Assert.assertNotNull(m_notificationDao); Assert.assertNotNull(m_userNotificationDao); Assert.assertNotNull(m_mockEventIpcManager); Assert.assertNotNull(m_ackService); Assert.assertNotNull(m_daemon); Assert.assertNotNull(m_populator); Assert.assertNotNull(m_jmConfigDao); Assert.assertSame("dao from populator should refer to same dao from local properties", m_populator.getAcknowledgmentDao(), m_ackDao); } /** * Make sure the DB is not empty */ @Transactional @Test public void testDbState() { Assert.assertFalse(m_nodeDao.findAll().isEmpty()); } /** * This tests the acknowledgment of an alarm and any related notifications. */ @Transactional @Test public void testAcknowledgeAlarm() { VerificationObject vo = createAckStructure(); Assert.assertTrue(vo.m_nodeId > 0); Assert.assertTrue(vo.m_alarmId > 0); Assert.assertTrue(vo.m_eventID > 0); Assert.assertTrue(vo.m_userNotifId > 0); OnmsAlarm alarm = m_alarmDao.get(vo.m_alarmId); OnmsAcknowledgment ack = new OnmsAcknowledgment(m_alarmDao.get(vo.m_alarmId)); m_ackDao.save(ack); m_ackDao.flush(); m_ackService.processAck(ack); alarm = m_alarmDao.get(ack.getRefId()); Assert.assertNotNull(alarm.getAlarmAckUser()); Assert.assertEquals("admin", alarm.getAlarmAckUser()); OnmsNotification notif = m_notificationDao.get(vo.m_notifId); Assert.assertNotNull(notif); Assert.assertEquals("admin", notif.getAnsweredBy()); Assert.assertEquals(alarm.getAlarmAckTime(), notif.getRespondTime()); } /** * This tests acknowledging a notification and a related alarm. If events are being deduplicated * they should all have the same alarm ID. */ @Transactional @Test public void testAcknowledgeNotification() { VerificationObject vo = createAckStructure(); Assert.assertTrue(vo.m_nodeId > 0); Assert.assertTrue(vo.m_alarmId > 0); Assert.assertTrue(vo.m_eventID > 0); Assert.assertTrue(vo.m_userNotifId > 0); OnmsAcknowledgment ack = new OnmsAcknowledgment(m_notificationDao.get(vo.m_notifId)); m_ackDao.save(ack); m_ackDao.flush(); m_ackService.processAck(ack); OnmsNotification notif = m_notificationDao.get(ack.getRefId()); Assert.assertNotNull(notif.getAnsweredBy()); Assert.assertEquals("admin", notif.getAnsweredBy()); OnmsAlarm alarm = m_alarmDao.get(vo.m_alarmId); Assert.assertNotNull(alarm); Assert.assertEquals("admin", alarm.getAlarmAckUser()); Assert.assertEquals(alarm.getAlarmAckTime(), notif.getRespondTime()); } @Transactional @Test public void testHandelEvent() throws InterruptedException { VerificationObject vo = createAckStructure(); EventBuilder bldr = new EventBuilder("uei.opennms.org/internal/ackd/Acknowledge", "AckdTest"); bldr.addParam("ackType", String.valueOf(AckType.ALARM)); bldr.addParam("refId", vo.m_alarmId); final String user = "ackd-test-user"; bldr.addParam("user", user); m_daemon.handleAckEvent(bldr.getEvent()); OnmsNotification notif = m_notificationDao.get(vo.m_notifId); Assert.assertEquals(notif.getAckUser(), user); // Assert.assertEquals(notif.getAckTime(), bldr.getEvent().getTime()); OnmsAlarm alarm = m_alarmDao.get(vo.m_alarmId); Assert.assertEquals(alarm.getAckUser(), user); // Assert.assertEquals(alarm.getAckTime(), bldr.getEvent().getTime()); } class VerificationObject { int m_eventID; int m_alarmId; int m_nodeId; int m_notifId; int m_userNotifId; } private VerificationObject createAckStructure() { final Date time = new Date(); VerificationObject vo = new VerificationObject(); List<OnmsNode> nodes = m_nodeDao.findAll(); Assert.assertTrue("List of nodes should not be empty", nodes.size() > 0); OnmsNode node = m_nodeDao.get(nodes.get(0).getId()); vo.m_nodeId = node.getId(); OnmsEvent event = new OnmsEvent(); event.setDistPoller(node.getDistPoller()); event.setNode(node); event.setEventCreateTime(time); event.setEventDescr("Test node down event."); event.setEventSeverity(6); event.setEventSource("AckdTest"); event.setEventTime(time); event.setEventUei(EventConstants.NODE_DOWN_EVENT_UEI); event.setIpAddr(node.getPrimaryInterface().getIpAddress()); event.setEventLog("Y"); event.setEventDisplay("Y"); event.setEventLogMsg("Testing node down event from AckdTest."); m_eventDao.save(event); vo.m_eventID = event.getId(); OnmsAlarm alarm = new OnmsAlarm(); alarm.setAlarmType(1); alarm.setClearKey("abc"); alarm.setClearUei(EventConstants.NODE_UP_EVENT_UEI); alarm.setCounter(1); alarm.setDescription(event.getEventDescr()); alarm.setDistPoller(event.getDistPoller()); alarm.setFirstEventTime(event.getEventTime()); alarm.setIpAddr(event.getIpAddr()); alarm.setLastEvent(event); alarm.setLastEventTime(event.getEventTime()); alarm.setLogMsg("Some Log Message"); alarm.setNode(event.getNode()); alarm.setReductionKey("xyz"); alarm.setServiceType(event.getServiceType()); alarm.setSeverity(OnmsSeverity.get(event.getEventSeverity())); alarm.setUei(event.getEventUei()); m_alarmDao.save(alarm); vo.m_alarmId = alarm.getId(); event.setAlarm(alarm); OnmsNotification notif = new OnmsNotification(); notif.setEvent(event); notif.setEventUei(event.getEventUei()); notif.setIpAddress(event.getIpAddr()); notif.setNode(event.getNode()); notif.setNotifConfigName("abc"); notif.setNumericMsg(event.getEventLogMsg()); notif.setPageTime(event.getEventTime()); notif.setServiceType(event.getServiceType()); notif.setSubject("notifyid: 1, node down"); notif.setTextMsg(event.getEventLogMsg()); m_notificationDao.save(notif); vo.m_notifId = notif.getNotifyId(); OnmsUserNotification userNotif = new OnmsUserNotification(); userNotif.setAutoNotify("Y"); userNotif.setContactInfo("[email protected]"); userNotif.setMedia("page"); userNotif.setNotification(notif); userNotif.setNotifyTime(event.getEventTime()); userNotif.setUserId("me"); Set<OnmsUserNotification> usersnotifieds = new HashSet<OnmsUserNotification>(); usersnotifieds.add(userNotif); m_userNotificationDao.save(userNotif); vo.m_userNotifId = userNotif.getId(); notif.setUsersNotified(usersnotifieds); m_notificationDao.update(notif); m_eventDao.update(event); m_eventDao.flush(); return vo; } }
matt suggested I just mark the whole class transactional instead, since setUp() basically means it's required anyways
opennms-ackd/src/test/java/org/opennms/netmgt/ackd/AckdTest.java
matt suggested I just mark the whole class transactional instead, since setUp() basically means it's required anyways
Java
lgpl-2.1
3d98570cd8c800d3d344b56a311dfe283879ce7c
0
zanata/zanata-platform,zanata/zanata-platform,zanata/zanata-platform,zanata/zanata-platform,zanata/zanata-platform,zanata/zanata-platform,zanata/zanata-platform
/* * Copyright 2015, Red Hat, Inc. and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * 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.zanata.dao; import java.util.Date; import java.util.List; import javax.annotation.Nonnull; import javax.annotation.Nullable; import org.apache.commons.lang.StringUtils; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.index.Term; import org.apache.lucene.queryparser.classic.MultiFieldQueryParser; import org.apache.lucene.queryparser.classic.ParseException; import org.apache.lucene.queryparser.classic.QueryParser; import org.apache.lucene.search.BooleanClause; import org.apache.lucene.search.BooleanQuery; import org.apache.lucene.search.TermQuery; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.search.jpa.FullTextEntityManager; import org.hibernate.search.jpa.FullTextQuery; import javax.enterprise.context.RequestScoped; import javax.inject.Inject; import org.zanata.common.EntityStatus; import org.zanata.hibernate.search.Analyzers; import org.zanata.hibernate.search.CaseInsensitiveWhitespaceAnalyzer; import org.zanata.hibernate.search.IndexFieldLabels; import org.zanata.jpa.FullText; import org.zanata.model.HAccount; import org.zanata.model.HPerson; import org.zanata.model.HProject; import org.zanata.model.HProjectIteration; import org.zanata.model.ProjectRole; @RequestScoped public class ProjectDAO extends AbstractDAOImpl<HProject, Long> { @Inject @FullText private FullTextEntityManager entityManager; public ProjectDAO() { super(HProject.class); } public ProjectDAO(Session session) { super(HProject.class, session); } public @Nullable HProject getBySlug(@Nonnull String slug) { if (!StringUtils.isEmpty(slug)) { return (HProject) getSession().byNaturalId(HProject.class) .using("slug", slug).load(); } return null; } @SuppressWarnings("unchecked") public List<HProject> getOffsetList(int offset, int count, boolean filterOutActive, boolean filterOutReadOnly, boolean filterOutObsolete) { String condition = constructFilterCondition(filterOutActive, filterOutReadOnly, filterOutObsolete); StringBuilder sb = new StringBuilder(); sb.append("from HProject p ") .append(condition) .append("order by UPPER(p.name) asc"); Query q = getSession().createQuery(sb.toString()); if (count > 0) { q.setMaxResults(count); } if (offset > 0) { q.setFirstResult(offset); } q.setCacheable(true) .setComment("ProjectDAO.getOffsetList"); return q.list(); } public int getFilterProjectSize(boolean filterOutActive, boolean filterOutReadOnly, boolean filterOutObsolete) { String condition = constructFilterCondition(filterOutActive, filterOutReadOnly, filterOutObsolete); String query = "select count(*) from HProject p " + condition; Query q = getSession().createQuery(query); q.setCacheable(true).setComment("ProjectDAO.getFilterProjectSize"); Long totalCount = (Long) q.uniqueResult(); if (totalCount == null) return 0; return totalCount.intValue(); } private String constructFilterCondition(boolean filterOutActive, boolean filterOutReadOnly, boolean filterOutObsolete) { StringBuilder condition = new StringBuilder(); if (filterOutActive || filterOutReadOnly || filterOutObsolete) { condition.append("where "); } if (filterOutActive) { // TODO bind this as a parameter condition.append("p.status <> '" + EntityStatus.ACTIVE.getInitial() + "' "); } if (filterOutReadOnly) { if (filterOutActive) { condition.append("and "); } // TODO bind this as a parameter condition.append("p.status <> '" + EntityStatus.READONLY.getInitial() + "' "); } if (filterOutObsolete) { if (filterOutActive || filterOutReadOnly) { condition.append("and "); } // TODO bind this as a parameter condition.append("p.status <> '" + EntityStatus.OBSOLETE.getInitial() + "' "); } return condition.toString(); } @SuppressWarnings("unchecked") public List<HProjectIteration> getAllIterations(String slug) { Query q = getSession() .createQuery( "from HProjectIteration t where t.project.slug = :projectSlug order by t.creationDate"); q.setParameter("projectSlug", slug); q.setCacheable(true).setComment("ProjectDAO.getAllIterations"); return q.list(); } @SuppressWarnings("unchecked") public List<HProjectIteration> getActiveIterations(String slug) { Query q = getSession() .createQuery( "from HProjectIteration t where t.project.slug = :projectSlug and t.status = :status"); q.setParameter("projectSlug", slug).setParameter("status", EntityStatus.ACTIVE); q.setCacheable(true).setComment("ProjectDAO.getActiveIterations"); return q.list(); } /** * @param projectId * project id * @return number of non-obsolete (active and read only) iterations under given project */ public int getTranslationCandidateCount(Long projectId) { Query q = getSession() .createQuery( "select count(*) from HProjectIteration it where it.project.id = :projectId and it.status <> :status") .setParameter("projectId", projectId) .setParameter("status", EntityStatus.OBSOLETE).setCacheable(true) .setComment("ProjectDAO.getTranslationCandidateCount"); return ((Long) q.uniqueResult()).intValue(); } @SuppressWarnings("unchecked") public List<HProjectIteration> getReadOnlyIterations(String slug) { Query q = getSession() .createQuery( "from HProjectIteration t where t.project.slug = :projectSlug and t.status = :status"); q.setParameter("projectSlug", slug).setParameter("status", EntityStatus.READONLY); q.setCacheable(true).setComment("ProjectDAO.getReadOnlyIterations"); return q.list(); } @SuppressWarnings("unchecked") public List<HProjectIteration> getObsoleteIterations(String slug) { Query q = getSession() .createQuery( "from HProjectIteration t where t.project.slug = :projectSlug and t.status = :status"); q.setParameter("projectSlug", slug).setParameter("status", EntityStatus.OBSOLETE); q.setCacheable(true).setComment("ProjectDAO.getObsoleteIterations"); return q.list(); } public int getTotalProjectCount() { String query = "select count(*) from HProject"; Query q = getSession().createQuery(query.toString()); q.setCacheable(true).setComment("ProjectDAO.getTotalProjectCount"); Long totalCount = (Long) q.uniqueResult(); if (totalCount == null) return 0; return totalCount.intValue(); } public int getTotalActiveProjectCount() { Query q = getSession() .createQuery( "select count(*) from HProject p where p.status = :status"); q.setParameter("status", EntityStatus.ACTIVE); q.setCacheable(true) .setComment("ProjectDAO.getTotalActiveProjectCount"); Long totalCount = (Long) q.uniqueResult(); if (totalCount == null) return 0; return totalCount.intValue(); } public int getTotalReadOnlyProjectCount() { Query q = getSession() .createQuery( "select count(*) from HProject p where p.status = :status"); q.setParameter("status", EntityStatus.READONLY); q.setCacheable(true).setComment( "ProjectDAO.getTotalReadOnlyProjectCount"); Long totalCount = (Long) q.uniqueResult(); if (totalCount == null) return 0; return totalCount.intValue(); } public int getTotalObsoleteProjectCount() { Query q = getSession() .createQuery( "select count(*) from HProject p where p.status = :status"); q.setParameter("status", EntityStatus.OBSOLETE); q.setCacheable(true).setComment( "ProjectDAO.getTotalObsoleteProjectCount"); Long totalCount = (Long) q.uniqueResult(); if (totalCount == null) return 0; return totalCount.intValue(); } public List<HProject> searchProjects(@Nonnull String searchQuery, int maxResult, int firstResult, boolean includeObsolete) throws ParseException { FullTextQuery query = buildSearchQuery(searchQuery, includeObsolete); if(maxResult > 0) { query.setMaxResults(maxResult); } return query.setFirstResult(firstResult) .getResultList(); } public int getQueryProjectSize(@Nonnull String searchQuery, boolean includeObsolete) throws ParseException { return searchProjects(searchQuery, -1, 0, includeObsolete).size(); } private FullTextQuery buildSearchQuery(@Nonnull String searchQuery, boolean includeObsolete) throws ParseException { String queryText = QueryParser.escape(searchQuery); Analyzer sourceAnalyzer = entityManager.getSearchFactory() .getAnalyzer(Analyzers.DEFAULT); MultiFieldQueryParser queryParser = new MultiFieldQueryParser( new String[]{ "slug", "name", "description" }, sourceAnalyzer); queryParser.setDefaultOperator(QueryParser.Operator.OR); BooleanQuery.Builder booleanQuery = new BooleanQuery.Builder(); booleanQuery.add(queryParser.parse(queryText), BooleanClause.Occur.SHOULD); if (!includeObsolete) { TermQuery obsoleteStateQuery = new TermQuery(new Term(IndexFieldLabels.ENTITY_STATUS, EntityStatus.OBSOLETE.toString().toLowerCase())); booleanQuery.add(obsoleteStateQuery, BooleanClause.Occur.MUST_NOT); } return entityManager.createFullTextQuery(booleanQuery.build(), HProject.class); } /** * Build BooleanQuery on single lucene field by splitting searchQuery with * white space. * * @param searchQuery * - query string, will replace hypen with space and escape * special char * @param field * - lucene field */ private BooleanQuery buildSearchFieldQuery(@Nonnull String searchQuery, @Nonnull String field) throws ParseException { BooleanQuery query = new BooleanQuery(); //escape special character search searchQuery = QueryParser.escape(searchQuery); for(String searchString: searchQuery.split("\\s+")) { QueryParser parser = new QueryParser(field, new CaseInsensitiveWhitespaceAnalyzer()); query.add(parser.parse(searchString + "*"), BooleanClause.Occur.MUST); } return query; } public List<HProject> findAllTranslatedProjects(HAccount account, int maxResults) { Query q = getSession() .createQuery( "select distinct tft.textFlow.document.projectIteration.project " + "from HTextFlowTarget tft " + "where tft.translator = :translator") .setParameter("translator", account) .setMaxResults(maxResults); return q.list(); } public int getTranslatedProjectCount(HAccount account) { Query q = getSession() .createQuery( "select count(distinct tft.textFlow.document.projectIteration.project) " + "from HTextFlowTarget tft " + "where tft.translator = :translator" ) .setParameter("translator", account); return ((Long) q.uniqueResult()).intValue(); } /** * @param project A project * @param account The user for which the last translated date. * @return A date indicating the last time on which account's user * translated project. */ public Date getLastTranslatedDate(HProject project, HAccount account) { Query q = getSession() .createQuery( "select max (tft.lastChanged) " + "from HTextFlowTarget tft " + "where tft.translator = :translator " + "and tft.textFlow.document.projectIteration.project = :project" ) .setParameter("translator", account) .setParameter("project", project) .setCacheable(true); return (Date) q.uniqueResult(); } /** * @param project A project * @return A date indicating the last time when any user translated project */ public Date getLastTranslatedDate(HProject project) { Query q = getSession() .createQuery( "select max (tft.lastChanged) " + "from HTextFlowTarget tft " + "where tft.textFlow.document.projectIteration.project = :project" ) .setParameter("project", project) .setCacheable(true); return (Date) q.uniqueResult(); } /** * @param project A project * @return A date indicating the last time when any user translated project */ public HPerson getLastTranslator(HProject project) { Query q = getSession() .createQuery( "select tft.translator " + "from HTextFlowTarget tft " + "where tft.textFlow.document.projectIteration.project = :project " + "order by tft.lastChanged desc" ) .setParameter("project", project) .setMaxResults(1) .setCacheable(true); List results = q.list(); if (results.isEmpty()) { return null; } else { return (HPerson) results.get(0); } } public List<HProject> getProjectsForMaintainer(HPerson maintainer, String filter, int firstResult, int maxResults) { final String sqlFilter = filter == null ? "" : filter.toLowerCase(); Query q = getSession().createQuery( "select m.project from HProjectMember m " + "where m.person = :maintainer " + "and m.role = :role " + "and m.project.status <> :obsolete " + "and (lower(m.project.name) like :filter " + "or lower(m.project.slug) like :filter) " + "order by m.project.name") .setParameter("maintainer", maintainer) .setParameter("role", ProjectRole.Maintainer) .setParameter("obsolete", EntityStatus.OBSOLETE) .setParameter("filter", "%" + sqlFilter + "%") .setFirstResult(firstResult) .setMaxResults(maxResults); return q.list(); } public int getMaintainedProjectCount(HPerson maintainer, String filter) { final String sqlFilter = filter == null ? "" : filter.toLowerCase(); Query q = getSession().createQuery( "select count(m) from HProjectMember m " + "where m.person = :maintainer " + "and m.role = :role " + "and m.project.status <> :obsolete " + "and (lower(m.project.name) like :filter " + "or lower(m.project.slug) like :filter)") .setParameter("maintainer", maintainer) .setParameter("role", ProjectRole.Maintainer) .setParameter("obsolete", EntityStatus.OBSOLETE) .setParameter("filter", "%" + sqlFilter + "%"); return ((Long) q.uniqueResult()).intValue(); } }
server/zanata-war/src/main/java/org/zanata/dao/ProjectDAO.java
/* * Copyright 2015, Red Hat, Inc. and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * 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.zanata.dao; import java.util.Date; import java.util.List; import javax.annotation.Nonnull; import javax.annotation.Nullable; import org.apache.commons.lang.StringUtils; import org.apache.lucene.index.Term; import org.apache.lucene.queryparser.classic.ParseException; import org.apache.lucene.queryparser.classic.QueryParser; import org.apache.lucene.search.BooleanClause; import org.apache.lucene.search.BooleanQuery; import org.apache.lucene.search.TermQuery; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.search.jpa.FullTextEntityManager; import org.hibernate.search.jpa.FullTextQuery; import javax.enterprise.context.RequestScoped; import javax.inject.Inject; import org.zanata.common.EntityStatus; import org.zanata.hibernate.search.CaseInsensitiveWhitespaceAnalyzer; import org.zanata.hibernate.search.IndexFieldLabels; import org.zanata.jpa.FullText; import org.zanata.model.HAccount; import org.zanata.model.HPerson; import org.zanata.model.HProject; import org.zanata.model.HProjectIteration; import org.zanata.model.ProjectRole; @RequestScoped public class ProjectDAO extends AbstractDAOImpl<HProject, Long> { @Inject @FullText private FullTextEntityManager entityManager; public ProjectDAO() { super(HProject.class); } public ProjectDAO(Session session) { super(HProject.class, session); } public @Nullable HProject getBySlug(@Nonnull String slug) { if (!StringUtils.isEmpty(slug)) { return (HProject) getSession().byNaturalId(HProject.class) .using("slug", slug).load(); } return null; } @SuppressWarnings("unchecked") public List<HProject> getOffsetList(int offset, int count, boolean filterOutActive, boolean filterOutReadOnly, boolean filterOutObsolete) { String condition = constructFilterCondition(filterOutActive, filterOutReadOnly, filterOutObsolete); StringBuilder sb = new StringBuilder(); sb.append("from HProject p ") .append(condition) .append("order by UPPER(p.name) asc"); Query q = getSession().createQuery(sb.toString()); if (count > 0) { q.setMaxResults(count); } if (offset > 0) { q.setFirstResult(offset); } q.setCacheable(true) .setComment("ProjectDAO.getOffsetList"); return q.list(); } public int getFilterProjectSize(boolean filterOutActive, boolean filterOutReadOnly, boolean filterOutObsolete) { String condition = constructFilterCondition(filterOutActive, filterOutReadOnly, filterOutObsolete); String query = "select count(*) from HProject p " + condition; Query q = getSession().createQuery(query); q.setCacheable(true).setComment("ProjectDAO.getFilterProjectSize"); Long totalCount = (Long) q.uniqueResult(); if (totalCount == null) return 0; return totalCount.intValue(); } private String constructFilterCondition(boolean filterOutActive, boolean filterOutReadOnly, boolean filterOutObsolete) { StringBuilder condition = new StringBuilder(); if (filterOutActive || filterOutReadOnly || filterOutObsolete) { condition.append("where "); } if (filterOutActive) { // TODO bind this as a parameter condition.append("p.status <> '" + EntityStatus.ACTIVE.getInitial() + "' "); } if (filterOutReadOnly) { if (filterOutActive) { condition.append("and "); } // TODO bind this as a parameter condition.append("p.status <> '" + EntityStatus.READONLY.getInitial() + "' "); } if (filterOutObsolete) { if (filterOutActive || filterOutReadOnly) { condition.append("and "); } // TODO bind this as a parameter condition.append("p.status <> '" + EntityStatus.OBSOLETE.getInitial() + "' "); } return condition.toString(); } @SuppressWarnings("unchecked") public List<HProjectIteration> getAllIterations(String slug) { Query q = getSession() .createQuery( "from HProjectIteration t where t.project.slug = :projectSlug order by t.creationDate"); q.setParameter("projectSlug", slug); q.setCacheable(true).setComment("ProjectDAO.getAllIterations"); return q.list(); } @SuppressWarnings("unchecked") public List<HProjectIteration> getActiveIterations(String slug) { Query q = getSession() .createQuery( "from HProjectIteration t where t.project.slug = :projectSlug and t.status = :status"); q.setParameter("projectSlug", slug).setParameter("status", EntityStatus.ACTIVE); q.setCacheable(true).setComment("ProjectDAO.getActiveIterations"); return q.list(); } /** * @param projectId * project id * @return number of non-obsolete (active and read only) iterations under given project */ public int getTranslationCandidateCount(Long projectId) { Query q = getSession() .createQuery( "select count(*) from HProjectIteration it where it.project.id = :projectId and it.status <> :status") .setParameter("projectId", projectId) .setParameter("status", EntityStatus.OBSOLETE).setCacheable(true) .setComment("ProjectDAO.getTranslationCandidateCount"); return ((Long) q.uniqueResult()).intValue(); } @SuppressWarnings("unchecked") public List<HProjectIteration> getReadOnlyIterations(String slug) { Query q = getSession() .createQuery( "from HProjectIteration t where t.project.slug = :projectSlug and t.status = :status"); q.setParameter("projectSlug", slug).setParameter("status", EntityStatus.READONLY); q.setCacheable(true).setComment("ProjectDAO.getReadOnlyIterations"); return q.list(); } @SuppressWarnings("unchecked") public List<HProjectIteration> getObsoleteIterations(String slug) { Query q = getSession() .createQuery( "from HProjectIteration t where t.project.slug = :projectSlug and t.status = :status"); q.setParameter("projectSlug", slug).setParameter("status", EntityStatus.OBSOLETE); q.setCacheable(true).setComment("ProjectDAO.getObsoleteIterations"); return q.list(); } public int getTotalProjectCount() { String query = "select count(*) from HProject"; Query q = getSession().createQuery(query.toString()); q.setCacheable(true).setComment("ProjectDAO.getTotalProjectCount"); Long totalCount = (Long) q.uniqueResult(); if (totalCount == null) return 0; return totalCount.intValue(); } public int getTotalActiveProjectCount() { Query q = getSession() .createQuery( "select count(*) from HProject p where p.status = :status"); q.setParameter("status", EntityStatus.ACTIVE); q.setCacheable(true) .setComment("ProjectDAO.getTotalActiveProjectCount"); Long totalCount = (Long) q.uniqueResult(); if (totalCount == null) return 0; return totalCount.intValue(); } public int getTotalReadOnlyProjectCount() { Query q = getSession() .createQuery( "select count(*) from HProject p where p.status = :status"); q.setParameter("status", EntityStatus.READONLY); q.setCacheable(true).setComment( "ProjectDAO.getTotalReadOnlyProjectCount"); Long totalCount = (Long) q.uniqueResult(); if (totalCount == null) return 0; return totalCount.intValue(); } public int getTotalObsoleteProjectCount() { Query q = getSession() .createQuery( "select count(*) from HProject p where p.status = :status"); q.setParameter("status", EntityStatus.OBSOLETE); q.setCacheable(true).setComment( "ProjectDAO.getTotalObsoleteProjectCount"); Long totalCount = (Long) q.uniqueResult(); if (totalCount == null) return 0; return totalCount.intValue(); } public List<HProject> searchProjects(@Nonnull String searchQuery, int maxResult, int firstResult, boolean includeObsolete) throws ParseException { FullTextQuery query = buildSearchQuery(searchQuery, includeObsolete); if(maxResult > 0) { query.setMaxResults(maxResult); } return query.setFirstResult(firstResult) .getResultList(); } public int getQueryProjectSize(@Nonnull String searchQuery, boolean includeObsolete) throws ParseException { return searchProjects(searchQuery, -1, 0, includeObsolete).size(); } private FullTextQuery buildSearchQuery(@Nonnull String searchQuery, boolean includeObsolete) throws ParseException { String queryText = QueryParser.escape(searchQuery); BooleanQuery booleanQuery = new BooleanQuery(); booleanQuery.add(buildSearchFieldQuery(queryText, "slug"), BooleanClause.Occur.SHOULD); booleanQuery.add(buildSearchFieldQuery(queryText, "name"), BooleanClause.Occur.SHOULD); booleanQuery.add(buildSearchFieldQuery(queryText, "description"), BooleanClause.Occur.SHOULD); if (!includeObsolete) { TermQuery obsoleteStateQuery = new TermQuery(new Term(IndexFieldLabels.ENTITY_STATUS, EntityStatus.OBSOLETE.toString().toLowerCase())); booleanQuery.add(obsoleteStateQuery, BooleanClause.Occur.MUST_NOT); } return entityManager.createFullTextQuery(booleanQuery, HProject.class); } /** * Build BooleanQuery on single lucene field by splitting searchQuery with * white space. * * @param searchQuery * - query string, will replace hypen with space and escape * special char * @param field * - lucene field */ private BooleanQuery buildSearchFieldQuery(@Nonnull String searchQuery, @Nonnull String field) throws ParseException { BooleanQuery query = new BooleanQuery(); //escape special character search searchQuery = QueryParser.escape(searchQuery); for(String searchString: searchQuery.split("\\s+")) { QueryParser parser = new QueryParser(field, new CaseInsensitiveWhitespaceAnalyzer()); query.add(parser.parse(searchString + "*"), BooleanClause.Occur.MUST); } return query; } public List<HProject> findAllTranslatedProjects(HAccount account, int maxResults) { Query q = getSession() .createQuery( "select distinct tft.textFlow.document.projectIteration.project " + "from HTextFlowTarget tft " + "where tft.translator = :translator") .setParameter("translator", account) .setMaxResults(maxResults); return q.list(); } public int getTranslatedProjectCount(HAccount account) { Query q = getSession() .createQuery( "select count(distinct tft.textFlow.document.projectIteration.project) " + "from HTextFlowTarget tft " + "where tft.translator = :translator" ) .setParameter("translator", account); return ((Long) q.uniqueResult()).intValue(); } /** * @param project A project * @param account The user for which the last translated date. * @return A date indicating the last time on which account's user * translated project. */ public Date getLastTranslatedDate(HProject project, HAccount account) { Query q = getSession() .createQuery( "select max (tft.lastChanged) " + "from HTextFlowTarget tft " + "where tft.translator = :translator " + "and tft.textFlow.document.projectIteration.project = :project" ) .setParameter("translator", account) .setParameter("project", project) .setCacheable(true); return (Date) q.uniqueResult(); } /** * @param project A project * @return A date indicating the last time when any user translated project */ public Date getLastTranslatedDate(HProject project) { Query q = getSession() .createQuery( "select max (tft.lastChanged) " + "from HTextFlowTarget tft " + "where tft.textFlow.document.projectIteration.project = :project" ) .setParameter("project", project) .setCacheable(true); return (Date) q.uniqueResult(); } /** * @param project A project * @return A date indicating the last time when any user translated project */ public HPerson getLastTranslator(HProject project) { Query q = getSession() .createQuery( "select tft.translator " + "from HTextFlowTarget tft " + "where tft.textFlow.document.projectIteration.project = :project " + "order by tft.lastChanged desc" ) .setParameter("project", project) .setMaxResults(1) .setCacheable(true); List results = q.list(); if (results.isEmpty()) { return null; } else { return (HPerson) results.get(0); } } public List<HProject> getProjectsForMaintainer(HPerson maintainer, String filter, int firstResult, int maxResults) { final String sqlFilter = filter == null ? "" : filter.toLowerCase(); Query q = getSession().createQuery( "select m.project from HProjectMember m " + "where m.person = :maintainer " + "and m.role = :role " + "and m.project.status <> :obsolete " + "and (lower(m.project.name) like :filter " + "or lower(m.project.slug) like :filter) " + "order by m.project.name") .setParameter("maintainer", maintainer) .setParameter("role", ProjectRole.Maintainer) .setParameter("obsolete", EntityStatus.OBSOLETE) .setParameter("filter", "%" + sqlFilter + "%") .setFirstResult(firstResult) .setMaxResults(maxResults); return q.list(); } public int getMaintainedProjectCount(HPerson maintainer, String filter) { final String sqlFilter = filter == null ? "" : filter.toLowerCase(); Query q = getSession().createQuery( "select count(m) from HProjectMember m " + "where m.person = :maintainer " + "and m.role = :role " + "and m.project.status <> :obsolete " + "and (lower(m.project.name) like :filter " + "or lower(m.project.slug) like :filter)") .setParameter("maintainer", maintainer) .setParameter("role", ProjectRole.Maintainer) .setParameter("obsolete", EntityStatus.OBSOLETE) .setParameter("filter", "%" + sqlFilter + "%"); return ((Long) q.uniqueResult()).intValue(); } }
ZNTA-2056 use same analyzer to parse search query
server/zanata-war/src/main/java/org/zanata/dao/ProjectDAO.java
ZNTA-2056 use same analyzer to parse search query
Java
apache-2.0
b98a6caa705f502f593f2813f07bb9395dd4cd64
0
ksfzhaohui/spring-loaded,spring-projects/spring-loaded,witekcc/spring-loaded,ksfzhaohui/spring-loaded,witekcc/spring-loaded,drunklite/spring-loaded,spring-projects/spring-loaded,drunklite/spring-loaded
/* * Copyright 2010-2012 VMware and contributors * * 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.springsource.loaded.agent; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.security.ProtectionDomain; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import org.objectweb.asm.ClassReader; import org.springsource.loaded.GlobalConfiguration; import org.springsource.loaded.LoadtimeInstrumentationPlugin; import org.springsource.loaded.ReloadEventProcessorPlugin; /** * First stab at the Spring plugin for Spring-Loaded. Notes...<br> * <ul> * <li>On reload, removes the Class entry in * org/springframework/web/servlet/mvc/annotation/AnnotationMethodHandlerAdapter.methodResolverCache. This enables us to add/changes * request mappings in controllers. * <li>That was for Roo, if we create a simple spring template project and run it, this doesn't work. It seems we need to redrive * detectHandlers() on the DefaultAnnotationHandlerMapping type which will rediscover the URL mappings and add them into the handler * list. We don't clear old ones out (yet) but the old mappings appear not to work anyway. * </ul> * * @author Andy Clement * @since 0.5.0 */ public class SpringPlugin implements LoadtimeInstrumentationPlugin, ReloadEventProcessorPlugin { private static final String THIS_CLASS = "org/springsource/loaded/agent/SpringPlugin"; private static Logger log = Logger.getLogger(SpringPlugin.class.getName()); private static boolean debug = true; // TODO [gc] what about GC here - how do we know when they are finished with? public static List<Object> instancesOf_AnnotationMethodHandlerAdapter = new ArrayList<Object>(); public static List<Object> instancesOf_DefaultAnnotationHandlerMapping = new ArrayList<Object>(); public static List<Object> instancesOf_RequestMappingHandlerMapping = new ArrayList<Object>(); public static List<Object> instancesOf_LocalVariableTableParameterNameDiscoverer = null; ClassLoader springLoader = null; public static boolean support305 = true; private Field classCacheField; private Field strongClassCacheField; private Field softClassCacheField; private Field field_parameterNamesCache; // From LocalVariableTableParameterNameDiscoverer private boolean cachedIntrospectionResultsClassLoaded = false; private Class<?> cachedIntrospectionResultsClass = null; public boolean accept(String slashedTypeName, ClassLoader classLoader, ProtectionDomain protectionDomain, byte[] bytes) { // TODO take classloader into account? if (slashedTypeName == null) { return false; } if (slashedTypeName.equals("org/springframework/core/LocalVariableTableParameterNameDiscoverer")) { return true; } // Just interested in whether this type got loaded if (slashedTypeName.equals("org/springframework/beans/CachedIntrospectionResults")) { cachedIntrospectionResultsClassLoaded = true; } return slashedTypeName.equals("org/springframework/web/servlet/mvc/annotation/AnnotationMethodHandlerAdapter") || slashedTypeName.equals("org/springframework/web/servlet/mvc/method/annotation/RequestMappingHandlerMapping") || // 3.1 (support305 && slashedTypeName .equals("org/springframework/web/servlet/mvc/annotation/DefaultAnnotationHandlerMapping")); } public byte[] modify(String slashedClassName, ClassLoader classLoader, byte[] bytes) { if (GlobalConfiguration.isRuntimeLogging && log.isLoggable(Level.INFO)) { log.info("loadtime modifying " + slashedClassName); } if (slashedClassName.equals("org/springframework/web/servlet/mvc/annotation/AnnotationMethodHandlerAdapter")) { return bytesWithInstanceCreationCaptured(bytes, THIS_CLASS, "recordAnnotationMethodHandlerAdapterInstance"); } else if (slashedClassName.equals("org/springframework/web/servlet/mvc/method/annotation/RequestMappingHandlerMapping")) { // springmvc spring 3.1 - doesnt work on 3.1 post M2 snapshots return bytesWithInstanceCreationCaptured(bytes, THIS_CLASS, "recordRequestMappingHandlerMappingInstance"); } else if (slashedClassName.equals("org/springframework/core/LocalVariableTableParameterNameDiscoverer")) { return bytesWithInstanceCreationCaptured(bytes, THIS_CLASS,"recordLocalVariableTableParameterNameDiscoverer"); } else { // "org/springframework/web/servlet/mvc/annotation/DefaultAnnotationHandlerMapping" // springmvc spring 3.0 return bytesWithInstanceCreationCaptured(bytes, THIS_CLASS, "recordDefaultAnnotationHandlerMappingInstance"); } } // called by the modified code public static void recordAnnotationMethodHandlerAdapterInstance(Object obj) { instancesOf_AnnotationMethodHandlerAdapter.add(obj); } public static void recordRequestMappingHandlerMappingInstance(Object obj) { instancesOf_RequestMappingHandlerMapping.add(obj); } public static void recordLocalVariableTableParameterNameDiscoverer(Object obj) { if (instancesOf_LocalVariableTableParameterNameDiscoverer == null) { instancesOf_LocalVariableTableParameterNameDiscoverer = new ArrayList<Object>(); } instancesOf_LocalVariableTableParameterNameDiscoverer.add(obj); } static { try { String debugString = System.getProperty("springloaded.plugins.spring.debug","false"); debug = Boolean.valueOf(debugString); } catch (Exception e) { // likely security exception } } // called by the modified code public static void recordDefaultAnnotationHandlerMappingInstance(Object obj) { if (debug) { System.out.println("Recording new instance of DefaultAnnotationHandlerMappingInstance"); } instancesOf_DefaultAnnotationHandlerMapping.add(obj); } public void reloadEvent(String typename, Class<?> clazz, String versionsuffix) { removeClazzFromMethodResolverCache(clazz); clearCachedIntrospectionResults(clazz); reinvokeDetectHandlers(); // Spring 3.0 reinvokeInitHandlerMethods(); // Spring 3.1 clearLocalVariableTableParameterNameDiscovererCache(clazz); } /** * The Spring class LocalVariableTableParameterNameDiscoverer holds a cache of parameter names discovered for members within * classes and needs clearing if the class changes. * @param clazz the class being reloaded, which may exist in a parameter name discoverer cache */ private void clearLocalVariableTableParameterNameDiscovererCache(Class<?> clazz) { if (instancesOf_LocalVariableTableParameterNameDiscoverer == null) { return; } if (debug) { System.out.println("ParameterNamesCache: Clearing parameter name discoverer caches"); } if (field_parameterNamesCache == null) { try { field_parameterNamesCache = instancesOf_LocalVariableTableParameterNameDiscoverer.get(0).getClass().getDeclaredField("parameterNamesCache"); } catch (NoSuchFieldException nsfe) { log.log(Level.SEVERE, "Unexpectedly cannot find parameterNamesCache field on LocalVariableTableParameterNameDiscoverer class"); } } for (Object instance: instancesOf_LocalVariableTableParameterNameDiscoverer) { field_parameterNamesCache.setAccessible(true); try { Map<?,?> parameterNamesCache = (Map<?,?>)field_parameterNamesCache.get(instance); Object o = parameterNamesCache.remove(clazz); if (debug) { System.out.println("ParameterNamesCache: Removed "+clazz.getName()+" from cache?"+(o!=null)); } } catch (IllegalAccessException e) { log.log(Level.SEVERE, "Unexpected IllegalAccessException trying to access parameterNamesCache field on LocalVariableTableParameterNameDiscoverer class"); } } } private void removeClazzFromMethodResolverCache(Class<?> clazz) { for (Object o : instancesOf_AnnotationMethodHandlerAdapter) { try { Field f = o.getClass().getDeclaredField("methodResolverCache"); f.setAccessible(true); Map<?, ?> map = (Map<?, ?>) f.get(o); Method removeMethod = Map.class.getDeclaredMethod("remove", Object.class); Object ret = removeMethod.invoke(map, clazz); if (GlobalConfiguration.debugplugins) { System.err.println("SpringPlugin: clearing methodResolverCache for " + clazz.getName()); } if (GlobalConfiguration.isRuntimeLogging && log.isLoggable(Level.INFO)) { log.info("cleared a cache entry? " + (ret != null)); } } catch (Exception e) { log.log(Level.SEVERE, "Unexpected problem accessing methodResolverCache on " + o, e); } } } private void clearCachedIntrospectionResults(Class<?> clazz) { if (cachedIntrospectionResultsClassLoaded) { try { // TODO not a fan of classloading like this if (cachedIntrospectionResultsClass == null) { // TODO what about two apps using reloading and diff versions of spring? cachedIntrospectionResultsClass = clazz.getClassLoader().loadClass( "org.springframework.beans.CachedIntrospectionResults"); } if (classCacheField == null && strongClassCacheField == null) { try { classCacheField = cachedIntrospectionResultsClass.getDeclaredField("classCache"); } catch(NoSuchFieldException e) { strongClassCacheField = cachedIntrospectionResultsClass.getDeclaredField("strongClassCache"); softClassCacheField = cachedIntrospectionResultsClass.getDeclaredField("softClassCache"); } } if(classCacheField != null) { classCacheField.setAccessible(true); Map m = (Map) classCacheField.get(null); Object o = m.remove(clazz); if (GlobalConfiguration.debugplugins) { System.err.println("SpringPlugin: clearing CachedIntrospectionResults.classCache for " + clazz.getName() + " removed=" + o); } } if(strongClassCacheField != null) { strongClassCacheField.setAccessible(true); Map m = (Map) strongClassCacheField.get(null); Object o = m.remove(clazz); if (GlobalConfiguration.debugplugins) { System.err.println("SpringPlugin: clearing CachedIntrospectionResults.strongClassCache for " + clazz.getName() + " removed=" + o); } } if(softClassCacheField != null) { softClassCacheField.setAccessible(true); Map m = (Map) softClassCacheField.get(null); Object o = m.remove(clazz); if (GlobalConfiguration.debugplugins) { System.err.println("SpringPlugin: clearing CachedIntrospectionResults.softClassCache for " + clazz.getName() + " removed=" + o); } } } catch (Exception e) { if (GlobalConfiguration.debugplugins) { e.printStackTrace(); } } } } private void reinvokeDetectHandlers() { // want to call detectHandlers on the DefaultAnnotationHandlerMapping type // protected void detectHandlers() throws BeansException { is defined on AbstractDetectingUrlHandlerMapping for (Object o : instancesOf_DefaultAnnotationHandlerMapping) { if (debug) { System.out.println("Invoking detectHandlers on instance of DefaultAnnotationHandlerMappingInstance"); } try { Class<?> clazz_AbstractDetectingUrlHandlerMapping = o.getClass().getSuperclass(); Method method_detectHandlers = clazz_AbstractDetectingUrlHandlerMapping.getDeclaredMethod("detectHandlers"); method_detectHandlers.setAccessible(true); method_detectHandlers.invoke(o); } catch (Exception e) { // if debugging then print it if (GlobalConfiguration.debugplugins) { e.printStackTrace(); } } } } @SuppressWarnings("rawtypes") private void reinvokeInitHandlerMethods() { // org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping (super AbstractHandlerMethodMapping) - call protected void initHandlerMethods() on it. for (Object o : instancesOf_RequestMappingHandlerMapping) { if (debug) { System.out.println("Invoking initHandlerMethods on instance of RequestMappingHandlerMapping"); } try { Class<?> clazz_AbstractHandlerMethodMapping = o.getClass().getSuperclass().getSuperclass(); // private final Map<T, HandlerMethod> handlerMethods = new LinkedHashMap<T, HandlerMethod>(); Field field_handlerMethods = clazz_AbstractHandlerMethodMapping.getDeclaredField("handlerMethods"); field_handlerMethods.setAccessible(true); Map m = (Map) field_handlerMethods.get(o); m.clear(); Field field_urlMap = clazz_AbstractHandlerMethodMapping.getDeclaredField("urlMap"); field_urlMap.setAccessible(true); m = (Map) field_urlMap.get(o); m.clear(); Method method_initHandlerMethods = clazz_AbstractHandlerMethodMapping.getDeclaredMethod("initHandlerMethods"); method_initHandlerMethods.setAccessible(true); method_initHandlerMethods.invoke(o); } catch (NoSuchFieldException nsfe) { if (debug) { if (nsfe.getMessage().equals("handlerMethods")) { System.out.println("problem resetting request mapping handlers - unable to find field 'handlerMethods' on type 'AbstractHandlerMethodMapping' - you probably are not on Spring 3.1"); } else { System.out.println("problem resetting request mapping handlers - NoSuchFieldException: "+nsfe.getMessage()); } } } catch (Exception e) { if (GlobalConfiguration.debugplugins) { e.printStackTrace(); } } } } public boolean shouldRerunStaticInitializer(String typename, Class<?> clazz, String encodedTimestamp) { return false; } /** * Modify the supplied bytes such that constructors are intercepted and will invoke the specified class/method so that the * instances can be tracked. * * @return modified bytes for the class */ private byte[] bytesWithInstanceCreationCaptured(byte[] bytes, String classToCall, String methodToCall) { ClassReader cr = new ClassReader(bytes); ClassVisitingConstructorAppender ca = new ClassVisitingConstructorAppender(classToCall, methodToCall); cr.accept(ca, 0); byte[] newbytes = ca.getBytes(); return newbytes; } }
springloaded/src/main/java/org/springsource/loaded/agent/SpringPlugin.java
/* * Copyright 2010-2012 VMware and contributors * * 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.springsource.loaded.agent; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.security.ProtectionDomain; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import org.objectweb.asm.ClassReader; import org.springsource.loaded.GlobalConfiguration; import org.springsource.loaded.LoadtimeInstrumentationPlugin; import org.springsource.loaded.ReloadEventProcessorPlugin; /** * First stab at the Spring plugin for Spring-Loaded. Notes...<br> * <ul> * <li>On reload, removes the Class entry in * org/springframework/web/servlet/mvc/annotation/AnnotationMethodHandlerAdapter.methodResolverCache. This enables us to add/changes * request mappings in controllers. * <li>That was for Roo, if we create a simple spring template project and run it, this doesn't work. It seems we need to redrive * detectHandlers() on the DefaultAnnotationHandlerMapping type which will rediscover the URL mappings and add them into the handler * list. We don't clear old ones out (yet) but the old mappings appear not to work anyway. * </ul> * * @author Andy Clement * @since 0.5.0 */ public class SpringPlugin implements LoadtimeInstrumentationPlugin, ReloadEventProcessorPlugin { private static final String THIS_CLASS = "org/springsource/loaded/agent/SpringPlugin"; private static Logger log = Logger.getLogger(SpringPlugin.class.getName()); private static boolean debug = true; // TODO [gc] what about GC here - how do we know when they are finished with? public static List<Object> instancesOf_AnnotationMethodHandlerAdapter = new ArrayList<Object>(); public static List<Object> instancesOf_DefaultAnnotationHandlerMapping = new ArrayList<Object>(); public static List<Object> instancesOf_RequestMappingHandlerMapping = new ArrayList<Object>(); public static List<Object> instancesOf_LocalVariableTableParameterNameDiscoverer = null; ClassLoader springLoader = null; public static boolean support305 = true; private Field classCacheField; private Field field_parameterNamesCache; // From LocalVariableTableParameterNameDiscoverer private boolean cachedIntrospectionResultsClassLoaded = false; private Class<?> cachedIntrospectionResultsClass = null; public boolean accept(String slashedTypeName, ClassLoader classLoader, ProtectionDomain protectionDomain, byte[] bytes) { // TODO take classloader into account? if (slashedTypeName == null) { return false; } if (slashedTypeName.equals("org/springframework/core/LocalVariableTableParameterNameDiscoverer")) { return true; } // Just interested in whether this type got loaded if (slashedTypeName.equals("org/springframework/beans/CachedIntrospectionResults")) { cachedIntrospectionResultsClassLoaded = true; } return slashedTypeName.equals("org/springframework/web/servlet/mvc/annotation/AnnotationMethodHandlerAdapter") || slashedTypeName.equals("org/springframework/web/servlet/mvc/method/annotation/RequestMappingHandlerMapping") || // 3.1 (support305 && slashedTypeName .equals("org/springframework/web/servlet/mvc/annotation/DefaultAnnotationHandlerMapping")); } public byte[] modify(String slashedClassName, ClassLoader classLoader, byte[] bytes) { if (GlobalConfiguration.isRuntimeLogging && log.isLoggable(Level.INFO)) { log.info("loadtime modifying " + slashedClassName); } if (slashedClassName.equals("org/springframework/web/servlet/mvc/annotation/AnnotationMethodHandlerAdapter")) { return bytesWithInstanceCreationCaptured(bytes, THIS_CLASS, "recordAnnotationMethodHandlerAdapterInstance"); } else if (slashedClassName.equals("org/springframework/web/servlet/mvc/method/annotation/RequestMappingHandlerMapping")) { // springmvc spring 3.1 - doesnt work on 3.1 post M2 snapshots return bytesWithInstanceCreationCaptured(bytes, THIS_CLASS, "recordRequestMappingHandlerMappingInstance"); } else if (slashedClassName.equals("org/springframework/core/LocalVariableTableParameterNameDiscoverer")) { return bytesWithInstanceCreationCaptured(bytes, THIS_CLASS,"recordLocalVariableTableParameterNameDiscoverer"); } else { // "org/springframework/web/servlet/mvc/annotation/DefaultAnnotationHandlerMapping" // springmvc spring 3.0 return bytesWithInstanceCreationCaptured(bytes, THIS_CLASS, "recordDefaultAnnotationHandlerMappingInstance"); } } // called by the modified code public static void recordAnnotationMethodHandlerAdapterInstance(Object obj) { instancesOf_AnnotationMethodHandlerAdapter.add(obj); } public static void recordRequestMappingHandlerMappingInstance(Object obj) { instancesOf_RequestMappingHandlerMapping.add(obj); } public static void recordLocalVariableTableParameterNameDiscoverer(Object obj) { if (instancesOf_LocalVariableTableParameterNameDiscoverer == null) { instancesOf_LocalVariableTableParameterNameDiscoverer = new ArrayList<Object>(); } instancesOf_LocalVariableTableParameterNameDiscoverer.add(obj); } static { try { String debugString = System.getProperty("springloaded.plugins.spring.debug","false"); debug = Boolean.valueOf(debugString); } catch (Exception e) { // likely security exception } } // called by the modified code public static void recordDefaultAnnotationHandlerMappingInstance(Object obj) { if (debug) { System.out.println("Recording new instance of DefaultAnnotationHandlerMappingInstance"); } instancesOf_DefaultAnnotationHandlerMapping.add(obj); } public void reloadEvent(String typename, Class<?> clazz, String versionsuffix) { removeClazzFromMethodResolverCache(clazz); clearCachedIntrospectionResults(clazz); reinvokeDetectHandlers(); // Spring 3.0 reinvokeInitHandlerMethods(); // Spring 3.1 clearLocalVariableTableParameterNameDiscovererCache(clazz); } /** * The Spring class LocalVariableTableParameterNameDiscoverer holds a cache of parameter names discovered for members within * classes and needs clearing if the class changes. * @param clazz the class being reloaded, which may exist in a parameter name discoverer cache */ private void clearLocalVariableTableParameterNameDiscovererCache(Class<?> clazz) { if (instancesOf_LocalVariableTableParameterNameDiscoverer == null) { return; } if (debug) { System.out.println("ParameterNamesCache: Clearing parameter name discoverer caches"); } if (field_parameterNamesCache == null) { try { field_parameterNamesCache = instancesOf_LocalVariableTableParameterNameDiscoverer.get(0).getClass().getDeclaredField("parameterNamesCache"); } catch (NoSuchFieldException nsfe) { log.log(Level.SEVERE, "Unexpectedly cannot find parameterNamesCache field on LocalVariableTableParameterNameDiscoverer class"); } } for (Object instance: instancesOf_LocalVariableTableParameterNameDiscoverer) { field_parameterNamesCache.setAccessible(true); try { Map<?,?> parameterNamesCache = (Map<?,?>)field_parameterNamesCache.get(instance); Object o = parameterNamesCache.remove(clazz); if (debug) { System.out.println("ParameterNamesCache: Removed "+clazz.getName()+" from cache?"+(o!=null)); } } catch (IllegalAccessException e) { log.log(Level.SEVERE, "Unexpected IllegalAccessException trying to access parameterNamesCache field on LocalVariableTableParameterNameDiscoverer class"); } } } private void removeClazzFromMethodResolverCache(Class<?> clazz) { for (Object o : instancesOf_AnnotationMethodHandlerAdapter) { try { Field f = o.getClass().getDeclaredField("methodResolverCache"); f.setAccessible(true); Map<?, ?> map = (Map<?, ?>) f.get(o); Method removeMethod = Map.class.getDeclaredMethod("remove", Object.class); Object ret = removeMethod.invoke(map, clazz); if (GlobalConfiguration.debugplugins) { System.err.println("SpringPlugin: clearing methodResolverCache for " + clazz.getName()); } if (GlobalConfiguration.isRuntimeLogging && log.isLoggable(Level.INFO)) { log.info("cleared a cache entry? " + (ret != null)); } } catch (Exception e) { log.log(Level.SEVERE, "Unexpected problem accessing methodResolverCache on " + o, e); } } } private void clearCachedIntrospectionResults(Class<?> clazz) { if (cachedIntrospectionResultsClassLoaded) { try { // TODO not a fan of classloading like this if (cachedIntrospectionResultsClass == null) { // TODO what about two apps using reloading and diff versions of spring? cachedIntrospectionResultsClass = clazz.getClassLoader().loadClass( "org.springframework.beans.CachedIntrospectionResults"); } if (classCacheField == null) { classCacheField = cachedIntrospectionResultsClass.getDeclaredField("classCache"); } classCacheField.setAccessible(true); Map m = (Map) classCacheField.get(null); Object o = m.remove(clazz); if (GlobalConfiguration.debugplugins) { System.err .println("SpringPlugin: clearing CachedIntrospectionResults for " + clazz.getName() + " removed=" + o); } } catch (Exception e) { if (GlobalConfiguration.debugplugins) { e.printStackTrace(); } } } } private void reinvokeDetectHandlers() { // want to call detectHandlers on the DefaultAnnotationHandlerMapping type // protected void detectHandlers() throws BeansException { is defined on AbstractDetectingUrlHandlerMapping for (Object o : instancesOf_DefaultAnnotationHandlerMapping) { if (debug) { System.out.println("Invoking detectHandlers on instance of DefaultAnnotationHandlerMappingInstance"); } try { Class<?> clazz_AbstractDetectingUrlHandlerMapping = o.getClass().getSuperclass(); Method method_detectHandlers = clazz_AbstractDetectingUrlHandlerMapping.getDeclaredMethod("detectHandlers"); method_detectHandlers.setAccessible(true); method_detectHandlers.invoke(o); } catch (Exception e) { // if debugging then print it if (GlobalConfiguration.debugplugins) { e.printStackTrace(); } } } } @SuppressWarnings("rawtypes") private void reinvokeInitHandlerMethods() { // org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping (super AbstractHandlerMethodMapping) - call protected void initHandlerMethods() on it. for (Object o : instancesOf_RequestMappingHandlerMapping) { if (debug) { System.out.println("Invoking initHandlerMethods on instance of RequestMappingHandlerMapping"); } try { Class<?> clazz_AbstractHandlerMethodMapping = o.getClass().getSuperclass().getSuperclass(); // private final Map<T, HandlerMethod> handlerMethods = new LinkedHashMap<T, HandlerMethod>(); Field field_handlerMethods = clazz_AbstractHandlerMethodMapping.getDeclaredField("handlerMethods"); field_handlerMethods.setAccessible(true); Map m = (Map) field_handlerMethods.get(o); m.clear(); Field field_urlMap = clazz_AbstractHandlerMethodMapping.getDeclaredField("urlMap"); field_urlMap.setAccessible(true); m = (Map) field_urlMap.get(o); m.clear(); Method method_initHandlerMethods = clazz_AbstractHandlerMethodMapping.getDeclaredMethod("initHandlerMethods"); method_initHandlerMethods.setAccessible(true); method_initHandlerMethods.invoke(o); } catch (NoSuchFieldException nsfe) { if (debug) { if (nsfe.getMessage().equals("handlerMethods")) { System.out.println("problem resetting request mapping handlers - unable to find field 'handlerMethods' on type 'AbstractHandlerMethodMapping' - you probably are not on Spring 3.1"); } else { System.out.println("problem resetting request mapping handlers - NoSuchFieldException: "+nsfe.getMessage()); } } } catch (Exception e) { if (GlobalConfiguration.debugplugins) { e.printStackTrace(); } } } } public boolean shouldRerunStaticInitializer(String typename, Class<?> clazz, String encodedTimestamp) { return false; } /** * Modify the supplied bytes such that constructors are intercepted and will invoke the specified class/method so that the * instances can be tracked. * * @return modified bytes for the class */ private byte[] bytesWithInstanceCreationCaptured(byte[] bytes, String classToCall, String methodToCall) { ClassReader cr = new ClassReader(bytes); ClassVisitingConstructorAppender ca = new ClassVisitingConstructorAppender(classToCall, methodToCall); cr.accept(ca, 0); byte[] newbytes = ca.getBytes(); return newbytes; } }
Fix #80: NoSuchFieldException with Spring 4.1
springloaded/src/main/java/org/springsource/loaded/agent/SpringPlugin.java
Fix #80: NoSuchFieldException with Spring 4.1
Java
apache-2.0
34440e06efa3f157b6131d9244f6b9197237acc3
0
DataTorrent/incubator-apex-malhar,ananthc/apex-malhar,PramodSSImmaneni/apex-malhar,prasannapramod/apex-malhar,chinmaykolhatkar/apex-malhar,vrozov/incubator-apex-malhar,siyuanh/apex-malhar,ilganeli/incubator-apex-malhar,skekre98/apex-mlhr,PramodSSImmaneni/incubator-apex-malhar,DataTorrent/Megh,chandnisingh/apex-malhar,siyuanh/apex-malhar,DataTorrent/incubator-apex-malhar,PramodSSImmaneni/incubator-apex-malhar,PramodSSImmaneni/incubator-apex-malhar,yogidevendra/incubator-apex-malhar,PramodSSImmaneni/apex-malhar,chandnisingh/apex-malhar,tweise/apex-malhar,tweise/incubator-apex-malhar,PramodSSImmaneni/incubator-apex-malhar,brightchen/apex-malhar,siyuanh/incubator-apex-malhar,tushargosavi/incubator-apex-malhar,chinmaykolhatkar/apex-malhar,ilganeli/incubator-apex-malhar,PramodSSImmaneni/apex-malhar,siyuanh/incubator-apex-malhar,brightchen/apex-malhar,chandnisingh/apex-malhar,trusli/apex-malhar,trusli/apex-malhar,ananthc/apex-malhar,yogidevendra/apex-malhar,chandnisingh/apex-malhar,PramodSSImmaneni/incubator-apex-malhar,skekre98/apex-mlhr,tushargosavi/incubator-apex-malhar,chandnisingh/apex-malhar,apache/incubator-apex-malhar,tushargosavi/incubator-apex-malhar,tweise/incubator-apex-malhar,DataTorrent/incubator-apex-malhar,skekre98/apex-mlhr,PramodSSImmaneni/incubator-apex-malhar,vrozov/apex-malhar,prasannapramod/apex-malhar,apache/incubator-apex-malhar,ananthc/apex-malhar,skekre98/apex-mlhr,siyuanh/incubator-apex-malhar,patilvikram/apex-malhar,apache/incubator-apex-malhar,skekre98/apex-mlhr,siyuanh/apex-malhar,yogidevendra/apex-malhar,siyuanh/incubator-apex-malhar,yogidevendra/incubator-apex-malhar,yogidevendra/incubator-apex-malhar,ananthc/apex-malhar,vrozov/incubator-apex-malhar,sandeep-n/incubator-apex-malhar,PramodSSImmaneni/apex-malhar,tushargosavi/incubator-apex-malhar,chinmaykolhatkar/incubator-apex-malhar,trusli/apex-malhar,tushargosavi/incubator-apex-malhar,tushargosavi/incubator-apex-malhar,patilvikram/apex-malhar,siyuanh/apex-malhar,chandnisingh/apex-malhar,ilganeli/incubator-apex-malhar,trusli/apex-malhar,DataTorrent/Megh,vrozov/incubator-apex-malhar,PramodSSImmaneni/incubator-apex-malhar,yogidevendra/apex-malhar,ilganeli/incubator-apex-malhar,siyuanh/apex-malhar,vrozov/incubator-apex-malhar,DataTorrent/incubator-apex-malhar,DataTorrent/incubator-apex-malhar,davidyan74/apex-malhar,davidyan74/apex-malhar,vrozov/apex-malhar,apache/incubator-apex-malhar,prasannapramod/apex-malhar,vrozov/apex-malhar,prasannapramod/apex-malhar,sandeep-n/incubator-apex-malhar,yogidevendra/apex-malhar,ilganeli/incubator-apex-malhar,PramodSSImmaneni/apex-malhar,vrozov/apex-malhar,chinmaykolhatkar/apex-malhar,brightchen/apex-malhar,siyuanh/apex-malhar,prasannapramod/apex-malhar,tweise/apex-malhar,sandeep-n/incubator-apex-malhar,chinmaykolhatkar/apex-malhar,yogidevendra/incubator-apex-malhar,sandeep-n/incubator-apex-malhar,chinmaykolhatkar/incubator-apex-malhar,apache/incubator-apex-malhar,chinmaykolhatkar/apex-malhar,yogidevendra/incubator-apex-malhar,siyuanh/incubator-apex-malhar,chinmaykolhatkar/apex-malhar,yogidevendra/incubator-apex-malhar,sandeep-n/incubator-apex-malhar,patilvikram/apex-malhar,tweise/incubator-apex-malhar,chinmaykolhatkar/incubator-apex-malhar,chandnisingh/apex-malhar,patilvikram/apex-malhar,davidyan74/apex-malhar,tweise/apex-malhar,yogidevendra/incubator-apex-malhar,tweise/apex-malhar,davidyan74/apex-malhar,brightchen/apex-malhar,skekre98/apex-mlhr,trusli/apex-malhar,patilvikram/apex-malhar,davidyan74/apex-malhar,DataTorrent/incubator-apex-malhar,chinmaykolhatkar/incubator-apex-malhar,vrozov/incubator-apex-malhar,ilganeli/incubator-apex-malhar,PramodSSImmaneni/apex-malhar,vrozov/apex-malhar,tushargosavi/incubator-apex-malhar,chinmaykolhatkar/incubator-apex-malhar,siyuanh/incubator-apex-malhar,brightchen/apex-malhar,tweise/incubator-apex-malhar,tweise/incubator-apex-malhar,apache/incubator-apex-malhar,patilvikram/apex-malhar,chinmaykolhatkar/incubator-apex-malhar,chinmaykolhatkar/apex-malhar,patilvikram/apex-malhar,DataTorrent/incubator-apex-malhar,yogidevendra/apex-malhar,sandeep-n/incubator-apex-malhar,PramodSSImmaneni/apex-malhar,ananthc/apex-malhar,tweise/incubator-apex-malhar,yogidevendra/apex-malhar,vrozov/apex-malhar,vrozov/incubator-apex-malhar,tweise/apex-malhar,brightchen/apex-malhar,tweise/incubator-apex-malhar,apache/incubator-apex-malhar,chinmaykolhatkar/incubator-apex-malhar,siyuanh/apex-malhar,vrozov/incubator-apex-malhar,trusli/apex-malhar,brightchen/apex-malhar,tweise/apex-malhar,ananthc/apex-malhar,trusli/apex-malhar,prasannapramod/apex-malhar,davidyan74/apex-malhar,sandeep-n/incubator-apex-malhar,ilganeli/incubator-apex-malhar,siyuanh/incubator-apex-malhar
/* * Copyright (c) 2012-2013 Malhar, Inc. * All Rights Reserved. */ package com.malhartech.demos.yahoofinance; import com.malhartech.api.ApplicationFactory; import com.malhartech.api.DAG; import com.malhartech.contrib.sqlite.SqliteStreamOperator; import com.malhartech.lib.io.SmtpOutputOperator; import com.malhartech.lib.util.Alert; import java.util.HashMap; import org.apache.hadoop.conf.Configuration; /** * This demo will output the stock market data from yahoo finance * * @author David Yan <[email protected]> */ public class ApplicationWithAlert implements ApplicationFactory { @Override public DAG getApplication(Configuration conf) { String[] symbols = {"YHOO", "GOOG", "AAPL", "FB", "AMZN", "NFLX", "IBM"}; DAG dag = new DAG(); YahooFinanceCSVInputOperator input1 = dag.addOperator("input1", new YahooFinanceCSVInputOperator()); SqliteStreamOperator sqlOper = dag.addOperator("sqlOper", new SqliteStreamOperator()); Alert<HashMap<String, Object>> alertOper = dag.addOperator("alert", new Alert<HashMap<String, Object>>()); //ConsoleOutputOperator consoleOperator = dag.addOperator("console", new ConsoleOutputOperator()); SmtpOutputOperator<HashMap<String, Object>> mailOper = dag.addOperator("mail", new SmtpOutputOperator<HashMap<String, Object>>()); mailOper.setFrom("[email protected]"); mailOper.addRecipient(SmtpOutputOperator.RecipientType.TO, "[email protected]"); mailOper.setContent("AAPL: {}\nThis is an auto-generated message. Do not reply."); mailOper.setSubject("ALERT: AAPL is less than 450"); mailOper.setSmtpHost("secure.emailsrvr.com"); mailOper.setSmtpPort(465); mailOper.setSmtpUserName("[email protected]"); mailOper.setSmtpPassword("Testing1"); mailOper.setUseSsl(true); alertOper.setAlertFrequency(60000); // 30 seconds for (String symbol: symbols) { input1.addSymbol(symbol); } input1.addFormat("s0"); input1.addFormat("l1"); SqliteStreamOperator.InputSchema inputSchema1 = new SqliteStreamOperator.InputSchema("t1"); inputSchema1.setColumnInfo("s0", "string", true); // symbol inputSchema1.setColumnInfo("l1", "float", false); // last trade sqlOper.setInputSchema(0, inputSchema1); // select the alert using SQL sqlOper.setStatement("SELECT t1.s0 AS symbol, t1.l1 AS last_trade FROM t1 WHERE t1.s0 = 'AAPL' AND t1.l1 < 450"); dag.addStream("input1_sql", input1.outputPort, sqlOper.in1); dag.addStream("sql_alert", sqlOper.result, alertOper.in); //dag.addStream("alert_console", alertOper.alert1, consoleOperator.input); dag.addStream("alert_mail", alertOper.alert1, mailOper.input); return dag; } }
demos/src/main/java/com/malhartech/demos/yahoofinance/ApplicationWithAlert.java
/* * Copyright (c) 2012-2013 Malhar, Inc. * All Rights Reserved. */ package com.malhartech.demos.yahoofinance; import com.malhartech.api.ApplicationFactory; import com.malhartech.api.DAG; import com.malhartech.contrib.sqlite.SqliteStreamOperator; import com.malhartech.lib.io.SmtpOutputOperator; import com.malhartech.lib.util.Alert; import java.util.HashMap; import org.apache.hadoop.conf.Configuration; /** * This demo will output the stock market data from yahoo finance * * @author David Yan <[email protected]> */ public class ApplicationWithAlert implements ApplicationFactory { @Override public DAG getApplication(Configuration conf) { String[] symbols = {"YHOO", "GOOG", "AAPL", "FB", "AMZN", "NFLX", "IBM"}; DAG dag = new DAG(); YahooFinanceCSVInputOperator input1 = dag.addOperator("input1", new YahooFinanceCSVInputOperator()); SqliteStreamOperator sqlOper = dag.addOperator("sqlOper", new SqliteStreamOperator()); Alert<HashMap<String, Object>> alertOper = dag.addOperator("alert", new Alert<HashMap<String, Object>>()); //ConsoleOutputOperator consoleOperator = dag.addOperator("console", new ConsoleOutputOperator()); SmtpOutputOperator<HashMap<String, Object>> mailOper = dag.addOperator("mail", new SmtpOutputOperator<HashMap<String, Object>>()); mailOper.setFrom("[email protected]"); mailOper.addRecipient(SmtpOutputOperator.RecipientType.TO, "[email protected]"); mailOper.setContent("AAPL: {}\nThis is an auto-generated message. Do not reply."); mailOper.setSubject("ALERT: AAPL is less than 450"); mailOper.setSmtpHost("secure.emailsrvr.com"); mailOper.setSmtpPort(465); mailOper.setSmtpUserName("[email protected]"); mailOper.setSmtpPassword("Testing1"); mailOper.setUseSsl(true); alertOper.setAlertFrequency(60000); // 30 seconds for (String symbol: symbols) { input1.addSymbol(symbol); } input1.addFormat("s0"); input1.addFormat("l1"); SqliteStreamOperator.InputSchema inputSchema1 = new SqliteStreamOperator.InputSchema("t1"); inputSchema1.setColumnInfo("s0", "string", true); // symbol inputSchema1.setColumnInfo("l1", "float", false); // last trade sqlOper.setInputSchema(0, inputSchema1); // Calculate PE Ratio and PB Ratio using SQL sqlOper.setStatement("SELECT t1.s0 AS symbol, t1.l1 AS last_trade FROM t1 WHERE t1.s0 = 'AAPL' AND t1.l1 < 450"); dag.addStream("input1_sql", input1.outputPort, sqlOper.in1); dag.addStream("sql_alert", sqlOper.result, alertOper.in); //dag.addStream("alert_console", alertOper.alert1, consoleOperator.input); dag.addStream("alert_mail", alertOper.alert1, mailOper.input); return dag; } }
corrected comment
demos/src/main/java/com/malhartech/demos/yahoofinance/ApplicationWithAlert.java
corrected comment
Java
apache-2.0
bc6101d49ed305cfb290910d0038446ad84f72b3
0
Devlight/NavigationTabBar,DevLight-Mobile-Agency/NavigationTabBar
/* * Copyright (C) 2015 Basil Miller * * 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.gigamole.library; import android.animation.Animator; import android.animation.ValueAnimator; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.PorterDuff; import android.graphics.PorterDuffColorFilter; import android.graphics.PorterDuffXfermode; import android.graphics.Rect; import android.graphics.RectF; import android.graphics.Typeface; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.os.Parcel; import android.os.Parcelable; import android.support.v4.view.ViewPager; import android.text.TextPaint; import android.text.TextUtils; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import android.view.animation.AccelerateDecelerateInterpolator; import android.view.animation.AccelerateInterpolator; import android.view.animation.DecelerateInterpolator; import android.view.animation.Interpolator; import android.view.animation.LinearInterpolator; import android.widget.Scroller; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Random; /** * Created by GIGAMOLE on 24.03.2016. */ public class NavigationTabBar extends View implements ViewPager.OnPageChangeListener { // NTP constants private final static String PREVIEW_BADGE = "0"; private final static String PREVIEW_TITLE = "Title"; private final static int INVALID_INDEX = -1; private final static int DEFAULT_BADGE_ANIMATION_DURATION = 200; private final static int DEFAULT_BADGE_REFRESH_ANIMATION_DURATION = 100; private final static int DEFAULT_ANIMATION_DURATION = 300; private final static int DEFAULT_INACTIVE_COLOR = Color.parseColor("#9f90af"); private final static int DEFAULT_ACTIVE_COLOR = Color.WHITE; private final static float MIN_FRACTION = 0.0f; private final static float MAX_FRACTION = 1.0f; private final static int MIN_ALPHA = 0; private final static int MAX_ALPHA = 255; private final static float ACTIVE_ICON_SCALE_BY = 0.35f; private final static float ICON_SIZE_FRACTION = 0.4f; private final static float TITLE_ACTIVE_ICON_SCALE_BY = 0.25f; private final static float TITLE_ICON_SIZE_FRACTION = 0.4f; private final static float TITLE_ACTIVE_SCALE_BY = 0.2f; private final static float TITLE_SIZE_FRACTION = 0.2f; private final static float TITLE_MARGIN_FRACTION = 0.15f; private final static float BADGE_HORIZONTAL_FRACTION = 0.5f; private final static float BADGE_VERTICAL_FRACTION = 0.75f; private final static float BADGE_TITLE_SIZE_FRACTION = 0.85f; private final static int ALL_INDEX = 0; private final static int ACTIVE_INDEX = 1; private final static int LEFT_INDEX = 0; private final static int CENTER_INDEX = 1; private final static int RIGHT_INDEX = 2; private final static int TOP_INDEX = 0; private final static int BOTTOM_INDEX = 1; private final static float LEFT_FRACTION = 0.25f; private final static float CENTER_FRACTION = 0.5f; private final static float RIGHT_FRACTION = 0.75f; private final static Interpolator DECELERATE_INTERPOLATOR = new DecelerateInterpolator(); private final static Interpolator ACCELERATE_INTERPOLATOR = new AccelerateInterpolator(); // NTP and pointer bounds private RectF mBounds = new RectF(); private RectF mPointerBounds = new RectF(); // Badge bounds and bg badge bounds final Rect mBadgeBounds = new Rect(); final RectF mBgBadgeBounds = new RectF(); // Canvas, where all of other canvas will be merged private Bitmap mBitmap; private Canvas mCanvas; // Canvas with icons private Bitmap mIconsBitmap; private Canvas mIconsCanvas; // Canvas for our rect pointer private Bitmap mPointerBitmap; private Canvas mPointerCanvas; // Main paint private Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG) { { setDither(true); setStyle(Style.FILL); } }; // Pointer paint private Paint mPointerPaint = new Paint(Paint.ANTI_ALIAS_FLAG) { { setDither(true); setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN)); } }; // Icons paint private Paint mIconPaint = new Paint(Paint.ANTI_ALIAS_FLAG) { { setDither(true); } }; // Paint for icon mask pointer final Paint mIconPointerPaint = new Paint(Paint.ANTI_ALIAS_FLAG) { { setStyle(Style.FILL); setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN)); } }; // Paint for model title final Paint mModelTitlePaint = new TextPaint(Paint.ANTI_ALIAS_FLAG) { { setDither(true); setColor(Color.WHITE); setTextAlign(Align.CENTER); } }; // Paint for badge final Paint mBadgePaint = new TextPaint(Paint.ANTI_ALIAS_FLAG) { { setDither(true); setTextAlign(Align.CENTER); setFakeBoldText(true); } }; // Variables for animator private ValueAnimator mAnimator = new ValueAnimator(); private ResizeInterpolator mResizeInterpolator = new ResizeInterpolator(); private int mAnimationDuration; // NTP models private ArrayList<Model> mModels = new ArrayList<>(); // Variables for ViewPager private ViewPager mViewPager; private ViewPager.OnPageChangeListener mOnPageChangeListener; private int mScrollState; // Tab listener private OnTabBarSelectedIndexListener mOnTabBarSelectedIndexListener; private ValueAnimator.AnimatorListener mAnimatorListener; // Variables for sizes private float mModelSize; private int mIconSize; // Corners radius for rect mode private float mCornersRadius; // Model title size and margin private float mModelTitleSize; private float mTitleMargin; // Model badge title size and margin private float mBadgeMargin; private float mBadgeTitleSize; // Model title mode: active ar all private TitleMode mTitleMode; // Model badge position: left, center or right private BadgePosition mBadgePosition; // Model badge gravity: top or bottom private BadgeGravity mBadgeGravity; // Indexes private int mLastIndex = INVALID_INDEX; private int mIndex = INVALID_INDEX; // General fraction value private float mFraction; // Coordinates of pointer private float mStartPointerX; private float mEndPointerX; private float mPointerLeftTop; private float mPointerRightBottom; // Detect if model has title private boolean mIsTitled; // Detect if model has badge private boolean mIsBadged; // Detect if model badge have custom typeface private boolean mIsBadgeUseTypeface; // Detect if is bar mode or indicator pager mode private boolean mIsViewPagerMode; // Detect whether the horizontal orientation private boolean mIsHorizontalOrientation; // Detect if we move from left to right private boolean mIsResizeIn; // Detect if we get action down event private boolean mIsActionDown; // Detect if we get action down event on pointer private boolean mIsPointerActionDown; // Detect when we set index from tab bar nor from ViewPager private boolean mIsSetIndexFromTabBar; // Color variables private int mInactiveColor; private int mActiveColor; // Custom typeface private Typeface mTypeface; public NavigationTabBar(final Context context) { this(context, null); } public NavigationTabBar(final Context context, final AttributeSet attrs) { this(context, attrs, 0); } public NavigationTabBar(final Context context, final AttributeSet attrs, final int defStyleAttr) { super(context, attrs, defStyleAttr); //Init NTB // Always draw setWillNotDraw(false); // More speed! setLayerType(LAYER_TYPE_HARDWARE, null); final TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.NavigationTabBar); try { setIsTitled( typedArray.getBoolean(R.styleable.NavigationTabBar_ntb_titled, false) ); setIsBadged( typedArray.getBoolean(R.styleable.NavigationTabBar_ntb_badged, false) ); setIsBadgeUseTypeface( typedArray.getBoolean(R.styleable.NavigationTabBar_ntb_badge_use_typeface, false) ); setTitleMode( typedArray.getInt(R.styleable.NavigationTabBar_ntb_title_mode, ALL_INDEX) ); setBadgePosition( typedArray.getInt(R.styleable.NavigationTabBar_ntb_badge_position, RIGHT_INDEX) ); setBadgeGravity( typedArray.getInt(R.styleable.NavigationTabBar_ntb_badge_gravity, TOP_INDEX) ); setTypeface( typedArray.getString(R.styleable.NavigationTabBar_ntb_typeface) ); setInactiveColor( typedArray.getColor( R.styleable.NavigationTabBar_ntb_inactive_color, DEFAULT_INACTIVE_COLOR ) ); setActiveColor( typedArray.getColor( R.styleable.NavigationTabBar_ntb_active_color, DEFAULT_ACTIVE_COLOR ) ); setAnimationDuration( typedArray.getInteger( R.styleable.NavigationTabBar_ntb_animation_duration, DEFAULT_ANIMATION_DURATION ) ); setCornersRadius( typedArray.getDimension(R.styleable.NavigationTabBar_ntb_corners_radius, 0.0f) ); // Init animator mAnimator.setFloatValues(MIN_FRACTION, MAX_FRACTION); mAnimator.setInterpolator(new LinearInterpolator()); mAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(final ValueAnimator animation) { updateIndicatorPosition((Float) animation.getAnimatedValue()); } }); // Set preview models if (isInEditMode()) { // Get preview colors String[] previewColors = null; try { final int previewColorsId = typedArray.getResourceId( R.styleable.NavigationTabBar_ntb_preview_colors, 0 ); previewColors = previewColorsId == 0 ? null : typedArray.getResources().getStringArray(previewColorsId); } catch (Exception exception) { previewColors = null; exception.printStackTrace(); } finally { if (previewColors == null) previewColors = typedArray.getResources().getStringArray(R.array.default_preview); for (String previewColor : previewColors) mModels.add(new Model(null, Color.parseColor(previewColor))); requestLayout(); } } } finally { typedArray.recycle(); } } public int getAnimationDuration() { return mAnimationDuration; } public void setAnimationDuration(final int animationDuration) { mAnimationDuration = animationDuration; mAnimator.setDuration(mAnimationDuration); resetScroller(); } public ArrayList<Model> getModels() { return mModels; } public void setModels(final ArrayList<Model> models) { //Set update listeners to badge model animation for (final Model model : models) { model.mBadgeAnimator.removeAllUpdateListeners(); model.mBadgeAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(final ValueAnimator animation) { model.mBadgeFraction = (float) animation.getAnimatedValue(); postInvalidate(); } }); } mModels.clear(); mModels = models; requestLayout(); } public boolean isTitled() { return mIsTitled; } public void setIsTitled(final boolean isTitled) { mIsTitled = isTitled; requestLayout(); } public boolean isBadged() { return mIsBadged; } public void setIsBadged(final boolean isBadged) { mIsBadged = isBadged; requestLayout(); } public boolean isBadgeUseTypeface() { return mIsBadgeUseTypeface; } public void setIsBadgeUseTypeface(final boolean isBadgeUseTypeface) { mIsBadgeUseTypeface = isBadgeUseTypeface; setBadgeTypeface(); postInvalidate(); } public TitleMode getTitleMode() { return mTitleMode; } private void setTitleMode(final int index) { switch (index) { case ACTIVE_INDEX: setTitleMode(TitleMode.ACTIVE); break; case ALL_INDEX: default: setTitleMode(TitleMode.ALL); } } public void setTitleMode(final TitleMode titleMode) { mTitleMode = titleMode; postInvalidate(); } public BadgePosition getBadgePosition() { return mBadgePosition; } private void setBadgePosition(final int index) { switch (index) { case LEFT_INDEX: setBadgePosition(BadgePosition.LEFT); break; case CENTER_INDEX: setBadgePosition(BadgePosition.CENTER); break; case RIGHT_INDEX: default: setBadgePosition(BadgePosition.RIGHT); } } public void setBadgePosition(final BadgePosition badgePosition) { mBadgePosition = badgePosition; postInvalidate(); } public BadgeGravity getBadgeGravity() { return mBadgeGravity; } private void setBadgeGravity(final int index) { switch (index) { case BOTTOM_INDEX: setBadgeGravity(BadgeGravity.BOTTOM); break; case TOP_INDEX: default: setBadgeGravity(BadgeGravity.TOP); } } public void setBadgeGravity(final BadgeGravity badgeGravity) { mBadgeGravity = badgeGravity; requestLayout(); } public Typeface getTypeface() { return mTypeface; } public void setTypeface(final String typeface) { Typeface tempTypeface; try { tempTypeface = Typeface.createFromAsset(getContext().getAssets(), typeface); } catch (Exception e) { tempTypeface = Typeface.create(Typeface.DEFAULT, Typeface.NORMAL); e.printStackTrace(); } setTypeface(tempTypeface); } public void setTypeface(final Typeface typeface) { mTypeface = typeface; mModelTitlePaint.setTypeface(typeface); setBadgeTypeface(); postInvalidate(); } private void setBadgeTypeface() { mBadgePaint.setTypeface( mIsBadgeUseTypeface ? mTypeface : Typeface.create(Typeface.DEFAULT, Typeface.NORMAL) ); } public int getActiveColor() { return mActiveColor; } public void setActiveColor(final int activeColor) { mActiveColor = activeColor; mIconPointerPaint.setColor(activeColor); postInvalidate(); } public int getInactiveColor() { return mInactiveColor; } public void setInactiveColor(final int inactiveColor) { mInactiveColor = inactiveColor; // Set color filter to wrap icons with inactive color mIconPaint.setColorFilter(new PorterDuffColorFilter(inactiveColor, PorterDuff.Mode.SRC_IN)); mModelTitlePaint.setColor(mInactiveColor); postInvalidate(); } public float getCornersRadius() { return mCornersRadius; } public void setCornersRadius(final float cornersRadius) { mCornersRadius = cornersRadius; postInvalidate(); } public float getBadgeMargin() { return mBadgeMargin; } public float getBarHeight() { return mBounds.height(); } public OnTabBarSelectedIndexListener getOnTabBarSelectedIndexListener() { return mOnTabBarSelectedIndexListener; } // Set on tab bar selected index listener where you can trigger action onStart or onEnd public void setOnTabBarSelectedIndexListener(final OnTabBarSelectedIndexListener onTabBarSelectedIndexListener) { mOnTabBarSelectedIndexListener = onTabBarSelectedIndexListener; if (mAnimatorListener == null) mAnimatorListener = new Animator.AnimatorListener() { @Override public void onAnimationStart(final Animator animation) { if (mOnTabBarSelectedIndexListener != null) mOnTabBarSelectedIndexListener.onStartTabSelected(mModels.get(mIndex), mIndex); } @Override public void onAnimationEnd(final Animator animation) { if (mOnTabBarSelectedIndexListener != null) mOnTabBarSelectedIndexListener.onEndTabSelected(mModels.get(mIndex), mIndex); } @Override public void onAnimationCancel(final Animator animation) { } @Override public void onAnimationRepeat(final Animator animation) { } }; mAnimator.removeListener(mAnimatorListener); mAnimator.addListener(mAnimatorListener); } public void setViewPager(final ViewPager viewPager) { // Detect whether ViewPager mode if (viewPager == null) { mIsViewPagerMode = false; return; } if (mViewPager == viewPager) return; if (mViewPager != null) mViewPager.setOnPageChangeListener(null); if (viewPager.getAdapter() == null) throw new IllegalStateException("ViewPager does not provide adapter instance."); mIsViewPagerMode = true; mViewPager = viewPager; mViewPager.addOnPageChangeListener(this); resetScroller(); postInvalidate(); } public void setViewPager(final ViewPager viewPager, int index) { setViewPager(viewPager); mIndex = index; if (mIsViewPagerMode) mViewPager.setCurrentItem(index, true); postInvalidate(); } // Reset scroller and reset scroll duration equals to animation duration private void resetScroller() { if (mViewPager == null) return; try { final Field scrollerField = ViewPager.class.getDeclaredField("mScroller"); scrollerField.setAccessible(true); final ResizeViewPagerScroller scroller = new ResizeViewPagerScroller(getContext()); scrollerField.set(mViewPager, scroller); } catch (Exception e) { e.printStackTrace(); } } public void setOnPageChangeListener(final ViewPager.OnPageChangeListener listener) { mOnPageChangeListener = listener; } public int getModelIndex() { return mIndex; } public void setModelIndex(int index) { setModelIndex(index, false); } // Set model index from touch or programmatically public void setModelIndex(int index, boolean force) { if (mAnimator.isRunning()) return; if (mModels.isEmpty()) return; // This check gives us opportunity to have an non selected model if (mIndex == INVALID_INDEX) force = true; // Detect if last is the same if (index == mIndex) return; // Snap index to models size index = Math.max(0, Math.min(index, mModels.size() - 1)); mIsResizeIn = index < mIndex; mLastIndex = mIndex; mIndex = index; mIsSetIndexFromTabBar = true; if (mIsViewPagerMode) { if (mViewPager == null) throw new IllegalStateException("ViewPager is null."); mViewPager.setCurrentItem(index, true); } // Set startX and endX for animation, where we animate two sides of rect with different interpolation mStartPointerX = mPointerLeftTop; mEndPointerX = mIndex * mModelSize; // If it force, so update immediately, else animate // This happens if we set index onCreate or something like this // You can use force param or call this method in some post() if (force) updateIndicatorPosition(MAX_FRACTION); else mAnimator.start(); } private void updateIndicatorPosition(final float fraction) { // Update general fraction mFraction = fraction; // Set the pointer left top side coordinate mPointerLeftTop = mStartPointerX + (mResizeInterpolator.getResizeInterpolation(fraction, mIsResizeIn) * (mEndPointerX - mStartPointerX)); // Set the pointer right bottom side coordinate mPointerRightBottom = (mStartPointerX + mModelSize) + (mResizeInterpolator.getResizeInterpolation(fraction, !mIsResizeIn) * (mEndPointerX - mStartPointerX)); // Update pointer postInvalidate(); } // Update NTP private void notifyDataSetChanged() { postInvalidate(); } @Override public boolean onTouchEvent(final MotionEvent event) { // Return if animation is running if (mAnimator.isRunning()) return true; // If is not idle state, return if (mScrollState != ViewPager.SCROLL_STATE_IDLE) return true; switch (event.getAction()) { case MotionEvent.ACTION_DOWN: // Action down touch mIsActionDown = true; if (!mIsViewPagerMode) break; // Detect if we touch down on pointer, later to move if (mIsHorizontalOrientation) mIsPointerActionDown = (int) (event.getX() / mModelSize) == mIndex; else mIsPointerActionDown = (int) (event.getY() / mModelSize) == mIndex; break; case MotionEvent.ACTION_MOVE: // If pointer touched, so move if (mIsPointerActionDown) { if (mIsHorizontalOrientation) mViewPager.setCurrentItem((int) (event.getX() / mModelSize), true); else mViewPager.setCurrentItem((int) (event.getY() / mModelSize), true); break; } if (mIsActionDown) break; case MotionEvent.ACTION_UP: // Press up and set model index relative to current coordinate if (mIsActionDown) { if (mIsHorizontalOrientation) setModelIndex((int) (event.getX() / mModelSize)); else setModelIndex((int) (event.getY() / mModelSize)); } case MotionEvent.ACTION_CANCEL: case MotionEvent.ACTION_OUTSIDE: default: // Reset action touch variables mIsPointerActionDown = false; mIsActionDown = false; break; } return true; } @Override protected void onMeasure(final int widthMeasureSpec, final int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); // Get measure size final int width = MeasureSpec.getSize(widthMeasureSpec); final int height = MeasureSpec.getSize(heightMeasureSpec); if (mModels.isEmpty() || width == 0 || height == 0) return; // Detect orientation and calculate icon size if (width > height) { mIsHorizontalOrientation = true; // Get smaller side float side = mModelSize > height ? height : mModelSize; if (mIsBadged) side -= side * TITLE_SIZE_FRACTION; mModelSize = (float) width / (float) mModels.size(); mIconSize = (int) (side * (mIsTitled ? TITLE_ICON_SIZE_FRACTION : ICON_SIZE_FRACTION)); mModelTitleSize = side * TITLE_SIZE_FRACTION; mTitleMargin = side * TITLE_MARGIN_FRACTION; // If is badged mode, so get vars and set paint with default bounds if (mIsBadged) { mBadgeTitleSize = mModelTitleSize * BADGE_TITLE_SIZE_FRACTION; final Rect badgeBounds = new Rect(); mBadgePaint.setTextSize(mBadgeTitleSize); mBadgePaint.getTextBounds(PREVIEW_BADGE, 0, 1, badgeBounds); mBadgeMargin = (badgeBounds.height() * 0.5f) + (mBadgeTitleSize * BADGE_HORIZONTAL_FRACTION * BADGE_VERTICAL_FRACTION); } } else { mIsHorizontalOrientation = false; mIsTitled = false; mIsBadged = false; mModelSize = (float) height / (float) mModels.size(); mIconSize = (int) ((mModelSize > width ? width : mModelSize) * ICON_SIZE_FRACTION); } // Set bounds for NTB mBounds.set(0.0f, 0.0f, width, height - mBadgeMargin); // Set main bitmap mBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); mCanvas = new Canvas(mBitmap); // Set pointer canvas mPointerBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); mPointerCanvas = new Canvas(mPointerBitmap); // Set icons canvas mIconsBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); mIconsCanvas = new Canvas(mIconsBitmap); // Set scale fraction for icons for (Model model : mModels) { final float originalIconSize = model.mIcon.getWidth() > model.mIcon.getHeight() ? model.mIcon.getWidth() : model.mIcon.getHeight(); model.mInactiveIconScale = (float) mIconSize / originalIconSize; model.mActiveIconScaleBy = model.mInactiveIconScale * (mIsTitled ? TITLE_ACTIVE_ICON_SCALE_BY : ACTIVE_ICON_SCALE_BY); } // Set start position of pointer for preview or on start if (isInEditMode() || !mIsViewPagerMode) { mIsSetIndexFromTabBar = true; // Set random in preview mode if (isInEditMode()) { mIndex = new Random().nextInt(mModels.size()); if (mIsBadged) for (int i = 0; i < mModels.size(); i++) { final Model model = mModels.get(i); if (i == mIndex) { model.mBadgeFraction = MAX_FRACTION; model.showBadge(); } else { model.mBadgeFraction = MIN_FRACTION; model.hideBadge(); } } } mStartPointerX = mIndex * mModelSize; mEndPointerX = mStartPointerX; updateIndicatorPosition(MAX_FRACTION); } } @Override protected void onDraw(final Canvas canvas) { if (mCanvas == null || mPointerCanvas == null || mIconsCanvas == null) return; // Reset and clear canvases mCanvas.drawColor(0, PorterDuff.Mode.CLEAR); mPointerCanvas.drawColor(0, PorterDuff.Mode.CLEAR); mIconsCanvas.drawColor(0, PorterDuff.Mode.CLEAR); // Get pointer badge margin for gravity final float pointerBadgeMargin = mBadgeGravity == BadgeGravity.TOP ? mBadgeMargin : 0.0f; // Draw our model colors for (int i = 0; i < mModels.size(); i++) { mPaint.setColor(mModels.get(i).getColor()); if (mIsHorizontalOrientation) { final float left = mModelSize * i; final float right = left + mModelSize; mCanvas.drawRect( left, pointerBadgeMargin, right, mBounds.height() + pointerBadgeMargin, mPaint ); } else { final float top = mModelSize * i; final float bottom = top + mModelSize; mCanvas.drawRect(0.0f, top, mBounds.width(), bottom, mPaint); } } // Set bound of pointer if (mIsHorizontalOrientation) mPointerBounds.set( mPointerLeftTop, pointerBadgeMargin, mPointerRightBottom, mBounds.height() + pointerBadgeMargin ); else mPointerBounds.set(0.0f, mPointerLeftTop, mBounds.width(), mPointerRightBottom); // Draw pointer for model colors if (mCornersRadius == 0) mPointerCanvas.drawRect(mPointerBounds, mPaint); else mPointerCanvas.drawRoundRect(mPointerBounds, mCornersRadius, mCornersRadius, mPaint); // Draw pointer into main canvas mCanvas.drawBitmap(mPointerBitmap, 0.0f, 0.0f, mPointerPaint); // Draw model icons for (int i = 0; i < mModels.size(); i++) { final Model model = mModels.get(i); // Variables to center our icons final float leftOffset; final float topOffset; final float matrixCenterX; final float matrixCenterY; // Set vars for icon when model with title or without final float iconMarginTitleHeight = mIconSize + mTitleMargin + mModelTitleSize; final float leftTitleOffset = (mModelSize * i) + (mModelSize * 0.5f); final float topTitleOffset = mBounds.height() - (mBounds.height() - iconMarginTitleHeight) * 0.5f; if (mIsHorizontalOrientation) { leftOffset = (mModelSize * i) + (mModelSize - model.mIcon.getWidth()) * 0.5f; topOffset = (mBounds.height() - model.mIcon.getHeight()) * 0.5f; matrixCenterX = leftOffset + model.mIcon.getWidth() * 0.5f; matrixCenterY = topOffset + model.mIcon.getHeight() * 0.5f + (mIsTitled && mTitleMode == TitleMode.ALL ? mTitleMargin * 0.5f : 0.0f); } else { leftOffset = (mBounds.width() - model.mIcon.getWidth()) * 0.5f; topOffset = (mModelSize * i) + (mModelSize - model.mIcon.getHeight()) * 0.5f; matrixCenterX = leftOffset + model.mIcon.getWidth() * 0.5f; matrixCenterY = topOffset + model.mIcon.getHeight() * 0.5f; } // Title translate position final float titleTranslate = -model.mIcon.getHeight() + topTitleOffset - mTitleMargin * 0.5f; // Translate icon to model center model.mIconMatrix.setTranslate( leftOffset, (mIsTitled && mTitleMode == TitleMode.ALL) ? titleTranslate : topOffset ); // Get interpolated fraction for left last and current models final float interpolation = mResizeInterpolator.getResizeInterpolation(mFraction, true); final float lastInterpolation = mResizeInterpolator.getResizeInterpolation(mFraction, false); // Scale value relative to interpolation final float matrixScale = model.mActiveIconScaleBy * interpolation; final float matrixLastScale = model.mActiveIconScaleBy * lastInterpolation; // Get title alpha relative to interpolation final int titleAlpha = (int) (MAX_ALPHA * interpolation); final int titleLastAlpha = MAX_ALPHA - (int) (MAX_ALPHA * lastInterpolation); // Get title scale relative to interpolation final float titleScale = MAX_FRACTION + (interpolation * TITLE_ACTIVE_SCALE_BY); final float titleLastScale = (MAX_FRACTION + TITLE_ACTIVE_SCALE_BY) - (lastInterpolation * TITLE_ACTIVE_SCALE_BY); // Check if we handle models from touch on NTP or from ViewPager // There is a strange logic of ViewPager onPageScrolled method, so it is if (mIsSetIndexFromTabBar) { if (mIndex == i) updateCurrentModel( model, leftOffset, topOffset, titleTranslate, interpolation, matrixCenterX, matrixCenterY, matrixScale, titleScale, titleAlpha ); else if (mLastIndex == i) updateLastModel( model, leftOffset, topOffset, titleTranslate, lastInterpolation, matrixCenterX, matrixCenterY, matrixLastScale, titleLastScale, titleLastAlpha ); else updateInactiveModel( model, leftOffset, topOffset, matrixCenterX, matrixCenterY ); } else { if (i != mIndex && i != mIndex + 1) updateInactiveModel( model, leftOffset, topOffset, matrixCenterX, matrixCenterY ); else if (i == mIndex + 1) updateCurrentModel( model, leftOffset, topOffset, titleTranslate, interpolation, matrixCenterX, matrixCenterY, matrixScale, titleScale, titleAlpha ); else if (i == mIndex) updateLastModel( model, leftOffset, topOffset, titleTranslate, lastInterpolation, matrixCenterX, matrixCenterY, matrixLastScale, titleLastScale, titleLastAlpha ); } // Draw model icon mIconsCanvas.drawBitmap(model.mIcon, model.mIconMatrix, mIconPaint); if (mIsTitled) mIconsCanvas.drawText( isInEditMode() ? PREVIEW_TITLE : model.getTitle(), leftTitleOffset, topTitleOffset, mModelTitlePaint ); } // Draw pointer with active color to wrap out active icon if (mCornersRadius == 0) mIconsCanvas.drawRect(mPointerBounds, mIconPointerPaint); else mIconsCanvas.drawRoundRect(mPointerBounds, mCornersRadius, mCornersRadius, mIconPointerPaint); // Draw general bitmap canvas.drawBitmap(mBitmap, 0.0f, 0.0f, null); // Draw icons bitmap on top canvas.drawBitmap( mIconsBitmap, 0.0f, pointerBadgeMargin, null); // If is not badged, exit if (!mIsBadged) return; // Model badge margin and offset relative to gravity mode final float modelBadgeMargin = mBadgeGravity == BadgeGravity.TOP ? mBadgeMargin : mBounds.height(); final float modelBadgeOffset = mBadgeGravity == BadgeGravity.TOP ? 0.0f : mBounds.height() - mBadgeMargin; for (int i = 0; i < mModels.size(); i++) { final Model model = mModels.get(i); // Set preview badge title if (isInEditMode() || TextUtils.isEmpty(model.getBadgeTitle())) model.setBadgeTitle(PREVIEW_BADGE); // Set badge title bounds mBadgePaint.setTextSize(mBadgeTitleSize * model.mBadgeFraction); mBadgePaint.getTextBounds( model.getBadgeTitle(), 0, model.getBadgeTitle().length(), mBadgeBounds ); // Get horizontal and vertical padding for bg final float horizontalPadding = mBadgeTitleSize * BADGE_HORIZONTAL_FRACTION; final float verticalPadding = horizontalPadding * BADGE_VERTICAL_FRACTION; // Set horizontal badge offset final float badgeBoundsHorizontalOffset = (mModelSize * i) + (mModelSize * mBadgePosition.mPositionFraction); // If is badge title only one char, so create circle else round rect if (model.getBadgeTitle().length() == 1) { final float badgeMargin = mBadgeMargin * model.mBadgeFraction; mBgBadgeBounds.set( badgeBoundsHorizontalOffset - badgeMargin, modelBadgeMargin - badgeMargin, badgeBoundsHorizontalOffset + badgeMargin, modelBadgeMargin + badgeMargin ); } else mBgBadgeBounds.set( badgeBoundsHorizontalOffset - mBadgeBounds.centerX() - horizontalPadding, modelBadgeMargin - (mBadgeMargin * model.mBadgeFraction), badgeBoundsHorizontalOffset + mBadgeBounds.centerX() + horizontalPadding, modelBadgeOffset + (verticalPadding * 2.0f) + mBadgeBounds.height() ); // Set color and alpha for badge bg if (model.mBadgeFraction == MIN_FRACTION) mBadgePaint.setColor(Color.TRANSPARENT); else mBadgePaint.setColor(mActiveColor); mBadgePaint.setAlpha((int) (MAX_ALPHA * model.mBadgeFraction)); // Set corners to round rect for badge bg and draw final float cornerRadius = mBgBadgeBounds.height() * 0.5f; canvas.drawRoundRect(mBgBadgeBounds, cornerRadius, cornerRadius, mBadgePaint); // Set color and alpha for badge title if (model.mBadgeFraction == MIN_FRACTION) mBadgePaint.setColor(Color.TRANSPARENT); else mBadgePaint.setColor(model.getColor()); mBadgePaint.setAlpha((int) (MAX_ALPHA * model.mBadgeFraction)); // Set badge title center position and draw title final float badgeHalfHeight = mBadgeBounds.height() * 0.5f; float badgeVerticalOffset = (mBgBadgeBounds.height() * 0.5f) + badgeHalfHeight - mBadgeBounds.bottom + modelBadgeOffset; canvas.drawText( model.getBadgeTitle(), badgeBoundsHorizontalOffset, badgeVerticalOffset + mBadgeBounds.height() - (mBadgeBounds.height() * model.mBadgeFraction), mBadgePaint ); } } // Method to transform current fraction of NTB and position private void updateCurrentModel( final Model model, final float leftOffset, final float topOffset, final float titleTranslate, final float interpolation, final float matrixCenterX, final float matrixCenterY, final float matrixScale, final float textScale, final int textAlpha ) { if (mIsTitled && mTitleMode == TitleMode.ACTIVE) model.mIconMatrix.setTranslate( leftOffset, topOffset - (interpolation * (topOffset - titleTranslate)) ); model.mIconMatrix.postScale( model.mInactiveIconScale + matrixScale, model.mInactiveIconScale + matrixScale, matrixCenterX, matrixCenterY + (mIsTitled && mTitleMode == TitleMode.ACTIVE ? mTitleMargin * 0.5f * interpolation : 0.0f) ); mModelTitlePaint.setTextSize(mModelTitleSize * textScale); if (mTitleMode == TitleMode.ACTIVE) mModelTitlePaint.setAlpha(textAlpha); } // Method to transform last fraction of NTB and position private void updateLastModel( final Model model, final float leftOffset, final float topOffset, final float titleTranslate, final float lastInterpolation, final float matrixCenterX, final float matrixCenterY, final float matrixLastScale, final float textLastScale, final int textLastAlpha ) { if (mIsTitled && mTitleMode == TitleMode.ACTIVE) model.mIconMatrix.setTranslate( leftOffset, titleTranslate + (lastInterpolation * (topOffset - titleTranslate)) ); model.mIconMatrix.postScale( model.mInactiveIconScale + model.mActiveIconScaleBy - matrixLastScale, model.mInactiveIconScale + model.mActiveIconScaleBy - matrixLastScale, matrixCenterX, matrixCenterY + (mIsTitled && mTitleMode == TitleMode.ACTIVE ? mTitleMargin * 0.5f - (mTitleMargin * 0.5f * lastInterpolation) : 0.0f) ); mModelTitlePaint.setTextSize(mModelTitleSize * textLastScale); if (mTitleMode == TitleMode.ACTIVE) mModelTitlePaint.setAlpha(textLastAlpha); } // Method to transform others fraction of NTB and position private void updateInactiveModel( final Model model, final float leftOffset, final float topOffset, final float matrixCenterX, final float matrixCenterY ) { if (mIsTitled && mTitleMode == TitleMode.ACTIVE) model.mIconMatrix.setTranslate(leftOffset, topOffset); model.mIconMatrix.postScale( model.mInactiveIconScale, model.mInactiveIconScale, matrixCenterX, matrixCenterY ); mModelTitlePaint.setTextSize(mModelTitleSize); if (mTitleMode == TitleMode.ACTIVE) mModelTitlePaint.setAlpha(MIN_ALPHA); } @Override public void onPageScrolled(int position, float positionOffset, final int positionOffsetPixels) { // If we animate, don`t call this if (!mIsSetIndexFromTabBar) { mIsResizeIn = position < mIndex; mLastIndex = mIndex; mIndex = position; mStartPointerX = position * mModelSize; mEndPointerX = mStartPointerX + mModelSize; updateIndicatorPosition(positionOffset); } if (mOnPageChangeListener != null) mOnPageChangeListener.onPageScrolled(position, positionOffset, positionOffsetPixels); } @Override public void onPageSelected(final int position) { // If VP idle, so update if (mScrollState == ViewPager.SCROLL_STATE_IDLE) { mIsResizeIn = position < mIndex; mLastIndex = mIndex; mIndex = position; postInvalidate(); } } @Override public void onPageScrollStateChanged(final int state) { // If VP idle, reset to MIN_FRACTION if (state == ViewPager.SCROLL_STATE_IDLE) { mFraction = MIN_FRACTION; mIsSetIndexFromTabBar = false; if (mOnPageChangeListener != null) mOnPageChangeListener.onPageSelected(mIndex); else { if (mOnTabBarSelectedIndexListener != null) mOnTabBarSelectedIndexListener.onEndTabSelected(mModels.get(mIndex), mIndex); } } mScrollState = state; if (mOnPageChangeListener != null) mOnPageChangeListener.onPageScrollStateChanged(state); } @Override public void onRestoreInstanceState(Parcelable state) { final SavedState savedState = (SavedState) state; super.onRestoreInstanceState(savedState.getSuperState()); mIndex = savedState.index; requestLayout(); } @Override public Parcelable onSaveInstanceState() { final Parcelable superState = super.onSaveInstanceState(); final SavedState savedState = new SavedState(superState); savedState.index = mIndex; return savedState; } static class SavedState extends BaseSavedState { int index; public SavedState(Parcelable superState) { super(superState); } private SavedState(Parcel in) { super(in); index = in.readInt(); } @Override public void writeToParcel(Parcel dest, int flags) { super.writeToParcel(dest, flags); dest.writeInt(index); } @SuppressWarnings("UnusedDeclaration") public static final Creator<SavedState> CREATOR = new Creator<SavedState>() { @Override public SavedState createFromParcel(Parcel in) { return new SavedState(in); } @Override public SavedState[] newArray(int size) { return new SavedState[size]; } }; } // Model class public static class Model { private String mTitle = ""; private int mColor; private Bitmap mIcon; private Matrix mIconMatrix = new Matrix(); private String mBadgeTitle = ""; private String mTempBadgeTitle = ""; private float mBadgeFraction; private boolean mIsBadgeShowed; private boolean mIsBadgeUpdated; private ValueAnimator mBadgeAnimator = new ValueAnimator(); private float mInactiveIconScale; private float mActiveIconScaleBy; public Model(final Drawable icon, final int color) { mColor = color; if (icon != null) { if(icon instanceof BitmapDrawable) { mIcon = ((BitmapDrawable) icon).getBitmap(); } else { mIcon = Bitmap.createBitmap(icon.getIntrinsicWidth(),icon.getIntrinsicHeight(), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(mIcon); icon.setBounds(0, 0, canvas.getWidth(), canvas.getHeight()); icon.draw(canvas); } } else { mIcon = Bitmap.createBitmap(1, 1, Bitmap.Config.RGB_565); } mBadgeAnimator.addListener(new Animator.AnimatorListener() { @Override public void onAnimationStart(final Animator animation) { } @Override public void onAnimationEnd(final Animator animation) { // Detect whether we just update text and don`t reset show state if (!mIsBadgeUpdated) mIsBadgeShowed = !mIsBadgeShowed; else mIsBadgeUpdated = false; } @Override public void onAnimationCancel(final Animator animation) { } @Override public void onAnimationRepeat(final Animator animation) { // Change title when we update and don`t see the title if (mIsBadgeUpdated) mBadgeTitle = mTempBadgeTitle; } }); } public Model(final Drawable icon, final int color, final String title) { this(icon, color); mTitle = title; } public Model(final Drawable icon, final int color, final String title, final String badgeTitle) { this(icon, color, title); mBadgeTitle = badgeTitle; } public String getTitle() { return mTitle; } public void setTitle(final String title) { mTitle = title; } public int getColor() { return mColor; } public void setColor(final int color) { mColor = color; } public boolean isBadgeShowed() { return mIsBadgeShowed; } public String getBadgeTitle() { return mBadgeTitle; } public void setBadgeTitle(final String badgeTitle) { mBadgeTitle = badgeTitle; } // If your badge is visible on screen, so you can update title with animation public void updateBadgeTitle(final String badgeTitle) { if (!mIsBadgeShowed) return; if (mBadgeAnimator.isRunning()) mBadgeAnimator.end(); mTempBadgeTitle = badgeTitle; mIsBadgeUpdated = true; mBadgeAnimator.setFloatValues(MAX_FRACTION, MIN_FRACTION); mBadgeAnimator.setDuration(DEFAULT_BADGE_REFRESH_ANIMATION_DURATION); mBadgeAnimator.setRepeatMode(ValueAnimator.REVERSE); mBadgeAnimator.setRepeatCount(1); mBadgeAnimator.start(); } public void toggleBadge() { if (mBadgeAnimator.isRunning()) mBadgeAnimator.end(); if (mIsBadgeShowed) hideBadge(); else showBadge(); } public void showBadge() { mIsBadgeUpdated = false; if (mBadgeAnimator.isRunning()) mBadgeAnimator.end(); if (mIsBadgeShowed) return; mBadgeAnimator.setFloatValues(MIN_FRACTION, MAX_FRACTION); mBadgeAnimator.setInterpolator(DECELERATE_INTERPOLATOR); mBadgeAnimator.setDuration(DEFAULT_BADGE_ANIMATION_DURATION); mBadgeAnimator.setRepeatMode(ValueAnimator.RESTART); mBadgeAnimator.setRepeatCount(0); mBadgeAnimator.start(); } public void hideBadge() { mIsBadgeUpdated = false; if (mBadgeAnimator.isRunning()) mBadgeAnimator.end(); if (!mIsBadgeShowed) return; mBadgeAnimator.setFloatValues(MAX_FRACTION, MIN_FRACTION); mBadgeAnimator.setInterpolator(ACCELERATE_INTERPOLATOR); mBadgeAnimator.setDuration(DEFAULT_BADGE_ANIMATION_DURATION); mBadgeAnimator.setRepeatMode(ValueAnimator.RESTART); mBadgeAnimator.setRepeatCount(0); mBadgeAnimator.start(); } } // Custom scroller with custom scroll duration private class ResizeViewPagerScroller extends Scroller { public ResizeViewPagerScroller(Context context) { super(context, new AccelerateDecelerateInterpolator()); } @Override public void startScroll(int startX, int startY, int dx, int dy, int duration) { super.startScroll(startX, startY, dx, dy, mAnimationDuration); } @Override public void startScroll(int startX, int startY, int dx, int dy) { super.startScroll(startX, startY, dx, dy, mAnimationDuration); } } // Resize interpolator to create smooth effect on pointer according to inspiration design // This is like improved accelerated and decelerated interpolator private class ResizeInterpolator implements Interpolator { // Spring factor private final float mFactor = 1.0f; // Check whether side we move private boolean mResizeIn; @Override public float getInterpolation(final float input) { if (mResizeIn) return (float) (1.0f - Math.pow((1.0f - input), 2.0f * mFactor)); else return (float) (Math.pow(input, 2.0f * mFactor)); } public float getResizeInterpolation(final float input, final boolean resizeIn) { mResizeIn = resizeIn; return getInterpolation(input); } } // Model title mode public enum TitleMode { ALL, ACTIVE } // Model badge position public enum BadgePosition { LEFT(LEFT_FRACTION), CENTER(CENTER_FRACTION), RIGHT(RIGHT_FRACTION); private float mPositionFraction; BadgePosition() { mPositionFraction = RIGHT_FRACTION; } BadgePosition(final float positionFraction) { mPositionFraction = positionFraction; } } // Model badge gravity public enum BadgeGravity { TOP, BOTTOM } // Out listener for selected index public interface OnTabBarSelectedIndexListener { void onStartTabSelected(final Model model, final int index); void onEndTabSelected(final Model model, final int index); } }
library/src/main/java/com/gigamole/library/NavigationTabBar.java
/* * Copyright (C) 2015 Basil Miller * * 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.gigamole.library; import android.animation.Animator; import android.animation.ValueAnimator; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.PorterDuff; import android.graphics.PorterDuffColorFilter; import android.graphics.PorterDuffXfermode; import android.graphics.Rect; import android.graphics.RectF; import android.graphics.Typeface; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.os.Parcel; import android.os.Parcelable; import android.support.v4.view.ViewPager; import android.text.TextPaint; import android.text.TextUtils; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import android.view.animation.AccelerateDecelerateInterpolator; import android.view.animation.AccelerateInterpolator; import android.view.animation.DecelerateInterpolator; import android.view.animation.Interpolator; import android.view.animation.LinearInterpolator; import android.widget.Scroller; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Random; /** * Created by GIGAMOLE on 24.03.2016. */ public class NavigationTabBar extends View implements ViewPager.OnPageChangeListener { // NTP constants private final static String PREVIEW_BADGE = "0"; private final static String PREVIEW_TITLE = "Title"; private final static int INVALID_INDEX = -1; private final static int DEFAULT_BADGE_ANIMATION_DURATION = 200; private final static int DEFAULT_BADGE_REFRESH_ANIMATION_DURATION = 100; private final static int DEFAULT_ANIMATION_DURATION = 300; private final static int DEFAULT_INACTIVE_COLOR = Color.parseColor("#9f90af"); private final static int DEFAULT_ACTIVE_COLOR = Color.WHITE; private final static float MIN_FRACTION = 0.0f; private final static float MAX_FRACTION = 1.0f; private final static int MIN_ALPHA = 0; private final static int MAX_ALPHA = 255; private final static float ACTIVE_ICON_SCALE_BY = 0.35f; private final static float ICON_SIZE_FRACTION = 0.4f; private final static float TITLE_ACTIVE_ICON_SCALE_BY = 0.25f; private final static float TITLE_ICON_SIZE_FRACTION = 0.4f; private final static float TITLE_ACTIVE_SCALE_BY = 0.2f; private final static float TITLE_SIZE_FRACTION = 0.2f; private final static float TITLE_MARGIN_FRACTION = 0.15f; private final static float BADGE_HORIZONTAL_FRACTION = 0.5f; private final static float BADGE_VERTICAL_FRACTION = 0.75f; private final static float BADGE_TITLE_SIZE_FRACTION = 0.85f; private final static int ALL_INDEX = 0; private final static int ACTIVE_INDEX = 1; private final static int LEFT_INDEX = 0; private final static int CENTER_INDEX = 1; private final static int RIGHT_INDEX = 2; private final static int TOP_INDEX = 0; private final static int BOTTOM_INDEX = 1; private final static float LEFT_FRACTION = 0.25f; private final static float CENTER_FRACTION = 0.5f; private final static float RIGHT_FRACTION = 0.75f; private final static Interpolator DECELERATE_INTERPOLATOR = new DecelerateInterpolator(); private final static Interpolator ACCELERATE_INTERPOLATOR = new AccelerateInterpolator(); // NTP and pointer bounds private RectF mBounds = new RectF(); private RectF mPointerBounds = new RectF(); // Badge bounds and bg badge bounds final Rect mBadgeBounds = new Rect(); final RectF mBgBadgeBounds = new RectF(); // Canvas, where all of other canvas will be merged private Bitmap mBitmap; private Canvas mCanvas; // Canvas with icons private Bitmap mIconsBitmap; private Canvas mIconsCanvas; // Canvas for our rect pointer private Bitmap mPointerBitmap; private Canvas mPointerCanvas; // Main paint private Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG) { { setDither(true); setStyle(Style.FILL); } }; // Pointer paint private Paint mPointerPaint = new Paint(Paint.ANTI_ALIAS_FLAG) { { setDither(true); setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN)); } }; // Icons paint private Paint mIconPaint = new Paint(Paint.ANTI_ALIAS_FLAG) { { setDither(true); } }; // Paint for icon mask pointer final Paint mIconPointerPaint = new Paint(Paint.ANTI_ALIAS_FLAG) { { setStyle(Style.FILL); setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN)); } }; // Paint for model title final Paint mModelTitlePaint = new TextPaint(Paint.ANTI_ALIAS_FLAG) { { setDither(true); setColor(Color.WHITE); setTextAlign(Align.CENTER); } }; // Paint for badge final Paint mBadgePaint = new TextPaint(Paint.ANTI_ALIAS_FLAG) { { setDither(true); setTextAlign(Align.CENTER); setFakeBoldText(true); } }; // Variables for animator private ValueAnimator mAnimator = new ValueAnimator(); private ResizeInterpolator mResizeInterpolator = new ResizeInterpolator(); private int mAnimationDuration; // NTP models private ArrayList<Model> mModels = new ArrayList<>(); // Variables for ViewPager private ViewPager mViewPager; private ViewPager.OnPageChangeListener mOnPageChangeListener; private int mScrollState; // Tab listener private OnTabBarSelectedIndexListener mOnTabBarSelectedIndexListener; private ValueAnimator.AnimatorListener mAnimatorListener; // Variables for sizes private float mModelSize; private int mIconSize; // Corners radius for rect mode private float mCornersRadius; // Model title size and margin private float mModelTitleSize; private float mTitleMargin; // Model badge title size and margin private float mBadgeMargin; private float mBadgeTitleSize; // Model title mode: active ar all private TitleMode mTitleMode; // Model badge position: left, center or right private BadgePosition mBadgePosition; // Model badge gravity: top or bottom private BadgeGravity mBadgeGravity; // Indexes private int mLastIndex = INVALID_INDEX; private int mIndex = INVALID_INDEX; // General fraction value private float mFraction; // Coordinates of pointer private float mStartPointerX; private float mEndPointerX; private float mPointerLeftTop; private float mPointerRightBottom; // Detect if model has title private boolean mIsTitled; // Detect if model has badge private boolean mIsBadged; // Detect if model badge have custom typeface private boolean mIsBadgeUseTypeface; // Detect if is bar mode or indicator pager mode private boolean mIsViewPagerMode; // Detect whether the horizontal orientation private boolean mIsHorizontalOrientation; // Detect if we move from left to right private boolean mIsResizeIn; // Detect if we get action down event private boolean mIsActionDown; // Detect if we get action down event on pointer private boolean mIsPointerActionDown; // Detect when we set index from tab bar nor from ViewPager private boolean mIsSetIndexFromTabBar; // Color variables private int mInactiveColor; private int mActiveColor; // Custom typeface private Typeface mTypeface; public NavigationTabBar(final Context context) { this(context, null); } public NavigationTabBar(final Context context, final AttributeSet attrs) { this(context, attrs, 0); } public NavigationTabBar(final Context context, final AttributeSet attrs, final int defStyleAttr) { super(context, attrs, defStyleAttr); //Init NTB // Always draw setWillNotDraw(false); // More speed! setLayerType(LAYER_TYPE_HARDWARE, null); final TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.NavigationTabBar); try { setIsTitled( typedArray.getBoolean(R.styleable.NavigationTabBar_ntb_titled, false) ); setIsBadged( typedArray.getBoolean(R.styleable.NavigationTabBar_ntb_badged, false) ); setIsBadgeUseTypeface( typedArray.getBoolean(R.styleable.NavigationTabBar_ntb_badge_use_typeface, false) ); setTitleMode( typedArray.getInt(R.styleable.NavigationTabBar_ntb_title_mode, ALL_INDEX) ); setBadgePosition( typedArray.getInt(R.styleable.NavigationTabBar_ntb_badge_position, RIGHT_INDEX) ); setBadgeGravity( typedArray.getInt(R.styleable.NavigationTabBar_ntb_badge_gravity, TOP_INDEX) ); setTypeface( typedArray.getString(R.styleable.NavigationTabBar_ntb_typeface) ); setInactiveColor( typedArray.getColor( R.styleable.NavigationTabBar_ntb_inactive_color, DEFAULT_INACTIVE_COLOR ) ); setActiveColor( typedArray.getColor( R.styleable.NavigationTabBar_ntb_active_color, DEFAULT_ACTIVE_COLOR ) ); setAnimationDuration( typedArray.getInteger( R.styleable.NavigationTabBar_ntb_animation_duration, DEFAULT_ANIMATION_DURATION ) ); setCornersRadius( typedArray.getDimension(R.styleable.NavigationTabBar_ntb_corners_radius, 0.0f) ); // Init animator mAnimator.setFloatValues(MIN_FRACTION, MAX_FRACTION); mAnimator.setInterpolator(new LinearInterpolator()); mAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(final ValueAnimator animation) { updateIndicatorPosition((Float) animation.getAnimatedValue()); } }); // Set preview models if (isInEditMode()) { // Get preview colors String[] previewColors = null; try { final int previewColorsId = typedArray.getResourceId( R.styleable.NavigationTabBar_ntb_preview_colors, 0 ); previewColors = previewColorsId == 0 ? null : typedArray.getResources().getStringArray(previewColorsId); } catch (Exception exception) { previewColors = null; exception.printStackTrace(); } finally { if (previewColors == null) previewColors = typedArray.getResources().getStringArray(R.array.default_preview); for (String previewColor : previewColors) mModels.add(new Model(null, Color.parseColor(previewColor))); requestLayout(); } } } finally { typedArray.recycle(); } } public int getAnimationDuration() { return mAnimationDuration; } public void setAnimationDuration(final int animationDuration) { mAnimationDuration = animationDuration; mAnimator.setDuration(mAnimationDuration); resetScroller(); } public ArrayList<Model> getModels() { return mModels; } public void setModels(final ArrayList<Model> models) { //Set update listeners to badge model animation for (final Model model : models) { model.mBadgeAnimator.removeAllUpdateListeners(); model.mBadgeAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(final ValueAnimator animation) { model.mBadgeFraction = (float) animation.getAnimatedValue(); postInvalidate(); } }); } mModels.clear(); mModels = models; requestLayout(); } public boolean isTitled() { return mIsTitled; } public void setIsTitled(final boolean isTitled) { mIsTitled = isTitled; requestLayout(); } public boolean isBadged() { return mIsBadged; } public void setIsBadged(final boolean isBadged) { mIsBadged = isBadged; requestLayout(); } public boolean isBadgeUseTypeface() { return mIsBadgeUseTypeface; } public void setIsBadgeUseTypeface(final boolean isBadgeUseTypeface) { mIsBadgeUseTypeface = isBadgeUseTypeface; setBadgeTypeface(); postInvalidate(); } public TitleMode getTitleMode() { return mTitleMode; } private void setTitleMode(final int index) { switch (index) { case ACTIVE_INDEX: setTitleMode(TitleMode.ACTIVE); break; case ALL_INDEX: default: setTitleMode(TitleMode.ALL); } } public void setTitleMode(final TitleMode titleMode) { mTitleMode = titleMode; postInvalidate(); } public BadgePosition getBadgePosition() { return mBadgePosition; } private void setBadgePosition(final int index) { switch (index) { case LEFT_INDEX: setBadgePosition(BadgePosition.LEFT); break; case CENTER_INDEX: setBadgePosition(BadgePosition.CENTER); break; case RIGHT_INDEX: default: setBadgePosition(BadgePosition.RIGHT); } } public void setBadgePosition(final BadgePosition badgePosition) { mBadgePosition = badgePosition; postInvalidate(); } public BadgeGravity getBadgeGravity() { return mBadgeGravity; } private void setBadgeGravity(final int index) { switch (index) { case BOTTOM_INDEX: setBadgeGravity(BadgeGravity.BOTTOM); break; case TOP_INDEX: default: setBadgeGravity(BadgeGravity.TOP); } } public void setBadgeGravity(final BadgeGravity badgeGravity) { mBadgeGravity = badgeGravity; requestLayout(); } public Typeface getTypeface() { return mTypeface; } public void setTypeface(final String typeface) { Typeface tempTypeface; try { tempTypeface = Typeface.createFromAsset(getContext().getAssets(), typeface); } catch (Exception e) { tempTypeface = Typeface.create(Typeface.DEFAULT, Typeface.NORMAL); e.printStackTrace(); } setTypeface(tempTypeface); } public void setTypeface(final Typeface typeface) { mTypeface = typeface; mModelTitlePaint.setTypeface(typeface); setBadgeTypeface(); postInvalidate(); } private void setBadgeTypeface() { mBadgePaint.setTypeface( mIsBadgeUseTypeface ? mTypeface : Typeface.create(Typeface.DEFAULT, Typeface.NORMAL) ); } public int getActiveColor() { return mActiveColor; } public void setActiveColor(final int activeColor) { mActiveColor = activeColor; mIconPointerPaint.setColor(activeColor); postInvalidate(); } public int getInactiveColor() { return mInactiveColor; } public void setInactiveColor(final int inactiveColor) { mInactiveColor = inactiveColor; // Set color filter to wrap icons with inactive color mIconPaint.setColorFilter(new PorterDuffColorFilter(inactiveColor, PorterDuff.Mode.SRC_IN)); mModelTitlePaint.setColor(mInactiveColor); postInvalidate(); } public float getCornersRadius() { return mCornersRadius; } public void setCornersRadius(final float cornersRadius) { mCornersRadius = cornersRadius; postInvalidate(); } public float getBadgeMargin() { return mBadgeMargin; } public float getBarHeight() { return mBounds.height(); } public OnTabBarSelectedIndexListener getOnTabBarSelectedIndexListener() { return mOnTabBarSelectedIndexListener; } // Set on tab bar selected index listener where you can trigger action onStart or onEnd public void setOnTabBarSelectedIndexListener(final OnTabBarSelectedIndexListener onTabBarSelectedIndexListener) { mOnTabBarSelectedIndexListener = onTabBarSelectedIndexListener; if (mAnimatorListener == null) mAnimatorListener = new Animator.AnimatorListener() { @Override public void onAnimationStart(final Animator animation) { if (mOnTabBarSelectedIndexListener != null) mOnTabBarSelectedIndexListener.onStartTabSelected(mModels.get(mIndex), mIndex); } @Override public void onAnimationEnd(final Animator animation) { if (mOnTabBarSelectedIndexListener != null) mOnTabBarSelectedIndexListener.onEndTabSelected(mModels.get(mIndex), mIndex); } @Override public void onAnimationCancel(final Animator animation) { } @Override public void onAnimationRepeat(final Animator animation) { } }; mAnimator.removeListener(mAnimatorListener); mAnimator.addListener(mAnimatorListener); } public void setViewPager(final ViewPager viewPager) { // Detect whether ViewPager mode if (viewPager == null) { mIsViewPagerMode = false; return; } if (mViewPager == viewPager) return; if (mViewPager != null) mViewPager.setOnPageChangeListener(null); if (viewPager.getAdapter() == null) throw new IllegalStateException("ViewPager does not provide adapter instance."); mIsViewPagerMode = true; mViewPager = viewPager; mViewPager.addOnPageChangeListener(this); resetScroller(); postInvalidate(); } public void setViewPager(final ViewPager viewPager, int index) { setViewPager(viewPager); mIndex = index; if (mIsViewPagerMode) mViewPager.setCurrentItem(index, true); postInvalidate(); } // Reset scroller and reset scroll duration equals to animation duration private void resetScroller() { if (mViewPager == null) return; try { final Field scrollerField = ViewPager.class.getDeclaredField("mScroller"); scrollerField.setAccessible(true); final ResizeViewPagerScroller scroller = new ResizeViewPagerScroller(getContext()); scrollerField.set(mViewPager, scroller); } catch (Exception e) { e.printStackTrace(); } } public void setOnPageChangeListener(final ViewPager.OnPageChangeListener listener) { mOnPageChangeListener = listener; } public int getModelIndex() { return mIndex; } public void setModelIndex(int index) { setModelIndex(index, false); } // Set model index from touch or programmatically public void setModelIndex(int index, boolean force) { if (mAnimator.isRunning()) return; if (mModels.isEmpty()) return; // This check gives us opportunity to have an non selected model if (mIndex == INVALID_INDEX) force = true; // Detect if last is the same if (index == mIndex) return; // Snap index to models size index = Math.max(0, Math.min(index, mModels.size() - 1)); mIsResizeIn = index < mIndex; mLastIndex = mIndex; mIndex = index; mIsSetIndexFromTabBar = true; if (mIsViewPagerMode) { if (mViewPager == null) throw new IllegalStateException("ViewPager is null."); mViewPager.setCurrentItem(index, true); } // Set startX and endX for animation, where we animate two sides of rect with different interpolation mStartPointerX = mPointerLeftTop; mEndPointerX = mIndex * mModelSize; // If it force, so update immediately, else animate // This happens if we set index onCreate or something like this // You can use force param or call this method in some post() if (force) updateIndicatorPosition(MAX_FRACTION); else mAnimator.start(); } private void updateIndicatorPosition(final float fraction) { // Update general fraction mFraction = fraction; // Set the pointer left top side coordinate mPointerLeftTop = mStartPointerX + (mResizeInterpolator.getResizeInterpolation(fraction, mIsResizeIn) * (mEndPointerX - mStartPointerX)); // Set the pointer right bottom side coordinate mPointerRightBottom = (mStartPointerX + mModelSize) + (mResizeInterpolator.getResizeInterpolation(fraction, !mIsResizeIn) * (mEndPointerX - mStartPointerX)); // Update pointer postInvalidate(); } // Update NTP private void notifyDataSetChanged() { postInvalidate(); } @Override public boolean onTouchEvent(final MotionEvent event) { // Return if animation is running if (mAnimator.isRunning()) return true; // If is not idle state, return if (mScrollState != ViewPager.SCROLL_STATE_IDLE) return true; switch (event.getAction()) { case MotionEvent.ACTION_DOWN: // Action down touch mIsActionDown = true; if (!mIsViewPagerMode) break; // Detect if we touch down on pointer, later to move if (mIsHorizontalOrientation) mIsPointerActionDown = (int) (event.getX() / mModelSize) == mIndex; else mIsPointerActionDown = (int) (event.getY() / mModelSize) == mIndex; break; case MotionEvent.ACTION_MOVE: // If pointer touched, so move if (mIsPointerActionDown) { if (mIsHorizontalOrientation) mViewPager.setCurrentItem((int) (event.getX() / mModelSize), true); else mViewPager.setCurrentItem((int) (event.getY() / mModelSize), true); break; } if (mIsActionDown) break; case MotionEvent.ACTION_UP: // Press up and set model index relative to current coordinate if (mIsActionDown) { if (mIsHorizontalOrientation) setModelIndex((int) (event.getX() / mModelSize)); else setModelIndex((int) (event.getY() / mModelSize)); } case MotionEvent.ACTION_CANCEL: case MotionEvent.ACTION_OUTSIDE: default: // Reset action touch variables mIsPointerActionDown = false; mIsActionDown = false; break; } return true; } @Override protected void onMeasure(final int widthMeasureSpec, final int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); // Get measure size final int width = MeasureSpec.getSize(widthMeasureSpec); final int height = MeasureSpec.getSize(heightMeasureSpec); if (mModels.isEmpty() || width == 0 || height == 0) return; // Detect orientation and calculate icon size if (width > height) { mIsHorizontalOrientation = true; // Get smaller side float side = mModelSize > height ? height : mModelSize; if (mIsBadged) side -= side * TITLE_SIZE_FRACTION; mModelSize = (float) width / (float) mModels.size(); mIconSize = (int) (side * (mIsTitled ? TITLE_ICON_SIZE_FRACTION : ICON_SIZE_FRACTION)); mModelTitleSize = side * TITLE_SIZE_FRACTION; mTitleMargin = side * TITLE_MARGIN_FRACTION; // If is badged mode, so get vars and set paint with default bounds if (mIsBadged) { mBadgeTitleSize = mModelTitleSize * BADGE_TITLE_SIZE_FRACTION; final Rect badgeBounds = new Rect(); mBadgePaint.setTextSize(mBadgeTitleSize); mBadgePaint.getTextBounds(PREVIEW_BADGE, 0, 1, badgeBounds); mBadgeMargin = (badgeBounds.height() * 0.5f) + (mBadgeTitleSize * BADGE_HORIZONTAL_FRACTION * BADGE_VERTICAL_FRACTION); } } else { mIsHorizontalOrientation = false; mIsTitled = false; mIsBadged = false; mModelSize = (float) height / (float) mModels.size(); mIconSize = (int) ((mModelSize > width ? width : mModelSize) * ICON_SIZE_FRACTION); } // Set bounds for NTB mBounds.set(0.0f, 0.0f, width, height - mBadgeMargin); // Set main bitmap mBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); mCanvas = new Canvas(mBitmap); // Set pointer canvas mPointerBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); mPointerCanvas = new Canvas(mPointerBitmap); // Set icons canvas mIconsBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); mIconsCanvas = new Canvas(mIconsBitmap); // Set scale fraction for icons for (Model model : mModels) { final float originalIconSize = model.mIcon.getWidth() > model.mIcon.getHeight() ? model.mIcon.getWidth() : model.mIcon.getHeight(); model.mInactiveIconScale = (float) mIconSize / originalIconSize; model.mActiveIconScaleBy = model.mInactiveIconScale * (mIsTitled ? TITLE_ACTIVE_ICON_SCALE_BY : ACTIVE_ICON_SCALE_BY); } // Set start position of pointer for preview or on start if (isInEditMode() || !mIsViewPagerMode) { mIsSetIndexFromTabBar = true; // Set random in preview mode if (isInEditMode()) { mIndex = new Random().nextInt(mModels.size()); if (mIsBadged) for (int i = 0; i < mModels.size(); i++) { final Model model = mModels.get(i); if (i == mIndex) { model.mBadgeFraction = MAX_FRACTION; model.showBadge(); } else { model.mBadgeFraction = MIN_FRACTION; model.hideBadge(); } } } mStartPointerX = mIndex * mModelSize; mEndPointerX = mStartPointerX; updateIndicatorPosition(MAX_FRACTION); } } @Override protected void onDraw(final Canvas canvas) { if (mCanvas == null || mPointerCanvas == null || mIconsCanvas == null) return; // Reset and clear canvases mCanvas.drawColor(0, PorterDuff.Mode.CLEAR); mPointerCanvas.drawColor(0, PorterDuff.Mode.CLEAR); mIconsCanvas.drawColor(0, PorterDuff.Mode.CLEAR); // Get pointer badge margin for gravity final float pointerBadgeMargin = mBadgeGravity == BadgeGravity.TOP ? mBadgeMargin : 0.0f; // Draw our model colors for (int i = 0; i < mModels.size(); i++) { mPaint.setColor(mModels.get(i).getColor()); if (mIsHorizontalOrientation) { final float left = mModelSize * i; final float right = left + mModelSize; mCanvas.drawRect( left, pointerBadgeMargin, right, mBounds.height() + pointerBadgeMargin, mPaint ); } else { final float top = mModelSize * i; final float bottom = top + mModelSize; mCanvas.drawRect(0.0f, top, mBounds.width(), bottom, mPaint); } } // Set bound of pointer if (mIsHorizontalOrientation) mPointerBounds.set( mPointerLeftTop, pointerBadgeMargin, mPointerRightBottom, mBounds.height() + pointerBadgeMargin ); else mPointerBounds.set(0.0f, mPointerLeftTop, mBounds.width(), mPointerRightBottom); // Draw pointer for model colors if (mCornersRadius == 0) mPointerCanvas.drawRect(mPointerBounds, mPaint); else mPointerCanvas.drawRoundRect(mPointerBounds, mCornersRadius, mCornersRadius, mPaint); // Draw pointer into main canvas mCanvas.drawBitmap(mPointerBitmap, 0.0f, 0.0f, mPointerPaint); // Draw model icons for (int i = 0; i < mModels.size(); i++) { final Model model = mModels.get(i); // Variables to center our icons final float leftOffset; final float topOffset; final float matrixCenterX; final float matrixCenterY; // Set vars for icon when model with title or without final float iconMarginTitleHeight = mIconSize + mTitleMargin + mModelTitleSize; final float leftTitleOffset = (mModelSize * i) + (mModelSize * 0.5f); final float topTitleOffset = mBounds.height() - (mBounds.height() - iconMarginTitleHeight) * 0.5f; if (mIsHorizontalOrientation) { leftOffset = (mModelSize * i) + (mModelSize - model.mIcon.getWidth()) * 0.5f; topOffset = (mBounds.height() - model.mIcon.getHeight()) * 0.5f; matrixCenterX = leftOffset + model.mIcon.getWidth() * 0.5f; matrixCenterY = topOffset + model.mIcon.getHeight() * 0.5f + (mIsTitled && mTitleMode == TitleMode.ALL ? mTitleMargin * 0.5f : 0.0f); } else { leftOffset = (mBounds.width() - model.mIcon.getWidth()) * 0.5f; topOffset = (mModelSize * i) + (mModelSize - model.mIcon.getHeight()) * 0.5f; matrixCenterX = leftOffset + model.mIcon.getWidth() * 0.5f; matrixCenterY = topOffset + model.mIcon.getHeight() * 0.5f; } // Title translate position final float titleTranslate = -model.mIcon.getHeight() + topTitleOffset - mTitleMargin * 0.5f; // Translate icon to model center model.mIconMatrix.setTranslate( leftOffset, (mIsTitled && mTitleMode == TitleMode.ALL) ? titleTranslate : topOffset ); // Get interpolated fraction for left last and current models final float interpolation = mResizeInterpolator.getResizeInterpolation(mFraction, true); final float lastInterpolation = mResizeInterpolator.getResizeInterpolation(mFraction, false); // Scale value relative to interpolation final float matrixScale = model.mActiveIconScaleBy * interpolation; final float matrixLastScale = model.mActiveIconScaleBy * lastInterpolation; // Get title alpha relative to interpolation final int titleAlpha = (int) (MAX_ALPHA * interpolation); final int titleLastAlpha = MAX_ALPHA - (int) (MAX_ALPHA * lastInterpolation); // Get title scale relative to interpolation final float titleScale = MAX_FRACTION + (interpolation * TITLE_ACTIVE_SCALE_BY); final float titleLastScale = (MAX_FRACTION + TITLE_ACTIVE_SCALE_BY) - (lastInterpolation * TITLE_ACTIVE_SCALE_BY); // Check if we handle models from touch on NTP or from ViewPager // There is a strange logic of ViewPager onPageScrolled method, so it is if (mIsSetIndexFromTabBar) { if (mIndex == i) updateCurrentModel( model, leftOffset, topOffset, titleTranslate, interpolation, matrixCenterX, matrixCenterY, matrixScale, titleScale, titleAlpha ); else if (mLastIndex == i) updateLastModel( model, leftOffset, topOffset, titleTranslate, lastInterpolation, matrixCenterX, matrixCenterY, matrixLastScale, titleLastScale, titleLastAlpha ); else updateInactiveModel( model, leftOffset, topOffset, matrixCenterX, matrixCenterY ); } else { if (i != mIndex && i != mIndex + 1) updateInactiveModel( model, leftOffset, topOffset, matrixCenterX, matrixCenterY ); else if (i == mIndex + 1) updateCurrentModel( model, leftOffset, topOffset, titleTranslate, interpolation, matrixCenterX, matrixCenterY, matrixScale, titleScale, titleAlpha ); else if (i == mIndex) updateLastModel( model, leftOffset, topOffset, titleTranslate, lastInterpolation, matrixCenterX, matrixCenterY, matrixLastScale, titleLastScale, titleLastAlpha ); } // Draw model icon mIconsCanvas.drawBitmap(model.mIcon, model.mIconMatrix, mIconPaint); if (mIsTitled) mIconsCanvas.drawText( isInEditMode() ? PREVIEW_TITLE : model.getTitle(), leftTitleOffset, topTitleOffset, mModelTitlePaint ); } // Draw pointer with active color to wrap out active icon if (mCornersRadius == 0) mIconsCanvas.drawRect(mPointerBounds, mIconPointerPaint); else mIconsCanvas.drawRoundRect(mPointerBounds, mCornersRadius, mCornersRadius, mIconPointerPaint); // Draw general bitmap canvas.drawBitmap(mBitmap, 0.0f, 0.0f, null); // Draw icons bitmap on top canvas.drawBitmap( mIconsBitmap, 0.0f, pointerBadgeMargin, null); // If is not badged, exit if (!mIsBadged) return; // Model badge margin and offset relative to gravity mode final float modelBadgeMargin = mBadgeGravity == BadgeGravity.TOP ? mBadgeMargin : mBounds.height(); final float modelBadgeOffset = mBadgeGravity == BadgeGravity.TOP ? 0.0f : mBounds.height() - mBadgeMargin; for (int i = 0; i < mModels.size(); i++) { final Model model = mModels.get(i); // Set preview badge title if (isInEditMode() || TextUtils.isEmpty(model.getBadgeTitle())) model.setBadgeTitle(PREVIEW_BADGE); // Set badge title bounds mBadgePaint.setTextSize(mBadgeTitleSize * model.mBadgeFraction); mBadgePaint.getTextBounds( model.getBadgeTitle(), 0, model.getBadgeTitle().length(), mBadgeBounds ); // Get horizontal and vertical padding for bg final float horizontalPadding = mBadgeTitleSize * BADGE_HORIZONTAL_FRACTION; final float verticalPadding = horizontalPadding * BADGE_VERTICAL_FRACTION; // Set horizontal badge offset final float badgeBoundsHorizontalOffset = (mModelSize * i) + (mModelSize * mBadgePosition.mPositionFraction); // If is badge title only one char, so create circle else round rect if (model.getBadgeTitle().length() == 1) { final float badgeMargin = mBadgeMargin * model.mBadgeFraction; mBgBadgeBounds.set( badgeBoundsHorizontalOffset - badgeMargin, modelBadgeMargin - badgeMargin, badgeBoundsHorizontalOffset + badgeMargin, modelBadgeMargin + badgeMargin ); } else mBgBadgeBounds.set( badgeBoundsHorizontalOffset - mBadgeBounds.centerX() - horizontalPadding, modelBadgeMargin - (mBadgeMargin * model.mBadgeFraction), badgeBoundsHorizontalOffset + mBadgeBounds.centerX() + horizontalPadding, modelBadgeOffset + (verticalPadding * 2.0f) + mBadgeBounds.height() ); // Set color and alpha for badge bg if (model.mBadgeFraction == MIN_FRACTION) mBadgePaint.setColor(Color.TRANSPARENT); else mBadgePaint.setColor(mActiveColor); mBadgePaint.setAlpha((int) (MAX_ALPHA * model.mBadgeFraction)); // Set corners to round rect for badge bg and draw final float cornerRadius = mBgBadgeBounds.height() * 0.5f; canvas.drawRoundRect(mBgBadgeBounds, cornerRadius, cornerRadius, mBadgePaint); // Set color and alpha for badge title if (model.mBadgeFraction == MIN_FRACTION) mBadgePaint.setColor(Color.TRANSPARENT); else mBadgePaint.setColor(model.getColor()); mBadgePaint.setAlpha((int) (MAX_ALPHA * model.mBadgeFraction)); // Set badge title center position and draw title final float badgeHalfHeight = mBadgeBounds.height() * 0.5f; float badgeVerticalOffset = (mBgBadgeBounds.height() * 0.5f) + badgeHalfHeight - mBadgeBounds.bottom + modelBadgeOffset; canvas.drawText( model.getBadgeTitle(), badgeBoundsHorizontalOffset, badgeVerticalOffset + mBadgeBounds.height() - (mBadgeBounds.height() * model.mBadgeFraction), mBadgePaint ); } } // Method to transform current fraction of NTB and position private void updateCurrentModel( final Model model, final float leftOffset, final float topOffset, final float titleTranslate, final float interpolation, final float matrixCenterX, final float matrixCenterY, final float matrixScale, final float textScale, final int textAlpha ) { if (mIsTitled && mTitleMode == TitleMode.ACTIVE) model.mIconMatrix.setTranslate( leftOffset, topOffset - (interpolation * (topOffset - titleTranslate)) ); model.mIconMatrix.postScale( model.mInactiveIconScale + matrixScale, model.mInactiveIconScale + matrixScale, matrixCenterX, matrixCenterY + (mIsTitled && mTitleMode == TitleMode.ACTIVE ? mTitleMargin * 0.5f * interpolation : 0.0f) ); mModelTitlePaint.setTextSize(mModelTitleSize * textScale); if (mTitleMode == TitleMode.ACTIVE) mModelTitlePaint.setAlpha(textAlpha); } // Method to transform last fraction of NTB and position private void updateLastModel( final Model model, final float leftOffset, final float topOffset, final float titleTranslate, final float lastInterpolation, final float matrixCenterX, final float matrixCenterY, final float matrixLastScale, final float textLastScale, final int textLastAlpha ) { if (mIsTitled && mTitleMode == TitleMode.ACTIVE) model.mIconMatrix.setTranslate( leftOffset, titleTranslate + (lastInterpolation * (topOffset - titleTranslate)) ); model.mIconMatrix.postScale( model.mInactiveIconScale + model.mActiveIconScaleBy - matrixLastScale, model.mInactiveIconScale + model.mActiveIconScaleBy - matrixLastScale, matrixCenterX, matrixCenterY + (mIsTitled && mTitleMode == TitleMode.ACTIVE ? mTitleMargin * 0.5f - (mTitleMargin * 0.5f * lastInterpolation) : 0.0f) ); mModelTitlePaint.setTextSize(mModelTitleSize * textLastScale); if (mTitleMode == TitleMode.ACTIVE) mModelTitlePaint.setAlpha(textLastAlpha); } // Method to transform others fraction of NTB and position private void updateInactiveModel( final Model model, final float leftOffset, final float topOffset, final float matrixCenterX, final float matrixCenterY ) { if (mIsTitled && mTitleMode == TitleMode.ACTIVE) model.mIconMatrix.setTranslate(leftOffset, topOffset); model.mIconMatrix.postScale( model.mInactiveIconScale, model.mInactiveIconScale, matrixCenterX, matrixCenterY ); mModelTitlePaint.setTextSize(mModelTitleSize); if (mTitleMode == TitleMode.ACTIVE) mModelTitlePaint.setAlpha(MIN_ALPHA); } @Override public void onPageScrolled(int position, float positionOffset, final int positionOffsetPixels) { // If we animate, don`t call this if (!mIsSetIndexFromTabBar) { mIsResizeIn = position < mIndex; mLastIndex = mIndex; mIndex = position; mStartPointerX = position * mModelSize; mEndPointerX = mStartPointerX + mModelSize; updateIndicatorPosition(positionOffset); } if (mOnPageChangeListener != null) mOnPageChangeListener.onPageScrolled(position, positionOffset, positionOffsetPixels); } @Override public void onPageSelected(final int position) { // If VP idle, so update if (mScrollState == ViewPager.SCROLL_STATE_IDLE) { mIsResizeIn = position < mIndex; mLastIndex = mIndex; mIndex = position; postInvalidate(); } } @Override public void onPageScrollStateChanged(final int state) { // If VP idle, reset to MIN_FRACTION if (state == ViewPager.SCROLL_STATE_IDLE) { mFraction = MIN_FRACTION; mIsSetIndexFromTabBar = false; if (mOnPageChangeListener != null) mOnPageChangeListener.onPageSelected(mIndex); else { if (mOnTabBarSelectedIndexListener != null) mOnTabBarSelectedIndexListener.onEndTabSelected(mModels.get(mIndex), mIndex); } } mScrollState = state; if (mOnPageChangeListener != null) mOnPageChangeListener.onPageScrollStateChanged(state); } @Override public void onRestoreInstanceState(Parcelable state) { final SavedState savedState = (SavedState) state; super.onRestoreInstanceState(savedState.getSuperState()); mIndex = savedState.index; requestLayout(); } @Override public Parcelable onSaveInstanceState() { final Parcelable superState = super.onSaveInstanceState(); final SavedState savedState = new SavedState(superState); savedState.index = mIndex; return savedState; } static class SavedState extends BaseSavedState { int index; public SavedState(Parcelable superState) { super(superState); } private SavedState(Parcel in) { super(in); index = in.readInt(); } @Override public void writeToParcel(Parcel dest, int flags) { super.writeToParcel(dest, flags); dest.writeInt(index); } @SuppressWarnings("UnusedDeclaration") public static final Creator<SavedState> CREATOR = new Creator<SavedState>() { @Override public SavedState createFromParcel(Parcel in) { return new SavedState(in); } @Override public SavedState[] newArray(int size) { return new SavedState[size]; } }; } // Model class public static class Model { private String mTitle = ""; private int mColor; private Bitmap mIcon; private Matrix mIconMatrix = new Matrix(); private String mBadgeTitle = ""; private String mTempBadgeTitle = ""; private float mBadgeFraction; private boolean mIsBadgeShowed; private boolean mIsBadgeUpdated; private ValueAnimator mBadgeAnimator = new ValueAnimator(); private float mInactiveIconScale; private float mActiveIconScaleBy; public Model(final Drawable icon, final int color) { mColor = color; mIcon = icon != null ? ((BitmapDrawable) icon).getBitmap() : Bitmap.createBitmap(1, 1, Bitmap.Config.RGB_565); mBadgeAnimator.addListener(new Animator.AnimatorListener() { @Override public void onAnimationStart(final Animator animation) { } @Override public void onAnimationEnd(final Animator animation) { // Detect whether we just update text and don`t reset show state if (!mIsBadgeUpdated) mIsBadgeShowed = !mIsBadgeShowed; else mIsBadgeUpdated = false; } @Override public void onAnimationCancel(final Animator animation) { } @Override public void onAnimationRepeat(final Animator animation) { // Change title when we update and don`t see the title if (mIsBadgeUpdated) mBadgeTitle = mTempBadgeTitle; } }); } public Model(final Drawable icon, final int color, final String title) { this(icon, color); mTitle = title; } public Model(final Drawable icon, final int color, final String title, final String badgeTitle) { this(icon, color, title); mBadgeTitle = badgeTitle; } public String getTitle() { return mTitle; } public void setTitle(final String title) { mTitle = title; } public int getColor() { return mColor; } public void setColor(final int color) { mColor = color; } public boolean isBadgeShowed() { return mIsBadgeShowed; } public String getBadgeTitle() { return mBadgeTitle; } public void setBadgeTitle(final String badgeTitle) { mBadgeTitle = badgeTitle; } // If your badge is visible on screen, so you can update title with animation public void updateBadgeTitle(final String badgeTitle) { if (!mIsBadgeShowed) return; if (mBadgeAnimator.isRunning()) mBadgeAnimator.end(); mTempBadgeTitle = badgeTitle; mIsBadgeUpdated = true; mBadgeAnimator.setFloatValues(MAX_FRACTION, MIN_FRACTION); mBadgeAnimator.setDuration(DEFAULT_BADGE_REFRESH_ANIMATION_DURATION); mBadgeAnimator.setRepeatMode(ValueAnimator.REVERSE); mBadgeAnimator.setRepeatCount(1); mBadgeAnimator.start(); } public void toggleBadge() { if (mBadgeAnimator.isRunning()) mBadgeAnimator.end(); if (mIsBadgeShowed) hideBadge(); else showBadge(); } public void showBadge() { mIsBadgeUpdated = false; if (mBadgeAnimator.isRunning()) mBadgeAnimator.end(); if (mIsBadgeShowed) return; mBadgeAnimator.setFloatValues(MIN_FRACTION, MAX_FRACTION); mBadgeAnimator.setInterpolator(DECELERATE_INTERPOLATOR); mBadgeAnimator.setDuration(DEFAULT_BADGE_ANIMATION_DURATION); mBadgeAnimator.setRepeatMode(ValueAnimator.RESTART); mBadgeAnimator.setRepeatCount(0); mBadgeAnimator.start(); } public void hideBadge() { mIsBadgeUpdated = false; if (mBadgeAnimator.isRunning()) mBadgeAnimator.end(); if (!mIsBadgeShowed) return; mBadgeAnimator.setFloatValues(MAX_FRACTION, MIN_FRACTION); mBadgeAnimator.setInterpolator(ACCELERATE_INTERPOLATOR); mBadgeAnimator.setDuration(DEFAULT_BADGE_ANIMATION_DURATION); mBadgeAnimator.setRepeatMode(ValueAnimator.RESTART); mBadgeAnimator.setRepeatCount(0); mBadgeAnimator.start(); } } // Custom scroller with custom scroll duration private class ResizeViewPagerScroller extends Scroller { public ResizeViewPagerScroller(Context context) { super(context, new AccelerateDecelerateInterpolator()); } @Override public void startScroll(int startX, int startY, int dx, int dy, int duration) { super.startScroll(startX, startY, dx, dy, mAnimationDuration); } @Override public void startScroll(int startX, int startY, int dx, int dy) { super.startScroll(startX, startY, dx, dy, mAnimationDuration); } } // Resize interpolator to create smooth effect on pointer according to inspiration design // This is like improved accelerated and decelerated interpolator private class ResizeInterpolator implements Interpolator { // Spring factor private final float mFactor = 1.0f; // Check whether side we move private boolean mResizeIn; @Override public float getInterpolation(final float input) { if (mResizeIn) return (float) (1.0f - Math.pow((1.0f - input), 2.0f * mFactor)); else return (float) (Math.pow(input, 2.0f * mFactor)); } public float getResizeInterpolation(final float input, final boolean resizeIn) { mResizeIn = resizeIn; return getInterpolation(input); } } // Model title mode public enum TitleMode { ALL, ACTIVE } // Model badge position public enum BadgePosition { LEFT(LEFT_FRACTION), CENTER(CENTER_FRACTION), RIGHT(RIGHT_FRACTION); private float mPositionFraction; BadgePosition() { mPositionFraction = RIGHT_FRACTION; } BadgePosition(final float positionFraction) { mPositionFraction = positionFraction; } } // Model badge gravity public enum BadgeGravity { TOP, BOTTOM } // Out listener for selected index public interface OnTabBarSelectedIndexListener { void onStartTabSelected(final Model model, final int index); void onEndTabSelected(final Model model, final int index); } }
Add support for Vector Drawables
library/src/main/java/com/gigamole/library/NavigationTabBar.java
Add support for Vector Drawables
Java
apache-2.0
c2f49b7fe9b5508a835bc919b0cecc9996acd3bc
0
kobakei/Android-RateThisApp
/* * Copyright 2013-2015 Keisuke Kobayashi * * 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.kobakei.ratethisapp; import java.lang.ref.WeakReference; import java.util.Date; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnCancelListener; import android.content.DialogInterface.OnClickListener; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.net.Uri; import android.os.Build; import android.support.annotation.StringRes; import android.support.v7.app.AlertDialog; import android.text.TextUtils; import android.util.Log; /** * RateThisApp<br> * A library to show the app rate dialog * @author Keisuke Kobayashi ([email protected]) * */ public class RateThisApp { private static final String TAG = RateThisApp.class.getSimpleName(); private static final String PREF_NAME = "RateThisApp"; private static final String KEY_INSTALL_DATE = "rta_install_date"; private static final String KEY_LAUNCH_TIMES = "rta_launch_times"; private static final String KEY_OPT_OUT = "rta_opt_out"; private static final String KEY_ASK_LATER_DATE = "rta_ask_later_date"; private static Date mInstallDate = new Date(); private static int mLaunchTimes = 0; private static boolean mOptOut = false; private static Date mAskLaterDate = new Date(); private static Config sConfig = new Config(); private static Callback sCallback = null; // Weak ref to avoid leaking the context private static WeakReference<AlertDialog> sDialogRef = null; /** * If true, print LogCat */ public static final boolean DEBUG = false; /** * Initialize RateThisApp configuration. * @param config Configuration object. */ public static void init(Config config) { sConfig = config; } /** * Set callback instance. * The callback will receive yes/no/later events. * @param callback */ public static void setCallback(Callback callback) { sCallback = callback; } /** * Call this API when the launcher activity is launched.<br> * It is better to call this API in onStart() of the launcher activity. * @param context Context */ public static void onStart(Context context) { SharedPreferences pref = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE); Editor editor = pref.edit(); // If it is the first launch, save the date in shared preference. if (pref.getLong(KEY_INSTALL_DATE, 0) == 0L) { storeInstallDate(context, editor); } // Increment launch times int launchTimes = pref.getInt(KEY_LAUNCH_TIMES, 0); launchTimes++; editor.putInt(KEY_LAUNCH_TIMES, launchTimes); log("Launch times; " + launchTimes); editor.commit(); mInstallDate = new Date(pref.getLong(KEY_INSTALL_DATE, 0)); mLaunchTimes = pref.getInt(KEY_LAUNCH_TIMES, 0); mOptOut = pref.getBoolean(KEY_OPT_OUT, false); mAskLaterDate = new Date(pref.getLong(KEY_ASK_LATER_DATE, 0)); printStatus(context); } /** * Show the rate dialog if the criteria is satisfied. * @param context Context * @return true if shown, false otherwise. */ public static boolean showRateDialogIfNeeded(final Context context) { if (shouldShowRateDialog()) { showRateDialog(context); return true; } else { return false; } } /** * Show the rate dialog if the criteria is satisfied. * @param context Context * @param themeId Theme ID * @return true if shown, false otherwise. */ public static boolean showRateDialogIfNeeded(final Context context, int themeId) { if (shouldShowRateDialog()) { showRateDialog(context, themeId); return true; } else { return false; } } /** * Check whether the rate dialog should be shown or not. * Developers may call this method directly if they want to show their own view instead of * dialog provided by this library. * @return */ public static boolean shouldShowRateDialog() { if (mOptOut) { return false; } else { if (mLaunchTimes >= sConfig.mCriteriaLaunchTimes) { return true; } long threshold = sConfig.mCriteriaInstallDays * 24 * 60 * 60 * 1000L; // msec if (new Date().getTime() - mInstallDate.getTime() >= threshold && new Date().getTime() - mAskLaterDate.getTime() >= threshold) { return true; } return false; } } /** * Show the rate dialog * @param context */ public static void showRateDialog(final Context context) { AlertDialog.Builder builder = new AlertDialog.Builder(context); showRateDialog(context, builder); } /** * Show the rate dialog * @param context * @param themeId */ public static void showRateDialog(final Context context, int themeId) { AlertDialog.Builder builder = new AlertDialog.Builder(context, themeId); showRateDialog(context, builder); } /** * Stop showing the rate dialog * @param context */ public static void stopRateDialog(final Context context){ setOptOut(context, true); } private static void showRateDialog(final Context context, AlertDialog.Builder builder) { if (sDialogRef != null && sDialogRef.get() != null) { // Dialog is already present return; } int titleId = sConfig.mTitleId != 0 ? sConfig.mTitleId : R.string.rta_dialog_title; int messageId = sConfig.mMessageId != 0 ? sConfig.mMessageId : R.string.rta_dialog_message; int cancelButtonID = sConfig.mCancelButton != 0 ? sConfig.mCancelButton : R.string.rta_dialog_cancel; int thanksButtonID = sConfig.mNoButtonId != 0 ? sConfig.mNoButtonId : R.string.rta_dialog_no; int rateButtonID = sConfig.mYesButtonId != 0 ? sConfig.mYesButtonId : R.string.rta_dialog_ok; builder.setTitle(titleId); builder.setMessage(messageId); builder.setCancelable(sConfig.mCancelable); builder.setPositiveButton(rateButtonID, new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (sCallback != null) { sCallback.onYesClicked(); } String appPackage = context.getPackageName(); String url = "https://play.google.com/store/apps/details?id=" + appPackage; if (!TextUtils.isEmpty(sConfig.mUrl)) { url = sConfig.mUrl; } Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); context.startActivity(intent); setOptOut(context, true); } }); builder.setNeutralButton(cancelButtonID, new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (sCallback != null) { sCallback.onCancelClicked(); } clearSharedPreferences(context); storeAskLaterDate(context); } }); builder.setNegativeButton(thanksButtonID, new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (sCallback != null) { sCallback.onNoClicked(); } setOptOut(context, true); } }); builder.setOnCancelListener(new OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { if (sCallback != null) { sCallback.onCancelClicked(); } clearSharedPreferences(context); storeAskLaterDate(context); } }); builder.setOnDismissListener(new DialogInterface.OnDismissListener() { @Override public void onDismiss(DialogInterface dialog) { sDialogRef.clear(); } }); sDialogRef = new WeakReference<>(builder.show()); } /** * Clear data in shared preferences.<br> * This API is called when the rate dialog is approved or canceled. * @param context */ private static void clearSharedPreferences(Context context) { SharedPreferences pref = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE); Editor editor = pref.edit(); editor.remove(KEY_INSTALL_DATE); editor.remove(KEY_LAUNCH_TIMES); editor.commit(); } /** * Set opt out flag. If it is true, the rate dialog will never shown unless app data is cleared. * @param context * @param optOut */ private static void setOptOut(final Context context, boolean optOut) { SharedPreferences pref = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE); Editor editor = pref.edit(); editor.putBoolean(KEY_OPT_OUT, optOut); editor.commit(); mOptOut = optOut; } /** * Store install date. * Install date is retrieved from package manager if possible. * @param context * @param editor */ private static void storeInstallDate(final Context context, SharedPreferences.Editor editor) { Date installDate = new Date(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) { PackageManager packMan = context.getPackageManager(); try { PackageInfo pkgInfo = packMan.getPackageInfo(context.getPackageName(), 0); installDate = new Date(pkgInfo.firstInstallTime); } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } } editor.putLong(KEY_INSTALL_DATE, installDate.getTime()); log("First install: " + installDate.toString()); } /** * Store the date the user asked for being asked again later. * @param context */ private static void storeAskLaterDate(final Context context) { SharedPreferences pref = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE); Editor editor = pref.edit(); editor.putLong(KEY_ASK_LATER_DATE, System.currentTimeMillis()); editor.commit(); } /** * Print values in SharedPreferences (used for debug) * @param context */ private static void printStatus(final Context context) { SharedPreferences pref = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE); log("*** RateThisApp Status ***"); log("Install Date: " + new Date(pref.getLong(KEY_INSTALL_DATE, 0))); log("Launch Times: " + pref.getInt(KEY_LAUNCH_TIMES, 0)); log("Opt out: " + pref.getBoolean(KEY_OPT_OUT, false)); } /** * Print log if enabled * @param message */ private static void log(String message) { if (DEBUG) { Log.v(TAG, message); } } /** * RateThisApp configuration. */ public static class Config { private String mUrl = null; private int mCriteriaInstallDays; private int mCriteriaLaunchTimes; private int mTitleId = 0; private int mMessageId = 0; private int mYesButtonId = 0; private int mNoButtonId = 0; private int mCancelButton = 0; private boolean mCancelable; /** * Constructor with default criteria. */ public Config() { this(7, 10); } /** * Constructor. * @param criteriaInstallDays * @param criteriaLaunchTimes */ public Config(int criteriaInstallDays, int criteriaLaunchTimes) { this.mCriteriaInstallDays = criteriaInstallDays; this.mCriteriaLaunchTimes = criteriaLaunchTimes; } /** * Set title string ID. * @param stringId */ public void setTitle(@StringRes int stringId) { this.mTitleId = stringId; } /** * Set message string ID. * @param stringId */ public void setMessage(@StringRes int stringId) { this.mMessageId = stringId; } /** * Set rate now string ID. * @param stringId */ public void setYesButtonText(@StringRes int stringId) { this.mYesButtonId = stringId; } /** * Set no thanks string ID. * @param stringId */ public void setNoButtonText(@StringRes int stringId) { this.mNoButtonId = stringId; } /** * Set cancel string ID. * @param stringId */ public void setCancelButtonText(@StringRes int stringId) { this.mCancelButton = stringId; } /** * Set navigation url when user clicks rate button. * Typically, url will be https://play.google.com/store/apps/details?id=PACKAGE_NAME for Google Play. * @param url */ public void setUrl(String url) { this.mUrl = url; } public void setCancelable(boolean cancelable) { this.mCancelable = cancelable; } } /** * Callback of dialog click event */ public interface Callback { /** * "Rate now" event */ void onYesClicked(); /** * "No, thanks" event */ void onNoClicked(); /** * "Later" event */ void onCancelClicked(); } }
ratethisapp/src/main/java/com/kobakei/ratethisapp/RateThisApp.java
/* * Copyright 2013-2015 Keisuke Kobayashi * * 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.kobakei.ratethisapp; import java.lang.ref.WeakReference; import java.util.Date; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnCancelListener; import android.content.DialogInterface.OnClickListener; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.net.Uri; import android.os.Build; import android.support.annotation.StringRes; import android.support.v7.app.AlertDialog; import android.text.TextUtils; import android.util.Log; /** * RateThisApp<br> * A library to show the app rate dialog * @author Keisuke Kobayashi ([email protected]) * */ public class RateThisApp { private static final String TAG = RateThisApp.class.getSimpleName(); private static final String PREF_NAME = "RateThisApp"; private static final String KEY_INSTALL_DATE = "rta_install_date"; private static final String KEY_LAUNCH_TIMES = "rta_launch_times"; private static final String KEY_OPT_OUT = "rta_opt_out"; private static final String KEY_ASK_LATER_DATE = "rta_ask_later_date"; private static Date mInstallDate = new Date(); private static int mLaunchTimes = 0; private static boolean mOptOut = false; private static Date mAskLaterDate = new Date(); private static Config sConfig = new Config(); private static Callback sCallback = null; // Weak ref to avoid leaking the context private static WeakReference<AlertDialog> sDialogRef = null; /** * If true, print LogCat */ public static final boolean DEBUG = false; /** * Initialize RateThisApp configuration. * @param config Configuration object. */ public static void init(Config config) { sConfig = config; } /** * Set callback instance. * The callback will receive yes/no/later events. * @param callback */ public static void setCallback(Callback callback) { sCallback = callback; } /** * Call this API when the launcher activity is launched.<br> * It is better to call this API in onStart() of the launcher activity. * @param context Context */ public static void onStart(Context context) { SharedPreferences pref = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE); Editor editor = pref.edit(); // If it is the first launch, save the date in shared preference. if (pref.getLong(KEY_INSTALL_DATE, 0) == 0L) { storeInstallDate(context, editor); } // Increment launch times int launchTimes = pref.getInt(KEY_LAUNCH_TIMES, 0); launchTimes++; editor.putInt(KEY_LAUNCH_TIMES, launchTimes); log("Launch times; " + launchTimes); editor.commit(); mInstallDate = new Date(pref.getLong(KEY_INSTALL_DATE, 0)); mLaunchTimes = pref.getInt(KEY_LAUNCH_TIMES, 0); mOptOut = pref.getBoolean(KEY_OPT_OUT, false); mAskLaterDate = new Date(pref.getLong(KEY_ASK_LATER_DATE, 0)); printStatus(context); } /** * Show the rate dialog if the criteria is satisfied. * @param context Context * @return true if shown, false otherwise. */ public static boolean showRateDialogIfNeeded(final Context context) { if (shouldShowRateDialog()) { showRateDialog(context); return true; } else { return false; } } /** * Show the rate dialog if the criteria is satisfied. * @param context Context * @param themeId Theme ID * @return true if shown, false otherwise. */ public static boolean showRateDialogIfNeeded(final Context context, int themeId) { if (shouldShowRateDialog()) { showRateDialog(context, themeId); return true; } else { return false; } } /** * Check whether the rate dialog should be shown or not. * Developers may call this method directly if they want to show their own view instead of * dialog provided by this library. * @return */ public static boolean shouldShowRateDialog() { if (mOptOut) { return false; } else { if (mLaunchTimes >= sConfig.mCriteriaLaunchTimes) { return true; } long threshold = sConfig.mCriteriaInstallDays * 24 * 60 * 60 * 1000L; // msec if (new Date().getTime() - mInstallDate.getTime() >= threshold && new Date().getTime() - mAskLaterDate.getTime() >= threshold) { return true; } return false; } } /** * Show the rate dialog * @param context */ public static void showRateDialog(final Context context) { AlertDialog.Builder builder = new AlertDialog.Builder(context); showRateDialog(context, builder); } /** * Show the rate dialog * @param context * @param themeId */ public static void showRateDialog(final Context context, int themeId) { AlertDialog.Builder builder = new AlertDialog.Builder(context, themeId); showRateDialog(context, builder); } /** * Stop showing the rate dialog * @param context */ public static void stopRateDialog(final Context context){ setOptOut(context, true); } private static void showRateDialog(final Context context, AlertDialog.Builder builder) { if (sDialogRef != null && sDialogRef.get() != null) { // Dialog is already present return; } int titleId = sConfig.mTitleId != 0 ? sConfig.mTitleId : R.string.rta_dialog_title; int messageId = sConfig.mMessageId != 0 ? sConfig.mMessageId : R.string.rta_dialog_message; int cancelButtonID = sConfig.mCancelButton != 0 ? sConfig.mCancelButton : R.string.rta_dialog_cancel; int thanksButtonID = sConfig.mNoButtonId != 0 ? sConfig.mNoButtonId : R.string.rta_dialog_no; int rateButtonID = sConfig.mYesButtonId != 0 ? sConfig.mYesButtonId : R.string.rta_dialog_ok; builder.setTitle(titleId); builder.setMessage(messageId); builder.setPositiveButton(rateButtonID, new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (sCallback != null) { sCallback.onYesClicked(); } String appPackage = context.getPackageName(); String url = "https://play.google.com/store/apps/details?id=" + appPackage; if (!TextUtils.isEmpty(sConfig.mUrl)) { url = sConfig.mUrl; } Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); context.startActivity(intent); setOptOut(context, true); } }); builder.setNeutralButton(cancelButtonID, new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (sCallback != null) { sCallback.onCancelClicked(); } clearSharedPreferences(context); storeAskLaterDate(context); } }); builder.setNegativeButton(thanksButtonID, new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (sCallback != null) { sCallback.onNoClicked(); } setOptOut(context, true); } }); builder.setOnCancelListener(new OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { if (sCallback != null) { sCallback.onCancelClicked(); } clearSharedPreferences(context); storeAskLaterDate(context); } }); builder.setOnDismissListener(new DialogInterface.OnDismissListener() { @Override public void onDismiss(DialogInterface dialog) { sDialogRef.clear(); } }); sDialogRef = new WeakReference<>(builder.show()); } /** * Clear data in shared preferences.<br> * This API is called when the rate dialog is approved or canceled. * @param context */ private static void clearSharedPreferences(Context context) { SharedPreferences pref = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE); Editor editor = pref.edit(); editor.remove(KEY_INSTALL_DATE); editor.remove(KEY_LAUNCH_TIMES); editor.commit(); } /** * Set opt out flag. If it is true, the rate dialog will never shown unless app data is cleared. * @param context * @param optOut */ private static void setOptOut(final Context context, boolean optOut) { SharedPreferences pref = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE); Editor editor = pref.edit(); editor.putBoolean(KEY_OPT_OUT, optOut); editor.commit(); mOptOut = optOut; } /** * Store install date. * Install date is retrieved from package manager if possible. * @param context * @param editor */ private static void storeInstallDate(final Context context, SharedPreferences.Editor editor) { Date installDate = new Date(); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) { PackageManager packMan = context.getPackageManager(); try { PackageInfo pkgInfo = packMan.getPackageInfo(context.getPackageName(), 0); installDate = new Date(pkgInfo.firstInstallTime); } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } } editor.putLong(KEY_INSTALL_DATE, installDate.getTime()); log("First install: " + installDate.toString()); } /** * Store the date the user asked for being asked again later. * @param context */ private static void storeAskLaterDate(final Context context) { SharedPreferences pref = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE); Editor editor = pref.edit(); editor.putLong(KEY_ASK_LATER_DATE, System.currentTimeMillis()); editor.commit(); } /** * Print values in SharedPreferences (used for debug) * @param context */ private static void printStatus(final Context context) { SharedPreferences pref = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE); log("*** RateThisApp Status ***"); log("Install Date: " + new Date(pref.getLong(KEY_INSTALL_DATE, 0))); log("Launch Times: " + pref.getInt(KEY_LAUNCH_TIMES, 0)); log("Opt out: " + pref.getBoolean(KEY_OPT_OUT, false)); } /** * Print log if enabled * @param message */ private static void log(String message) { if (DEBUG) { Log.v(TAG, message); } } /** * RateThisApp configuration. */ public static class Config { private String mUrl = null; private int mCriteriaInstallDays; private int mCriteriaLaunchTimes; private int mTitleId = 0; private int mMessageId = 0; private int mYesButtonId = 0; private int mNoButtonId = 0; private int mCancelButton = 0; /** * Constructor with default criteria. */ public Config() { this(7, 10); } /** * Constructor. * @param criteriaInstallDays * @param criteriaLaunchTimes */ public Config(int criteriaInstallDays, int criteriaLaunchTimes) { this.mCriteriaInstallDays = criteriaInstallDays; this.mCriteriaLaunchTimes = criteriaLaunchTimes; } /** * Set title string ID. * @param stringId */ public void setTitle(@StringRes int stringId) { this.mTitleId = stringId; } /** * Set message string ID. * @param stringId */ public void setMessage(@StringRes int stringId) { this.mMessageId = stringId; } /** * Set rate now string ID. * @param stringId */ public void setYesButtonText(@StringRes int stringId) { this.mYesButtonId = stringId; } /** * Set no thanks string ID. * @param stringId */ public void setNoButtonText(@StringRes int stringId) { this.mNoButtonId = stringId; } /** * Set cancel string ID. * @param stringId */ public void setCancelButtonText(@StringRes int stringId) { this.mCancelButton = stringId; } /** * Set navigation url when user clicks rate button. * Typically, url will be https://play.google.com/store/apps/details?id=PACKAGE_NAME for Google Play. * @param url */ public void setUrl(String url) { this.mUrl = url; } } /** * Callback of dialog click event */ public interface Callback { /** * "Rate now" event */ void onYesClicked(); /** * "No, thanks" event */ void onNoClicked(); /** * "Later" event */ void onCancelClicked(); } }
Add cancelable option to configuration
ratethisapp/src/main/java/com/kobakei/ratethisapp/RateThisApp.java
Add cancelable option to configuration
Java
apache-2.0
ba76cf2a6e4d4e8c2b8c50fae79eb9f1ee9361fa
0
emqtt/mqtt-jmeter
package net.xmeter.gui; import java.awt.BorderLayout; import javax.swing.JPanel; import org.apache.jmeter.gui.util.VerticalPanel; import org.apache.jmeter.samplers.gui.AbstractSamplerGui; import org.apache.jmeter.testelement.TestElement; import org.apache.jorphan.logging.LoggingManager; import org.apache.log.Logger; import net.xmeter.Constants; import net.xmeter.samplers.ConnectionSampler; public class ConnectionSamplerUI extends AbstractSamplerGui implements Constants { private static final Logger logger = LoggingManager.getLoggerForClass(); private CommonConnUI connUI = new CommonConnUI(); /** * */ private static final long serialVersionUID = 1666890646673145131L; public ConnectionSamplerUI() { this.init(); } private void init() { logger.info("Initializing the UI."); setLayout(new BorderLayout()); setBorder(makeBorder()); add(makeTitlePanel(), BorderLayout.NORTH); JPanel mainPanel = new VerticalPanel(); add(mainPanel, BorderLayout.CENTER); mainPanel.add(connUI.createConnPanel()); mainPanel.add(connUI.createProtocolPanel()); mainPanel.add(connUI.createAuthentication()); mainPanel.add(connUI.createConnOptions()); } @Override public void configure(TestElement element) { super.configure(element); ConnectionSampler sampler = (ConnectionSampler)element; connUI.configure(sampler); } @Override public TestElement createTestElement() { ConnectionSampler sampler = new ConnectionSampler(); this.configureTestElement(sampler); connUI.setupSamplerProperties(sampler); return sampler; } @Override public String getLabelResource() { throw new RuntimeException(); } @Override public String getStaticLabel() { return "MQTT Connection Sampler"; } @Override public void modifyTestElement(TestElement arg0) { ConnectionSampler sampler = (ConnectionSampler)arg0; this.configureTestElement(sampler); connUI.setupSamplerProperties(sampler); } @Override public void clearGui() { super.clearGui(); connUI.clearUI(); } }
mqtt_jmeter/src/main/java/net/xmeter/gui/ConnectionSamplerUI.java
package net.xmeter.gui; import java.awt.BorderLayout; import javax.swing.JPanel; import org.apache.jmeter.gui.util.VerticalPanel; import org.apache.jmeter.samplers.gui.AbstractSamplerGui; import org.apache.jmeter.testelement.TestElement; import org.apache.jorphan.logging.LoggingManager; import org.apache.log.Logger; import net.xmeter.Constants; import net.xmeter.samplers.ConnectionSampler; public class ConnectionSamplerUI extends AbstractSamplerGui implements Constants { private static final Logger logger = LoggingManager.getLoggerForClass(); private CommonConnUI connUI = new CommonConnUI(); /** * */ private static final long serialVersionUID = 1666890646673145131L; public ConnectionSamplerUI() { this.init(); } private void init() { logger.info("Initializing the UI."); setLayout(new BorderLayout()); setBorder(makeBorder()); add(makeTitlePanel(), BorderLayout.NORTH); JPanel mainPanel = new VerticalPanel(); add(mainPanel, BorderLayout.CENTER); mainPanel.add(connUI.createConnPanel()); mainPanel.add(connUI.createProtocolPanel()); mainPanel.add(connUI.createAuthentication()); mainPanel.add(connUI.createConnOptions()); } @Override public void configure(TestElement element) { super.configure(element); ConnectionSampler sampler = (ConnectionSampler)element; connUI.configure(sampler); } @Override public TestElement createTestElement() { ConnectionSampler sampler = new ConnectionSampler(); this.configureTestElement(sampler); connUI.setupSamplerProperties(sampler); return sampler; } @Override public String getLabelResource() { return ""; } @Override public String getStaticLabel() { return "MQTT Connection Sampler"; } @Override public void modifyTestElement(TestElement arg0) { ConnectionSampler sampler = (ConnectionSampler)arg0; this.configureTestElement(sampler); connUI.setupSamplerProperties(sampler); } @Override public void clearGui() { super.clearGui(); connUI.clearUI(); } }
add sampler label
mqtt_jmeter/src/main/java/net/xmeter/gui/ConnectionSamplerUI.java
add sampler label
Java
apache-2.0
8147cba33019e8a26c34b671d92ab8c56e447aa2
0
4u7/couchbase-lite-java-core,Spotme/couchbase-lite-java-core,netsense-sas/couchbase-lite-java-core,mariosotil/couchbase-lite-java-core,mariosotil/couchbase-lite-java-core,couchbase/couchbase-lite-java-core,mariosotil/couchbase-lite-java-core,deleet/couchbase-lite-java-core,gotmyjobs/couchbase-lite-java-core
/** * Original iOS version by Jens Alfke * Ported to Android by Marty Schoch * * Copyright (c) 2012 Couchbase, 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 com.couchbase.lite.support; import com.couchbase.lite.Database; import com.couchbase.lite.util.Log; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.nio.channels.FileChannel; public class FileDirUtils { public static boolean removeItemIfExists(String path) { File f = new File(path); return f.delete() || !f.exists(); } public static boolean deleteRecursive(File fileOrDirectory) { if (fileOrDirectory.isDirectory()) { for (File child : fileOrDirectory.listFiles()) { deleteRecursive(child); } } boolean result = fileOrDirectory.delete() || !fileOrDirectory.exists(); return result; } public static String getDatabaseNameFromPath(String path) { int lastSlashPos = path.lastIndexOf("/"); int extensionPos = path.lastIndexOf("."); if(lastSlashPos < 0 || extensionPos < 0 || extensionPos < lastSlashPos) { String message = "Unable to determine database name from path: " + path; Log.e(Database.TAG, message); throw new IllegalArgumentException(message); } return path.substring(lastSlashPos + 1, extensionPos); } public static void copyFile(File sourceFile, File destFile) throws IOException { if(!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if(source != null) { source.close(); } if(destination != null) { destination.close(); } } } public static void copyFolder(File src, File dest) throws IOException{ if(src.isDirectory()){ //if directory not exists, create it if(!dest.exists()){ dest.mkdir(); } //list all the directory contents String files[] = src.list(); for (String file : files) { //construct the src and dest file structure File srcFile = new File(src, file); File destFile = new File(dest, file); //recursive copy copyFolder(srcFile,destFile); } }else{ copyFile(src, dest); } } }
src/main/java/com/couchbase/lite/support/FileDirUtils.java
/** * Original iOS version by Jens Alfke * Ported to Android by Marty Schoch * * Copyright (c) 2012 Couchbase, 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 com.couchbase.lite.support; import com.couchbase.lite.Database; import com.couchbase.lite.util.Log; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.nio.channels.FileChannel; public class FileDirUtils { public static boolean removeItemIfExists(String path) { File f = new File(path); return f.delete() || !f.exists(); } public static boolean deleteRecursive(File fileOrDirectory) { if (fileOrDirectory.isDirectory()) { for (File child : fileOrDirectory.listFiles()) { deleteRecursive(child); } } boolean result = fileOrDirectory.delete() || !fileOrDirectory.exists(); return result; } public static String getDatabaseNameFromPath(String path) { int lastSlashPos = path.lastIndexOf("/"); int extensionPos = path.lastIndexOf("."); if(lastSlashPos < 0 || extensionPos < 0 || extensionPos < lastSlashPos) { Log.e(Database.TAG, "Unable to determine database name from path"); return null; } return path.substring(lastSlashPos + 1, extensionPos); } public static void copyFile(File sourceFile, File destFile) throws IOException { if(!destFile.exists()) { destFile.createNewFile(); } FileChannel source = null; FileChannel destination = null; try { source = new FileInputStream(sourceFile).getChannel(); destination = new FileOutputStream(destFile).getChannel(); destination.transferFrom(source, 0, source.size()); } finally { if(source != null) { source.close(); } if(destination != null) { destination.close(); } } } public static void copyFolder(File src, File dest) throws IOException{ if(src.isDirectory()){ //if directory not exists, create it if(!dest.exists()){ dest.mkdir(); } //list all the directory contents String files[] = src.list(); for (String file : files) { //construct the src and dest file structure File srcFile = new File(src, file); File destFile = new File(dest, file); //recursive copy copyFolder(srcFile,destFile); } }else{ copyFile(src, dest); } } }
Issue #111 - Fix: Why does Database ever let this.name be null? https://github.com/couchbase/couchbase-lite-java-core/issues/111
src/main/java/com/couchbase/lite/support/FileDirUtils.java
Issue #111 - Fix: Why does Database ever let this.name be null?
Java
apache-2.0
ad61b68192a7a0b37a4346eddc2dd57c4d11a98b
0
jduberville/AndEngine,duchien85/AndEngine,luoxiaoshenghustedu/AndEngine,godghdai/AndEngine,zcwk/AndEngine,yudhir/AndEngine,yaye729125/gles,jduberville/AndEngine,shiguang1120/AndEngine,viacheslavokolitiy/AndEngine,pongo710/AndEngine,pongo710/AndEngine,borrom/AndEngine,ericlaro/AndEngineLibrary,ericlaro/AndEngineLibrary,zhidew/AndEngine,chautn/AndEngine,ericlaro/AndEngineLibrary,shiguang1120/AndEngine,nicolasgramlich/AndEngine,zcwk/AndEngine,yudhir/AndEngine,duchien85/AndEngine,borrom/AndEngine,chautn/AndEngine,borrom/AndEngine,godghdai/AndEngine,parthipanramesh/AndEngine,Munazza/AndEngine,parthipanramesh/AndEngine,luoxiaoshenghustedu/AndEngine,msdgwzhy6/AndEngine,chautn/AndEngine,zhidew/AndEngine,viacheslavokolitiy/AndEngine,msdgwzhy6/AndEngine,shiguang1120/AndEngine,jduberville/AndEngine,yudhir/AndEngine,chautn/AndEngine,pongo710/AndEngine,nicolasgramlich/AndEngine,godghdai/AndEngine,viacheslavokolitiy/AndEngine,jduberville/AndEngine,shiguang1120/AndEngine,nicolasgramlich/AndEngine,yaye729125/gles,msdgwzhy6/AndEngine,luoxiaoshenghustedu/AndEngine,zcwk/AndEngine,yaye729125/gles,Munazza/AndEngine,zhidew/AndEngine,zcwk/AndEngine,luoxiaoshenghustedu/AndEngine,nicolasgramlich/AndEngine,pongo710/AndEngine,ericlaro/AndEngineLibrary,yudhir/AndEngine,parthipanramesh/AndEngine,Munazza/AndEngine,msdgwzhy6/AndEngine,godghdai/AndEngine,yaye729125/gles,borrom/AndEngine,viacheslavokolitiy/AndEngine,Munazza/AndEngine,zhidew/AndEngine,parthipanramesh/AndEngine
package org.anddev.andengine.entity.sprite; import java.util.Arrays; import org.anddev.andengine.opengl.texture.region.TiledTextureRegion; import org.anddev.andengine.opengl.vertex.RectangleVertexBuffer; import org.anddev.andengine.util.MathUtils; import org.anddev.andengine.util.constants.TimeConstants; public class AnimatedSprite extends TiledSprite implements TimeConstants { // =========================================================== // Constants // =========================================================== private static final int LOOP_CONTINUOUS = -1; // =========================================================== // Fields // =========================================================== private boolean mAnimationRunning; private long mAnimationProgress; private long mAnimationDuration; private long[] mFrameEndsInNanoseconds; private int mFirstTileIndex; private int mInitialLoopCount; private int mLoopCount; private IAnimationListener mAnimationListener; private int mFrameCount; private int[] mFrames; // =========================================================== // Constructors // =========================================================== public AnimatedSprite(final float pX, final float pY, final TiledTextureRegion pTiledTextureRegion) { super(pX, pY, pTiledTextureRegion); } public AnimatedSprite(final float pX, final float pY, final float pTileWidth, final float pTileHeight, final TiledTextureRegion pTiledTextureRegion) { super(pX, pY, pTileWidth, pTileHeight, pTiledTextureRegion); } public AnimatedSprite(final float pX, final float pY, final TiledTextureRegion pTiledTextureRegion, final RectangleVertexBuffer pRectangleVertexBuffer) { super(pX, pY, pTiledTextureRegion, pRectangleVertexBuffer); } public AnimatedSprite(final float pX, final float pY, final float pTileWidth, final float pTileHeight, final TiledTextureRegion pTiledTextureRegion, final RectangleVertexBuffer pRectangleVertexBuffer) { super(pX, pY, pTileWidth, pTileHeight, pTiledTextureRegion, pRectangleVertexBuffer); } // =========================================================== // Getter & Setter // =========================================================== public boolean isAnimationRunning() { return this.mAnimationRunning; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override protected void onManagedUpdate(final float pSecondsElapsed) { super.onManagedUpdate(pSecondsElapsed); if(this.mAnimationRunning) { final long nanoSecondsElapsed = (long) (pSecondsElapsed * TimeConstants.NANOSECONDSPERSECOND); this.mAnimationProgress += nanoSecondsElapsed; if(this.mAnimationProgress > this.mAnimationDuration) { this.mAnimationProgress %= this.mAnimationDuration; if(this.mInitialLoopCount != AnimatedSprite.LOOP_CONTINUOUS) { this.mLoopCount--; } } if(this.mInitialLoopCount == AnimatedSprite.LOOP_CONTINUOUS || this.mLoopCount >= 0) { final int currentFrameIndex = this.calculateCurrentFrameIndex(); if(this.mFrames == null) { this.setCurrentTileIndex(this.mFirstTileIndex + currentFrameIndex); } else { this.setCurrentTileIndex(this.mFrames[currentFrameIndex]); } } else { this.mAnimationRunning = false; if(this.mAnimationListener != null) { this.mAnimationListener.onAnimationEnd(this); } } } } // =========================================================== // Methods // =========================================================== public void stopAnimation() { this.mAnimationRunning = false; } public void stopAnimation(final int pTileIndex) { this.mAnimationRunning = false; this.setCurrentTileIndex(pTileIndex); } private int calculateCurrentFrameIndex() { final long animationProgress = this.mAnimationProgress; final long[] frameEnds = this.mFrameEndsInNanoseconds; final int frameCount = this.mFrameCount; for(int i = 0; i < frameCount; i++) { if(frameEnds[i] > animationProgress) { return i; } } return frameCount - 1; } public AnimatedSprite animate(final long pFrameDurationEach) { return this.animate(pFrameDurationEach, true); } public AnimatedSprite animate(final long pFrameDurationEach, final boolean pLoop) { return this.animate(pFrameDurationEach, (pLoop) ? AnimatedSprite.LOOP_CONTINUOUS : 0, null); } public AnimatedSprite animate(final long pFrameDurationEach, final int pLoopCount) { return this.animate(pFrameDurationEach, pLoopCount, null); } public AnimatedSprite animate(final long pFrameDurationEach, final boolean pLoop, final IAnimationListener pAnimationListener) { return this.animate(pFrameDurationEach, (pLoop) ? AnimatedSprite.LOOP_CONTINUOUS : 0, pAnimationListener); } public AnimatedSprite animate(final long pFrameDurationEach, final int pLoopCount, final IAnimationListener pAnimationListener) { final long[] frameDurations = new long[this.getTextureRegion().getTileCount()]; Arrays.fill(frameDurations, pFrameDurationEach); return this.animate(frameDurations, pLoopCount, pAnimationListener); } public AnimatedSprite animate(final long[] pFrameDurations) { return this.animate(pFrameDurations, true); } public AnimatedSprite animate(final long[] pFrameDurations, final boolean pLoop) { return this.animate(pFrameDurations, (pLoop) ? AnimatedSprite.LOOP_CONTINUOUS : 0, null); } public AnimatedSprite animate(final long[] pFrameDurations, final int pLoopCount) { return this.animate(pFrameDurations, pLoopCount, null); } public AnimatedSprite animate(final long[] pFrameDurations, final boolean pLoop, final IAnimationListener pAnimationListener) { return this.animate(pFrameDurations, (pLoop) ? AnimatedSprite.LOOP_CONTINUOUS : 0, pAnimationListener); } public AnimatedSprite animate(final long[] pFrameDurations, final int pLoopCount, final IAnimationListener pAnimationListener) { return this.animate(pFrameDurations, 0, this.getTextureRegion().getTileCount() - 1, pLoopCount, pAnimationListener); } public AnimatedSprite animate(final long[] pFrameDurations, final int pFirstTileIndex, final int pLastTileIndex, final boolean pLoop) { return this.animate(pFrameDurations, pFirstTileIndex, pLastTileIndex, (pLoop) ? AnimatedSprite.LOOP_CONTINUOUS : 0, null); } public AnimatedSprite animate(final long[] pFrameDurations, final int pFirstTileIndex, final int pLastTileIndex, final int pLoopCount) { return this.animate(pFrameDurations, pFirstTileIndex, pLastTileIndex, pLoopCount, null); } public AnimatedSprite animate(final long[] pFrameDurations, final int[] pFrames, final int pLoopCount) { return this.animate(pFrameDurations, pFrames, pLoopCount, null); } /** * Animate specifics frames * * @param pFrameDurations must have the same length as pFrames. * @param pFrames indices of the frames to animate. * @param pLoopCount * @param pAnimationListener */ public AnimatedSprite animate(final long[] pFrameDurations, final int[] pFrames, final int pLoopCount, final IAnimationListener pAnimationListener) { final int frameCount = pFrames.length; if(pFrameDurations.length != frameCount) { throw new IllegalArgumentException("pFrameDurations must have the same length as pFrames."); } return this.init(pFrameDurations, frameCount, pFrames, 0, pLoopCount, pAnimationListener); } /** * @param pFrameDurations * must have the same length as pFirstTileIndex to * pLastTileIndex. * @param pFirstTileIndex * @param pLastTileIndex * @param pLoopCount * @param pAnimationListener */ public AnimatedSprite animate(final long[] pFrameDurations, final int pFirstTileIndex, final int pLastTileIndex, final int pLoopCount, final IAnimationListener pAnimationListener) { if(pLastTileIndex - pFirstTileIndex < 1) { throw new IllegalArgumentException("An animation needs at least two tiles to animate between."); } final int frameCount = (pLastTileIndex - pFirstTileIndex) + 1; if(pFrameDurations.length != frameCount) { throw new IllegalArgumentException("pFrameDurations must have the same length as pFirstTileIndex to pLastTileIndex."); } return this.init(pFrameDurations, frameCount, null, pFirstTileIndex, pLoopCount, pAnimationListener); } private AnimatedSprite init(final long[] pFrameDurations, final int frameCount, final int[] pFrames, final int pFirstTileIndex, final int pLoopCount, final IAnimationListener pAnimationListener) { this.mFrameCount = frameCount; this.mAnimationListener = pAnimationListener; this.mInitialLoopCount = pLoopCount; this.mLoopCount = pLoopCount; this.mFrames = pFrames; this.mFirstTileIndex = pFirstTileIndex; if(this.mFrameEndsInNanoseconds == null || this.mFrameCount > this.mFrameEndsInNanoseconds.length) { this.mFrameEndsInNanoseconds = new long[this.mFrameCount]; } final long[] frameEndsInNanoseconds = this.mFrameEndsInNanoseconds; MathUtils.arraySumInto(pFrameDurations, frameEndsInNanoseconds, TimeConstants.NANOSECONDSPERMILLISECOND); final long lastFrameEnd = frameEndsInNanoseconds[this.mFrameCount - 1]; this.mAnimationDuration = lastFrameEnd; this.mAnimationProgress = 0; this.mAnimationRunning = true; return this; } // =========================================================== // Inner and Anonymous Classes // =========================================================== public static interface IAnimationListener { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== public void onAnimationEnd(final AnimatedSprite pAnimatedSprite); } }
src/org/anddev/andengine/entity/sprite/AnimatedSprite.java
package org.anddev.andengine.entity.sprite; import java.util.Arrays; import org.anddev.andengine.opengl.texture.region.TiledTextureRegion; import org.anddev.andengine.opengl.vertex.RectangleVertexBuffer; import org.anddev.andengine.util.MathUtils; import org.anddev.andengine.util.constants.TimeConstants; public class AnimatedSprite extends TiledSprite implements TimeConstants { // =========================================================== // Constants // =========================================================== private static final int LOOP_CONTINUOUS = -1; // =========================================================== // Fields // =========================================================== private boolean mAnimationRunning; private long mAnimationProgress; private long mAnimationDuration; private long[] mFrameEndsInNanoseconds; private int mFirstTileIndex; private int mInitialLoopCount; private int mLoopCount; private IAnimationListener mAnimationListener; private int mFrameCount; private int[] mFrames; // =========================================================== // Constructors // =========================================================== public AnimatedSprite(final float pX, final float pY, final TiledTextureRegion pTiledTextureRegion) { super(pX, pY, pTiledTextureRegion); } public AnimatedSprite(final float pX, final float pY, final float pTileWidth, final float pTileHeight, final TiledTextureRegion pTiledTextureRegion) { super(pX, pY, pTileWidth, pTileHeight, pTiledTextureRegion); } public AnimatedSprite(final float pX, final float pY, final TiledTextureRegion pTiledTextureRegion, final RectangleVertexBuffer pRectangleVertexBuffer) { super(pX, pY, pTiledTextureRegion, pRectangleVertexBuffer); } public AnimatedSprite(final float pX, final float pY, final float pTileWidth, final float pTileHeight, final TiledTextureRegion pTiledTextureRegion, final RectangleVertexBuffer pRectangleVertexBuffer) { super(pX, pY, pTileWidth, pTileHeight, pTiledTextureRegion, pRectangleVertexBuffer); } // =========================================================== // Getter & Setter // =========================================================== public boolean isAnimationRunning() { return this.mAnimationRunning; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override protected void onManagedUpdate(final float pSecondsElapsed) { super.onManagedUpdate(pSecondsElapsed); if(this.mAnimationRunning) { final long nanoSecondsElapsed = (long) (pSecondsElapsed * TimeConstants.NANOSECONDSPERSECOND); this.mAnimationProgress += nanoSecondsElapsed; if(this.mAnimationProgress > this.mAnimationDuration) { this.mAnimationProgress %= this.mAnimationDuration; if(this.mInitialLoopCount != AnimatedSprite.LOOP_CONTINUOUS) { this.mLoopCount--; } } if(this.mInitialLoopCount == AnimatedSprite.LOOP_CONTINUOUS || this.mLoopCount >= 0) { final int currentFrameIndex = this.calculateCurrentFrameIndex(); if(this.mFrames == null) { this.setCurrentTileIndex(this.mFirstTileIndex + currentFrameIndex); } else { this.setCurrentTileIndex(this.mFrames[currentFrameIndex]); } } else { this.mAnimationRunning = false; if(this.mAnimationListener != null) { this.mAnimationListener.onAnimationEnd(this); } } } } // =========================================================== // Methods // =========================================================== public void stopAnimation() { this.mAnimationRunning = false; } public void stopAnimation(final int pTileIndex) { this.mAnimationRunning = false; this.setCurrentTileIndex(pTileIndex); } private int calculateCurrentFrameIndex() { final long animationProgress = this.mAnimationProgress; final long[] frameEnds = this.mFrameEndsInNanoseconds; final int frameCount = this.mFrameCount; for(int i = 0; i < frameCount; i++) { if(frameEnds[i] > animationProgress) { return i; } } return frameCount - 1; } public AnimatedSprite animate(final long pFrameDurationEach) { return this.animate(pFrameDurationEach, true); } public AnimatedSprite animate(final long pFrameDurationEach, final boolean pLoop) { return this.animate(pFrameDurationEach, (pLoop) ? AnimatedSprite.LOOP_CONTINUOUS : 0, null); } public AnimatedSprite animate(final long pFrameDurationEach, final int pLoopCount) { return this.animate(pFrameDurationEach, pLoopCount, null); } public AnimatedSprite animate(final long pFrameDurationEach, final boolean pLoop, final IAnimationListener pAnimationListener) { return this.animate(pFrameDurationEach, (pLoop) ? AnimatedSprite.LOOP_CONTINUOUS : 0, pAnimationListener); } public AnimatedSprite animate(final long pFrameDurationEach, final int pLoopCount, final IAnimationListener pAnimationListener) { final long[] frameDurations = new long[this.getTextureRegion().getTileCount()]; Arrays.fill(frameDurations, pFrameDurationEach); return this.animate(frameDurations, pLoopCount, pAnimationListener); } public AnimatedSprite animate(final long[] pFrameDurations) { return this.animate(pFrameDurations, true); } public AnimatedSprite animate(final long[] pFrameDurations, final boolean pLoop) { return this.animate(pFrameDurations, (pLoop) ? AnimatedSprite.LOOP_CONTINUOUS : 0, null); } public AnimatedSprite animate(final long[] pFrameDurations, final int pLoopCount) { return this.animate(pFrameDurations, pLoopCount, null); } public AnimatedSprite animate(final long[] pFrameDurations, final boolean pLoop, final IAnimationListener pAnimationListener) { return this.animate(pFrameDurations, (pLoop) ? AnimatedSprite.LOOP_CONTINUOUS : 0, pAnimationListener); } public AnimatedSprite animate(final long[] pFrameDurations, final int pLoopCount, final IAnimationListener pAnimationListener) { return this.animate(pFrameDurations, 0, this.getTextureRegion().getTileCount() - 1, pLoopCount, pAnimationListener); } public AnimatedSprite animate(final long[] pFrameDurations, final int pFirstTileIndex, final int pLastTileIndex, final boolean pLoop) { return this.animate(pFrameDurations, pFirstTileIndex, pLastTileIndex, (pLoop) ? AnimatedSprite.LOOP_CONTINUOUS : 0, null); } public AnimatedSprite animate(final long[] pFrameDurations, final int pFirstTileIndex, final int pLastTileIndex, final int pLoopCount) { return this.animate(pFrameDurations, pFirstTileIndex, pLastTileIndex, pLoopCount, null); } public AnimatedSprite animate(final long[] pFrameDurations, final int[] pFrames, final int pLoopCount) { return this.animate(pFrameDurations, pFrames, pLoopCount, null); } /** * Animate specifics frames * * @param pFrameDurations must have the same length as pFrames. * @param pFrames indices of the frames to animate. * @param pLoopCount * @param pAnimationListener */ public AnimatedSprite animate(final long[] pFrameDurations, final int[] pFrames, final int pLoopCount, final IAnimationListener pAnimationListener) { final int frameCount = pFrames.length; if(pFrameDurations.length != frameCount) { throw new IllegalArgumentException("pFrameDurations must have the same length as pFrames."); } return this.init(pFrameDurations, frameCount, pFrames, 0, pLoopCount, pAnimationListener); } /** * @param pFrameDurations * must have the same length as pFirstTileIndex to * pLastTileIndex. * @param pFirstTileIndex * @param pLastTileIndex * @param pLoopCount * @param pAnimationListener */ public AnimatedSprite animate(final long[] pFrameDurations, final int pFirstTileIndex, final int pLastTileIndex, final int pLoopCount, final IAnimationListener pAnimationListener) { if(pLastTileIndex - pFirstTileIndex < 1) { throw new IllegalArgumentException("An animation needs at least two tiles to animate between."); } final int frameCount = (pLastTileIndex - pFirstTileIndex) + 1; if(pFrameDurations.length != frameCount) { throw new IllegalArgumentException("pFrameDurations must have the same length as pFirstTileIndex to pLastTileIndex."); } return this.init(pFrameDurations, frameCount, null, pFirstTileIndex, pLoopCount, pAnimationListener); } private AnimatedSprite init(final long[] pFrameDurations, final int frameCount, final int[] pFrames, final int pFirstTileIndex, final int pLoopCount, final IAnimationListener pAnimationListener) { this.mFrameCount = frameCount; this.mAnimationListener = pAnimationListener; this.mInitialLoopCount = pLoopCount; this.mLoopCount = pLoopCount; this.mFrames = pFrames; this.mFirstTileIndex = pFirstTileIndex; if(this.mFrameEndsInNanoseconds == null || this.mFrameCount > this.mFrameEndsInNanoseconds.length) { this.mFrameEndsInNanoseconds = new long[this.mFrameCount]; } final long[] frameEndsInNanoseconds = this.mFrameEndsInNanoseconds; MathUtils.arraySumInto(pFrameDurations, frameEndsInNanoseconds, TimeConstants.NANOSECONDSPERMILLISECOND); final long lastFrameEnd = frameEndsInNanoseconds[this.mFrameCount - 1]; this.mAnimationDuration = lastFrameEnd; this.mAnimationProgress = 0; this.mAnimationRunning = true; return this; } // =========================================================== // Inner and Anonymous Classes // =========================================================== public static interface IAnimationListener { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== public void onAnimationEnd(final AnimatedSprite pAnimatedSprite); } }
Dummy commit.
src/org/anddev/andengine/entity/sprite/AnimatedSprite.java
Dummy commit.
Java
apache-2.0
15eb9fe02047a41e9523ebc736be729ede6bbc4a
0
otto-de/edison-microservice,otto-de/edison-microservice,otto-de/edison-microservice,otto-de/edison-microservice
package de.otto.edison.jobs.controller; import de.otto.edison.jobs.domain.JobInfo; import de.otto.edison.jobs.service.JobService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.List; import java.util.Optional; import static de.otto.edison.jobs.controller.JobRepresentation.representationOf; import static de.otto.edison.jobs.controller.UrlHelper.baseUriOf; import static java.util.stream.Collectors.toList; import static javax.servlet.http.HttpServletResponse.*; import static org.springframework.web.bind.annotation.RequestMethod.*; @Controller public class JobsController { private static final Logger LOG = LoggerFactory.getLogger(JobsController.class); @Autowired private JobService jobService; @Value("${server.context-path}") private String serverContextPath; public JobsController() { } JobsController(final JobService jobService) { this.jobService = jobService; } @RequestMapping(value = "/internal/jobs", method = GET, produces = "text/html") public ModelAndView getJobsAsHtml(@RequestParam(value = "type", required = false) String type, @RequestParam(value = "count", defaultValue = "100") int count, @RequestParam(value = "distinct", defaultValue = "true", required = false) boolean distinct, HttpServletRequest request) { final List<JobRepresentation> jobRepresentations = getJobInfos(type, count, distinct).stream() .map((j) -> representationOf(j, true, baseUriOf(request))) .collect(toList()); final ModelAndView modelAndView = new ModelAndView("jobs"); modelAndView.addObject("jobs", jobRepresentations); return modelAndView; } @RequestMapping(value = "/internal/jobs", method = GET, produces = "application/json") @ResponseBody public List<JobRepresentation> getJobsAsJson(@RequestParam(value = "type", required = false) String type, @RequestParam(value = "count", defaultValue = "100") int count, @RequestParam(value = "distinct", defaultValue = "true", required = false) boolean distinct, HttpServletRequest request) { return getJobInfos(type, count, distinct) .stream() .map((j) -> representationOf(j, false, baseUriOf(request))) .collect(toList()); } @RequestMapping(value = "/internal/jobs", method = DELETE) public void deleteJobs(@RequestParam(value = "type", required = false) String type) { jobService.deleteJobs(Optional.ofNullable(type)); } /** * Starts a new job of the specified type, if no such job is currently running. * <p> * The method will return immediately, without waiting for the job to complete. * <p> * If a job with same type is running, the response will have HTTP status 409 CONFLICT, * otherwise HTTP 204 NO CONTENT is returned, together with the response header 'Location', * containing the full URL of the running job. * * @param jobType the type of the started job * @param request the HttpServletRequest used to determine the base URL * @param response the HttpServletResponse used to set the Location header * @throws IOException in case the job was not able to start properly (ie. conflict) */ @RequestMapping( value = "/internal/jobs/{jobType}", method = POST) public void startJob(final @PathVariable String jobType, final HttpServletRequest request, final HttpServletResponse response) throws IOException { final Optional<String> jobId = jobService.startAsyncJob(jobType); if (jobId.isPresent()) { response.setHeader("Location", baseUriOf(request) + "/internal/jobs/" + jobId.get()); response.setStatus(SC_NO_CONTENT); } else { response.sendError(SC_CONFLICT); } } @RequestMapping( value = "/internal/jobs/{jobType}/disable", method = POST ) public String disableJobType(final @PathVariable String jobType) { jobService.disableJobType(jobType); return "redirect:/internal/jobdefinitions"; } @RequestMapping( value = "/internal/jobs/{jobType}/enable", method = POST ) public String enableJobType(final @PathVariable String jobType) { jobService.enableJobType(jobType); return "redirect:/internal/jobdefinitions"; } @RequestMapping(value = "/internal/jobs/{id}", method = GET, produces = "text/html") public ModelAndView getJobAsHtml(final HttpServletRequest request, final HttpServletResponse response, @PathVariable("id") final String jobId) throws IOException { setCorsHeaders(response); final Optional<JobInfo> optionalJob = jobService.findJob(jobId); if (optionalJob.isPresent()) { final ModelAndView modelAndView = new ModelAndView("job"); modelAndView.addObject("job", representationOf(optionalJob.get(), true, baseUriOf(request))); return modelAndView; } else { response.sendError(SC_NOT_FOUND, "Job not found"); return null; } } @RequestMapping(value = "/internal/jobs/{id}", method = GET, produces = "application/json") @ResponseBody public JobRepresentation getJob(final HttpServletRequest request, final HttpServletResponse response, @PathVariable("id") final String jobId) throws IOException { setCorsHeaders(response); final Optional<JobInfo> optionalJob = jobService.findJob(jobId); if (optionalJob.isPresent()) { return representationOf(optionalJob.get(), false, baseUriOf(request)); } else { response.sendError(SC_NOT_FOUND, "Job not found"); return null; } } private void setCorsHeaders(final HttpServletResponse response) { response.setHeader("Access-Control-Allow-Methods", "GET"); response.setHeader("Access-Control-Allow-Origin", "*"); } private List<JobInfo> getJobInfos(String type, int count, boolean distinct) { final List<JobInfo> jobInfos; if (distinct) { jobInfos = jobService.findJobsDistinct(); } else { jobInfos = jobService.findJobs(Optional.ofNullable(type), count); } return jobInfos; } }
edison-jobs/src/main/java/de/otto/edison/jobs/controller/JobsController.java
package de.otto.edison.jobs.controller; import de.otto.edison.jobs.domain.JobInfo; import de.otto.edison.jobs.service.JobService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.List; import java.util.Optional; import static de.otto.edison.jobs.controller.JobRepresentation.representationOf; import static de.otto.edison.jobs.controller.UrlHelper.baseUriOf; import static java.util.stream.Collectors.toList; import static javax.servlet.http.HttpServletResponse.*; import static org.springframework.web.bind.annotation.RequestMethod.*; @Controller public class JobsController { private static final Logger LOG = LoggerFactory.getLogger(JobsController.class); @Autowired private JobService jobService; @Value("${server.context-path}") private String serverContextPath; public JobsController() { } JobsController(final JobService jobService) { this.jobService = jobService; } @RequestMapping(value = "/internal/jobs", method = GET, produces = "text/html") public ModelAndView getJobsAsHtml(@RequestParam(value = "type", required = false) String type, @RequestParam(value = "count", defaultValue = "100") int count, @RequestParam(value = "distinct", defaultValue = "false", required = false) boolean distinct, HttpServletRequest request) { final List<JobRepresentation> jobRepresentations = getJobInfos(type, count, distinct).stream() .map((j) -> representationOf(j, true, baseUriOf(request))) .collect(toList()); final ModelAndView modelAndView = new ModelAndView("jobs"); modelAndView.addObject("jobs", jobRepresentations); return modelAndView; } @RequestMapping(value = "/internal/jobs", method = GET, produces = "application/json") @ResponseBody public List<JobRepresentation> getJobsAsJson(@RequestParam(value = "type", required = false) String type, @RequestParam(value = "count", defaultValue = "100") int count, @RequestParam(value = "distinct", defaultValue = "false", required = false) boolean distinct, HttpServletRequest request) { return getJobInfos(type, count, distinct) .stream() .map((j) -> representationOf(j, false, baseUriOf(request))) .collect(toList()); } @RequestMapping(value = "/internal/jobs", method = DELETE) public void deleteJobs(@RequestParam(value = "type", required = false) String type) { jobService.deleteJobs(Optional.ofNullable(type)); } /** * Starts a new job of the specified type, if no such job is currently running. * <p> * The method will return immediately, without waiting for the job to complete. * <p> * If a job with same type is running, the response will have HTTP status 409 CONFLICT, * otherwise HTTP 204 NO CONTENT is returned, together with the response header 'Location', * containing the full URL of the running job. * * @param jobType the type of the started job * @param request the HttpServletRequest used to determine the base URL * @param response the HttpServletResponse used to set the Location header * @throws IOException in case the job was not able to start properly (ie. conflict) */ @RequestMapping( value = "/internal/jobs/{jobType}", method = POST) public void startJob(final @PathVariable String jobType, final HttpServletRequest request, final HttpServletResponse response) throws IOException { final Optional<String> jobId = jobService.startAsyncJob(jobType); if (jobId.isPresent()) { response.setHeader("Location", baseUriOf(request) + "/internal/jobs/" + jobId.get()); response.setStatus(SC_NO_CONTENT); } else { response.sendError(SC_CONFLICT); } } @RequestMapping( value = "/internal/jobs/{jobType}/disable", method = POST ) public String disableJobType(final @PathVariable String jobType) { jobService.disableJobType(jobType); return "redirect:/internal/jobdefinitions"; } @RequestMapping( value = "/internal/jobs/{jobType}/enable", method = POST ) public String enableJobType(final @PathVariable String jobType) { jobService.enableJobType(jobType); return "redirect:/internal/jobdefinitions"; } @RequestMapping(value = "/internal/jobs/{id}", method = GET, produces = "text/html") public ModelAndView getJobAsHtml(final HttpServletRequest request, final HttpServletResponse response, @PathVariable("id") final String jobId) throws IOException { setCorsHeaders(response); final Optional<JobInfo> optionalJob = jobService.findJob(jobId); if (optionalJob.isPresent()) { final ModelAndView modelAndView = new ModelAndView("job"); modelAndView.addObject("job", representationOf(optionalJob.get(), true, baseUriOf(request))); return modelAndView; } else { response.sendError(SC_NOT_FOUND, "Job not found"); return null; } } @RequestMapping(value = "/internal/jobs/{id}", method = GET, produces = "application/json") @ResponseBody public JobRepresentation getJob(final HttpServletRequest request, final HttpServletResponse response, @PathVariable("id") final String jobId) throws IOException { setCorsHeaders(response); final Optional<JobInfo> optionalJob = jobService.findJob(jobId); if (optionalJob.isPresent()) { return representationOf(optionalJob.get(), false, baseUriOf(request)); } else { response.sendError(SC_NOT_FOUND, "Job not found"); return null; } } private void setCorsHeaders(final HttpServletResponse response) { response.setHeader("Access-Control-Allow-Methods", "GET"); response.setHeader("Access-Control-Allow-Origin", "*"); } private List<JobInfo> getJobInfos(String type, int count, boolean distinct) { final List<JobInfo> jobInfos; if (distinct) { jobInfos = jobService.findJobsDistinct(); } else { jobInfos = jobService.findJobs(Optional.ofNullable(type), count); } return jobInfos; } }
change default of joboverview to show distinct jobs
edison-jobs/src/main/java/de/otto/edison/jobs/controller/JobsController.java
change default of joboverview to show distinct jobs
Java
apache-2.0
1ad1a4374e7b5a79d20c83d136cc79b688d33f56
0
henry-newbie/CalendarView
package com.henry.calendarview; import android.content.Context; import android.content.res.Resources; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Paint.Align; import android.graphics.Paint.Style; import android.graphics.RectF; import android.graphics.Typeface; import android.text.format.DateUtils; import android.text.format.Time; import android.view.MotionEvent; import android.view.View; import java.security.InvalidParameterException; import java.text.DateFormatSymbols; import java.util.Calendar; import java.util.HashMap; import java.util.List; import java.util.Locale; /** * 每个月作为一个ItemView */ class SimpleMonthView extends View { public static final String VIEW_PARAMS_SELECTED_BEGIN_DATE = "selected_begin_date"; public static final String VIEW_PARAMS_SELECTED_LAST_DATE = "selected_last_date"; public static final String VIEW_PARAMS_NEAREST_DATE = "mNearestDay"; // public static final String VIEW_PARAMS_HEIGHT = "height"; public static final String VIEW_PARAMS_MONTH = "month"; public static final String VIEW_PARAMS_YEAR = "year"; public static final String VIEW_PARAMS_WEEK_START = "week_start"; private static final int SELECTED_CIRCLE_ALPHA = 128; protected static int DEFAULT_HEIGHT = 32; // 默认一行的高度 protected static final int DEFAULT_NUM_ROWS = 6; protected static int DAY_SELECTED_RECT_SIZE; // 选中圆角矩形半径 protected static int ROW_SEPARATOR = 12; // 每行中间的间距 protected static int MINI_DAY_NUMBER_TEXT_SIZE; // 日期字体的最小尺寸 private static int TAG_TEXT_SIZE; // 标签字体大小 protected static int MIN_HEIGHT = 10; // 最小高度 // protected static int MONTH_DAY_LABEL_TEXT_SIZE; // 头部的星期几的字体大小 protected static int MONTH_HEADER_SIZE; // 头部的高度(包括年份月份,星期几) protected static int YEAR_MONTH_TEXT_SIZE; // 头部年份月份的字体大小 protected static int WEEK_TEXT_SIZE; // 头部年份月份的字体大小 // private final int mSelectType; // 类型 // private boolean mIsDisplayTag; // 是否显示标签 private List<SimpleMonthAdapter.CalendarDay> mInvalidDays; // 禁用的日期 private List<SimpleMonthAdapter.CalendarDay> mBusyDays; // 被占用的日期 private SimpleMonthAdapter.CalendarDay mNearestDay; // 比离入住日期大且是最近的已被占用或者无效日期 private List<SimpleMonthAdapter.CalendarDay> mCalendarTags; // 日期下面的标签 private String mDefTag = "标签"; protected int mPadding = 0; private String mDayOfWeekTypeface; private String mMonthTitleTypeface; protected Paint mWeekTextPaint; // 头部星期几的字体画笔 protected Paint mDayTextPaint; protected Paint mTagTextPaint; // 日期底部的文字画笔 // protected Paint mTitleBGPaint; protected Paint mYearMonthPaint; // 头部的画笔 protected Paint mSelectedDayBgPaint; protected Paint mBusyDayBgPaint; protected Paint mInValidDayBgPaint; // protected Paint mSelectedDayTextPaint; protected int mCurrentDayTextColor; // 今天的字体颜色 protected int mYearMonthTextColor; // 头部年份和月份字体颜色 protected int mWeekTextColor; // 头部星期几字体颜色 // protected int mDayTextColor; protected int mDayTextColor; // 日期字体颜色 protected int mSelectedDayTextColor; // 被选中的日期字体颜色 protected int mPreviousDayTextColor; // 过去的字体颜色 protected int mSelectedDaysBgColor; // 选中的日期背景颜色 protected int mBusyDaysBgColor; // 被占用的日期背景颜色 protected int mInValidDaysBgColor; // 禁用的日期背景颜色 protected int mBusyDaysTextColor; // 被占用的日期字体颜色 protected int mInValidDaysTextColor; // 禁用的日期字体颜色 private final StringBuilder mStringBuilder; protected boolean mHasToday = false; protected int mToday = -1; protected int mWeekStart = 1; // 一周的第一天(不同国家的一星期的第一天不同) protected int mNumDays = 7; // 一行几列 protected int mNumCells; // 一个月有多少天 private int mDayOfWeekStart = 0; // 日期对应星期几 // protected Boolean mDrawRect; // 圆角还是圆形 protected int mRowHeight = DEFAULT_HEIGHT; // 行高 protected int mWidth; // simpleMonthView的宽度 protected int mYear; protected int mMonth; final Time today; private final Calendar mCalendar; private final Calendar mDayLabelCalendar; // 用于显示星期几 private final Boolean isPrevDayEnabled; // 今天以前的日期是否能被操作 private int mNumRows; private DateFormatSymbols mDateFormatSymbols = new DateFormatSymbols(); private OnDayClickListener mOnDayClickListener; SimpleMonthAdapter.CalendarDay mStartDate; // 入住日期 SimpleMonthAdapter.CalendarDay mEndDate; // 退房日期 SimpleMonthAdapter.CalendarDay cellCalendar; // cell的对应的日期 /** * @param context * @param typedArray * @param dataModel */ public SimpleMonthView(Context context, TypedArray typedArray, DayPickerView.DataModel dataModel) { super(context); Resources resources = context.getResources(); mDayLabelCalendar = Calendar.getInstance(); mCalendar = Calendar.getInstance(); today = new Time(Time.getCurrentTimezone()); today.setToNow(); mDayOfWeekTypeface = resources.getString(R.string.sans_serif); mMonthTitleTypeface = resources.getString(R.string.sans_serif); mCurrentDayTextColor = typedArray.getColor(R.styleable.DayPickerView_colorCurrentDay, resources.getColor(R.color.normal_day)); mYearMonthTextColor = typedArray.getColor(R.styleable.DayPickerView_colorYearMonthText, resources.getColor(R.color.normal_day)); mWeekTextColor = typedArray.getColor(R.styleable.DayPickerView_colorWeekText, resources.getColor(R.color.normal_day)); // mDayTextColor = typedArray.getColor(R.styleable.DayPickerView_colorDayName, resources.getColor(R.color.normal_day)); mDayTextColor = typedArray.getColor(R.styleable.DayPickerView_colorNormalDayText, resources.getColor(R.color.normal_day)); mPreviousDayTextColor = typedArray.getColor(R.styleable.DayPickerView_colorPreviousDayText, resources.getColor(R.color.normal_day)); mSelectedDaysBgColor = typedArray.getColor(R.styleable.DayPickerView_colorSelectedDayBackground, resources.getColor(R.color.selected_day_background)); mSelectedDayTextColor = typedArray.getColor(R.styleable.DayPickerView_colorSelectedDayText, resources.getColor(R.color.selected_day_text)); mBusyDaysBgColor = typedArray.getColor(R.styleable.DayPickerView_colorBusyDaysBg, Color.GRAY); mInValidDaysBgColor = typedArray.getColor(R.styleable.DayPickerView_colorInValidDaysBg, Color.GRAY); mBusyDaysTextColor = typedArray.getColor(R.styleable.DayPickerView_colorBusyDaysText, resources.getColor(R.color.normal_day)); mInValidDaysTextColor = typedArray.getColor(R.styleable.DayPickerView_colorInValidDaysText, resources.getColor(R.color.normal_day)); // mDrawRect = typedArray.getBoolean(R.styleable.DayPickerView_drawRoundRect, true); mStringBuilder = new StringBuilder(50); MINI_DAY_NUMBER_TEXT_SIZE = typedArray.getDimensionPixelSize(R.styleable.DayPickerView_textSizeDay, resources.getDimensionPixelSize(R.dimen.text_size_day)); TAG_TEXT_SIZE = typedArray.getDimensionPixelSize(R.styleable.DayPickerView_textSizeTag, resources.getDimensionPixelSize(R.dimen.text_size_tag)); YEAR_MONTH_TEXT_SIZE = typedArray.getDimensionPixelSize(R.styleable.DayPickerView_textSizeYearMonth, resources.getDimensionPixelSize(R.dimen.text_size_month)); WEEK_TEXT_SIZE = typedArray.getDimensionPixelSize(R.styleable.DayPickerView_textSizeWeek, resources.getDimensionPixelSize(R.dimen.text_size_day_name)); MONTH_HEADER_SIZE = typedArray.getDimensionPixelOffset(R.styleable.DayPickerView_headerMonthHeight, resources.getDimensionPixelOffset(R.dimen.header_month_height)); DAY_SELECTED_RECT_SIZE = typedArray.getDimensionPixelSize(R.styleable.DayPickerView_selectedDayRadius, resources.getDimensionPixelOffset(R.dimen.selected_day_radius)); mRowHeight = ((typedArray.getDimensionPixelSize(R.styleable.DayPickerView_calendarHeight, resources.getDimensionPixelOffset(R.dimen.calendar_height)) - MONTH_HEADER_SIZE - ROW_SEPARATOR) / 6); isPrevDayEnabled = typedArray.getBoolean(R.styleable.DayPickerView_enablePreviousDay, false); mInvalidDays = dataModel.invalidDays; mBusyDays = dataModel.busyDays; mCalendarTags = dataModel.tags; mDefTag = dataModel.defTag; cellCalendar = new SimpleMonthAdapter.CalendarDay(); initView(); } /** * 计算每个月的日期占用的行数 * * @return */ private int calculateNumRows() { int offset = findDayOffset(); int dividend = (offset + mNumCells) / mNumDays; int remainder = (offset + mNumCells) % mNumDays; return (dividend + (remainder > 0 ? 1 : 0)); } /** * 绘制头部的一行星期几 * * @param canvas */ private void drawMonthDayLabels(Canvas canvas) { int y = MONTH_HEADER_SIZE - (WEEK_TEXT_SIZE / 2); // 一个cell的二分之宽度 int dayWidthHalf = (mWidth - mPadding * 2) / (mNumDays * 2); for (int i = 0; i < mNumDays; i++) { int calendarDay = (i + mWeekStart) % mNumDays; int x = (2 * i + 1) * dayWidthHalf + mPadding; mDayLabelCalendar.set(Calendar.DAY_OF_WEEK, calendarDay); canvas.drawText(mDateFormatSymbols.getShortWeekdays()[mDayLabelCalendar.get(Calendar.DAY_OF_WEEK)].toUpperCase(Locale.getDefault()), x, y, mWeekTextPaint); } } /** * 绘制头部(年份月份,星期几) * * @param canvas */ private void drawMonthTitle(Canvas canvas) { int x = (mWidth + 2 * mPadding) / 2; int y = (MONTH_HEADER_SIZE - WEEK_TEXT_SIZE) / 2 + (YEAR_MONTH_TEXT_SIZE / 3); StringBuilder stringBuilder = new StringBuilder(getMonthAndYearString().toLowerCase()); stringBuilder.setCharAt(0, Character.toUpperCase(stringBuilder.charAt(0))); canvas.drawText(stringBuilder.toString(), x, y, mYearMonthPaint); } /** * 每个月第一天是星期几 * * @return */ private int findDayOffset() { return (mDayOfWeekStart < mWeekStart ? (mDayOfWeekStart + mNumDays) : mDayOfWeekStart) - mWeekStart; } /** * 获取年份和月份 * * @return */ private String getMonthAndYearString() { int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_YEAR | DateUtils.FORMAT_NO_MONTH_DAY; mStringBuilder.setLength(0); long millis = mCalendar.getTimeInMillis(); return DateUtils.formatDateRange(getContext(), millis, millis, flags); } private void onDayClick(SimpleMonthAdapter.CalendarDay calendarDay) { if (mOnDayClickListener != null && (isPrevDayEnabled || !prevDay(calendarDay.day, today))) { mOnDayClickListener.onDayClick(this, calendarDay); } } private boolean sameDay(int monthDay, Time time) { return (mYear == time.year) && (mMonth == time.month) && (monthDay == time.monthDay); } /** * 判断是否是已经过去的日期 * * @param monthDay * @param time * @return */ private boolean prevDay(int monthDay, Time time) { return ((mYear < time.year)) || (mYear == time.year && mMonth < time.month) || (mYear == time.year && mMonth == time.month && monthDay < time.monthDay); } /** * 绘制所有的cell * * @param canvas */ protected void drawMonthCell(Canvas canvas) { // ? int y = MONTH_HEADER_SIZE + ROW_SEPARATOR + mRowHeight / 2; int paddingDay = (mWidth - 2 * mPadding) / (2 * mNumDays); int dayOffset = findDayOffset(); int day = 1; while (day <= mNumCells) { int x = paddingDay * (1 + dayOffset * 2) + mPadding; mDayTextPaint.setColor(mDayTextColor); mDayTextPaint.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL)); mTagTextPaint.setColor(mDayTextColor); cellCalendar.setDay(mYear, mMonth, day); // 当天 boolean isToady = false; if (mHasToday && (mToday == day)) { isToady = true; canvas.drawText("今天", x, getTextYCenter(mDayTextPaint, y - DAY_SELECTED_RECT_SIZE / 2), mDayTextPaint); } // 已过去的日期 boolean isPrevDay = false; if (!isPrevDayEnabled && prevDay(day, today)) { isPrevDay = true; mDayTextPaint.setColor(mPreviousDayTextColor); mDayTextPaint.setTypeface(Typeface.defaultFromStyle(Typeface.ITALIC)); canvas.drawText(String.format("%d", day), x, y, mDayTextPaint); } boolean isBeginDay = false; // 绘制起始日期的方格 if (mStartDate != null && cellCalendar.equals(mStartDate) && !mStartDate.equals(mEndDate)) { isBeginDay = true; drawDayBg(canvas, x, y, mSelectedDayBgPaint); mDayTextPaint.setColor(mSelectedDayTextColor); canvas.drawText("入住", x, getTextYCenter(mDayTextPaint, y + DAY_SELECTED_RECT_SIZE / 2), mDayTextPaint); } boolean isLastDay = false; // 绘制结束日期的方格 if (mEndDate != null && cellCalendar.equals(mEndDate) && !mStartDate.equals(mEndDate)) { isLastDay = true; drawDayBg(canvas, x, y, mSelectedDayBgPaint); mDayTextPaint.setColor(mSelectedDayTextColor); canvas.drawText("退房", x, getTextYCenter(mDayTextPaint, y + DAY_SELECTED_RECT_SIZE / 2), mDayTextPaint); } // 在入住和退房之间的日期 if (cellCalendar.after(mStartDate) && cellCalendar.before(mEndDate)) { mDayTextPaint.setColor(mSelectedDayTextColor); drawDayBg(canvas, x, y, mSelectedDayBgPaint); // 标签变为白色 mTagTextPaint.setColor(Color.WHITE); // canvas.drawText(String.format("%d", day), x, y - DAY_SELECTED_RECT_SIZE / 2, mDayTextPaint); } // 被占用的日期 boolean isBusyDay = false; for (SimpleMonthAdapter.CalendarDay calendarDay : mBusyDays) { if (cellCalendar.equals(calendarDay) && !isPrevDay) { isBusyDay = true; // RectF rectF = new RectF(x - DAY_SELECTED_RECT_SIZE, // (y - MINI_DAY_NUMBER_TEXT_SIZE / 3) - DAY_SELECTED_RECT_SIZE, // x + DAY_SELECTED_RECT_SIZE, (y - MINI_DAY_NUMBER_TEXT_SIZE / 3) + DAY_SELECTED_RECT_SIZE); // 选择了入住和退房日期,退房日期等于mNearestDay的情况 if (mStartDate != null && mEndDate != null && mNearestDay != null && mEndDate.equals(mNearestDay) && mEndDate.equals(calendarDay)) { } else { // 选择了入住日期,没有选择退房日期,mNearestDay变为可选且不变灰色 if (mStartDate != null && mEndDate == null && mNearestDay != null && cellCalendar.equals(mNearestDay)) { mDayTextPaint.setColor(mDayTextColor); } else { drawDayBg(canvas, x, y, mBusyDayBgPaint); // canvas.drawRoundRect(rectF, 10.0f, 10.0f, mBusyDayBgPaint); mDayTextPaint.setColor(mBusyDaysTextColor); } canvas.drawText("已租", x, getTextYCenter(mBusyDayBgPaint, y + DAY_SELECTED_RECT_SIZE / 2), mDayTextPaint); } canvas.drawText(String.format("%d", day), x, getTextYCenter(mTagTextPaint, y - DAY_SELECTED_RECT_SIZE / 2), mDayTextPaint); } } // 禁用的日期 boolean isInvalidDays = false; for (SimpleMonthAdapter.CalendarDay calendarDay : mInvalidDays) { if (cellCalendar.equals(calendarDay) && !isPrevDay) { isBusyDay = true; // RectF rectF = new RectF(x - DAY_SELECTED_RECT_SIZE, // (y - MINI_DAY_NUMBER_TEXT_SIZE / 3) - DAY_SELECTED_RECT_SIZE, // x + DAY_SELECTED_RECT_SIZE, (y - MINI_DAY_NUMBER_TEXT_SIZE / 3) + DAY_SELECTED_RECT_SIZE); // 选择了入住和退房日期,退房日期等于mNearestDay的情况 if (mStartDate != null && mEndDate != null && mNearestDay != null && mEndDate.equals(mNearestDay) && mEndDate.equals(calendarDay)) { } else { // 选择了入住日期,没有选择退房日期,mNearestDay变为可选且不变灰色 if (mStartDate != null && mEndDate == null && mNearestDay != null && cellCalendar.equals(mNearestDay)) { mDayTextPaint.setColor(mDayTextColor); } else { drawDayBg(canvas, x, y, mInValidDayBgPaint); // canvas.drawRoundRect(rectF, 10.0f, 10.0f, mBusyDayBgPaint); mDayTextPaint.setColor(mInValidDaysTextColor); } canvas.drawText("禁用", x, getTextYCenter(mInValidDayBgPaint, y + DAY_SELECTED_RECT_SIZE / 2), mDayTextPaint); } canvas.drawText(String.format("%d", day), x, getTextYCenter(mTagTextPaint, y - DAY_SELECTED_RECT_SIZE / 2), mDayTextPaint); } } // 把入住日期之前和不可用日期之后的日期全部灰掉(思路: // 1:入住日期和退房日期不能同一天 // 2:只选择了入住日期且没有选择退房日期 // 3:比入住日期小全部变灰且不可点击 // 4:比入住日期大且离入住日期最近的被禁用或者被占用的日期 if (mStartDate != null && mEndDate == null && !mStartDate.equals(mEndDate) && !isInvalidDays && !isBusyDay) { if (cellCalendar.before(mStartDate) || (mNearestDay != null && cellCalendar.after(mNearestDay))) { // RectF rectF = new RectF(x - DAY_SELECTED_RECT_SIZE, (y - MINI_DAY_NUMBER_TEXT_SIZE / 3) - DAY_SELECTED_RECT_SIZE, // x + DAY_SELECTED_RECT_SIZE, (y - MINI_DAY_NUMBER_TEXT_SIZE / 3) + DAY_SELECTED_RECT_SIZE); // canvas.drawRoundRect(rectF, 10.0f, 10.0f, mBusyDayBgPaint); drawDayBg(canvas, x, y, mBusyDayBgPaint); } } // 绘制标签 if (!isPrevDay && !isInvalidDays && !isBusyDay && !isBeginDay && !isLastDay) { boolean isCalendarTag = false; for (SimpleMonthAdapter.CalendarDay calendarDay : mCalendarTags) { if (cellCalendar.equals(calendarDay)) { isCalendarTag = true; canvas.drawText(calendarDay.tag, x, getTextYCenter(mTagTextPaint, y + DAY_SELECTED_RECT_SIZE / 2), mTagTextPaint); } } if (!isCalendarTag) { canvas.drawText(mDefTag, x, getTextYCenter(mTagTextPaint, y + DAY_SELECTED_RECT_SIZE / 2), mTagTextPaint); } } // 绘制日期 if (!isToady && !isPrevDay && !isInvalidDays && !isBusyDay) { canvas.drawText(String.format("%d", day), x, getTextYCenter(mTagTextPaint, y - DAY_SELECTED_RECT_SIZE / 2), mDayTextPaint); } dayOffset++; if (dayOffset == mNumDays) { dayOffset = 0; y += mRowHeight; } day++; } } /** * 根据坐标获取对应的日期 * @param x * @param y * @return */ public SimpleMonthAdapter.CalendarDay getDayFromLocation(float x, float y) { int padding = mPadding; if ((x < padding) || (x > mWidth - mPadding)) { return null; } int yDay = (int) (y - MONTH_HEADER_SIZE) / mRowHeight; int day = 1 + ((int) ((x - padding) * mNumDays / (mWidth - padding - mPadding)) - findDayOffset()) + yDay * mNumDays; if (mMonth > 11 || mMonth < 0 || CalendarUtils.getDaysInMonth(mMonth, mYear) < day || day < 1) return null; SimpleMonthAdapter.CalendarDay calendar = new SimpleMonthAdapter.CalendarDay(mYear, mMonth, day); // 获取日期下面的tag boolean flag = false; for (SimpleMonthAdapter.CalendarDay calendarTag : mCalendarTags) { if (calendarTag.compareTo(calendar) == 0) { flag = true; calendar = calendarTag; } } if (!flag) { calendar.tag = mDefTag; } return calendar; } /** * 初始化一些paint */ protected void initView() { // 头部年份和月份的字体paint mYearMonthPaint = new Paint(); mYearMonthPaint.setFakeBoldText(true); mYearMonthPaint.setAntiAlias(true); mYearMonthPaint.setTextSize(YEAR_MONTH_TEXT_SIZE); mYearMonthPaint.setTypeface(Typeface.create(mMonthTitleTypeface, Typeface.BOLD)); mYearMonthPaint.setColor(mYearMonthTextColor); mYearMonthPaint.setTextAlign(Align.CENTER); mYearMonthPaint.setStyle(Style.FILL); // 头部星期几字体paint mWeekTextPaint = new Paint(); mWeekTextPaint.setAntiAlias(true); mWeekTextPaint.setTextSize(WEEK_TEXT_SIZE); mWeekTextPaint.setColor(mWeekTextColor); mWeekTextPaint.setTypeface(Typeface.create(mDayOfWeekTypeface, Typeface.NORMAL)); mWeekTextPaint.setStyle(Style.FILL); mWeekTextPaint.setTextAlign(Align.CENTER); mWeekTextPaint.setFakeBoldText(true); // // 头部背景paint // mTitleBGPaint = new Paint(); // mTitleBGPaint.setFakeBoldText(true); // mTitleBGPaint.setAntiAlias(true); // mTitleBGPaint.setColor(mSelectedDayTextColor); // mTitleBGPaint.setTextAlign(Align.CENTER); // mTitleBGPaint.setStyle(Style.FILL); // 被选中的日期背景paint mSelectedDayBgPaint = new Paint(); mSelectedDayBgPaint.setFakeBoldText(true); mSelectedDayBgPaint.setAntiAlias(true); mSelectedDayBgPaint.setColor(mSelectedDaysBgColor); mSelectedDayBgPaint.setTextAlign(Align.CENTER); mSelectedDayBgPaint.setStyle(Style.FILL); mSelectedDayBgPaint.setAlpha(SELECTED_CIRCLE_ALPHA); // 被占用的日期paint mBusyDayBgPaint = new Paint(); mBusyDayBgPaint.setFakeBoldText(true); mBusyDayBgPaint.setAntiAlias(true); mBusyDayBgPaint.setColor(mBusyDaysBgColor); mBusyDayBgPaint.setTextSize(TAG_TEXT_SIZE); mBusyDayBgPaint.setTextAlign(Align.CENTER); mBusyDayBgPaint.setStyle(Style.FILL); mBusyDayBgPaint.setAlpha(SELECTED_CIRCLE_ALPHA); // 禁用的日期paint mInValidDayBgPaint = new Paint(); mInValidDayBgPaint.setFakeBoldText(true); mInValidDayBgPaint.setAntiAlias(true); mInValidDayBgPaint.setColor(mInValidDaysBgColor); mInValidDayBgPaint.setTextSize(TAG_TEXT_SIZE); mInValidDayBgPaint.setTextAlign(Align.CENTER); mInValidDayBgPaint.setStyle(Style.FILL); mInValidDayBgPaint.setAlpha(SELECTED_CIRCLE_ALPHA); // // 被选中的日期字体paint // mSelectedDayTextPaint = new Paint(); // mSelectedDayTextPaint.setAntiAlias(true); // mSelectedDayTextPaint.setTextSize(MONTH_DAY_LABEL_TEXT_SIZE); // mSelectedDayTextPaint.setColor(Color.WHITE); // mSelectedDayTextPaint.setTypeface(Typeface.create(mDayOfWeekTypeface, Typeface.NORMAL)); // mSelectedDayTextPaint.setStyle(Style.FILL); // mSelectedDayTextPaint.setTextAlign(Align.CENTER); // mSelectedDayTextPaint.setFakeBoldText(true); // 日期字体paint mDayTextPaint = new Paint(); mDayTextPaint.setAntiAlias(true); mDayTextPaint.setColor(mDayTextColor); mDayTextPaint.setTextSize(MINI_DAY_NUMBER_TEXT_SIZE); mDayTextPaint.setStyle(Style.FILL); mDayTextPaint.setTextAlign(Align.CENTER); mDayTextPaint.setFakeBoldText(false); // 标签字体paint mTagTextPaint = new Paint(); mTagTextPaint.setAntiAlias(true); mTagTextPaint.setColor(mDayTextColor); mTagTextPaint.setTextSize(TAG_TEXT_SIZE); mTagTextPaint.setStyle(Style.FILL); mTagTextPaint.setTextAlign(Align.CENTER); mTagTextPaint.setFakeBoldText(false); } @Override protected void onDraw(Canvas canvas) { drawMonthTitle(canvas); drawMonthDayLabels(canvas); drawMonthCell(canvas); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { // 设置simpleMonthView的宽度和高度 setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec), mRowHeight * mNumRows + MONTH_HEADER_SIZE + ROW_SEPARATOR); } protected void onSizeChanged(int w, int h, int oldw, int oldh) { mWidth = w; } public boolean onTouchEvent(MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_UP) { SimpleMonthAdapter.CalendarDay calendarDay = getDayFromLocation(event.getX(), event.getY()); // boolean isValidDay = false; if (calendarDay == null) { return true; } for (SimpleMonthAdapter.CalendarDay day : mInvalidDays) { // 选择了入住日期,这时候比入住日期大且离入住日期最近的不可用日期变为可选 if (calendarDay.equals(day) && !(mEndDate == null && mNearestDay != null && calendarDay.equals(mNearestDay))) { return true; } } for (SimpleMonthAdapter.CalendarDay day : mBusyDays) { // 选择了入住日期,这时候比入住日期大且离入住日期最近的不可用日期变为可选 if (calendarDay.equals(day) && !(mEndDate == null && mNearestDay != null && calendarDay.equals(mNearestDay))) { return true; } } onDayClick(calendarDay); } return true; } // public void reuse() { // mNumRows = DEFAULT_NUM_ROWS; // requestLayout(); // } /** * 设置传递进来的参数 * * @param params */ public void setMonthParams(HashMap<String, Object> params) { if (!params.containsKey(VIEW_PARAMS_MONTH) && !params.containsKey(VIEW_PARAMS_YEAR)) { throw new InvalidParameterException("You must specify month and year for this view"); } setTag(params); // if (params.containsKey(VIEW_PARAMS_HEIGHT)) { // mRowHeight = (int) params.get(VIEW_PARAMS_HEIGHT); // if (mRowHeight < MIN_HEIGHT) { // mRowHeight = MIN_HEIGHT; // } // } if (params.containsKey(VIEW_PARAMS_SELECTED_BEGIN_DATE)) { mStartDate = (SimpleMonthAdapter.CalendarDay) params.get(VIEW_PARAMS_SELECTED_BEGIN_DATE); } if (params.containsKey(VIEW_PARAMS_SELECTED_LAST_DATE)) { mEndDate = (SimpleMonthAdapter.CalendarDay) params.get(VIEW_PARAMS_SELECTED_LAST_DATE); } if (params.containsKey("mNearestDay")) { mNearestDay = (SimpleMonthAdapter.CalendarDay) params.get("mNearestDay"); } mMonth = (int) params.get(VIEW_PARAMS_MONTH); mYear = (int) params.get(VIEW_PARAMS_YEAR); mHasToday = false; mToday = -1; mCalendar.set(Calendar.MONTH, mMonth); mCalendar.set(Calendar.YEAR, mYear); mCalendar.set(Calendar.DAY_OF_MONTH, 1); mDayOfWeekStart = mCalendar.get(Calendar.DAY_OF_WEEK); if (params.containsKey(VIEW_PARAMS_WEEK_START)) { mWeekStart = (int) params.get(VIEW_PARAMS_WEEK_START); } else { mWeekStart = mCalendar.getFirstDayOfWeek(); } mNumCells = CalendarUtils.getDaysInMonth(mMonth, mYear); for (int i = 0; i < mNumCells; i++) { final int day = i + 1; if (sameDay(day, today)) { mHasToday = true; mToday = day; } } mNumRows = calculateNumRows(); } public void setOnDayClickListener(OnDayClickListener onDayClickListener) { mOnDayClickListener = onDayClickListener; } public interface OnDayClickListener { void onDayClick(SimpleMonthView simpleMonthView, SimpleMonthAdapter.CalendarDay calendarDay); } /** * 绘制cell * * @param canvas * @param x * @param y */ private void drawDayBg(Canvas canvas, int x, int y, Paint paint) { RectF rectF = new RectF(x - DAY_SELECTED_RECT_SIZE, y - DAY_SELECTED_RECT_SIZE, x + DAY_SELECTED_RECT_SIZE, y + DAY_SELECTED_RECT_SIZE); canvas.drawRoundRect(rectF, 10.0f, 10.0f, paint); } /** * 在使用drawText方法时文字不能根据y坐标居中,所以重新计算y坐标 * @param paint * @param y * @return */ private float getTextYCenter(Paint paint, int y) { Paint.FontMetrics fontMetrics = paint.getFontMetrics(); float fontTotalHeight = fontMetrics.bottom - fontMetrics.top; float offY = fontTotalHeight / 2 - fontMetrics.bottom; return y + offY; } }
library/src/main/java/com/henry/calendarview/SimpleMonthView.java
package com.henry.calendarview; import android.content.Context; import android.content.res.Resources; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Paint.Align; import android.graphics.Paint.Style; import android.graphics.RectF; import android.graphics.Typeface; import android.text.format.DateUtils; import android.text.format.Time; import android.view.MotionEvent; import android.view.View; import java.security.InvalidParameterException; import java.text.DateFormatSymbols; import java.util.Calendar; import java.util.HashMap; import java.util.List; import java.util.Locale; /** * 每个月作为一个ItemView */ class SimpleMonthView extends View { public static final String VIEW_PARAMS_SELECTED_BEGIN_DATE = "selected_begin_date"; public static final String VIEW_PARAMS_SELECTED_LAST_DATE = "selected_last_date"; public static final String VIEW_PARAMS_NEAREST_DATE = "mNearestDay"; // public static final String VIEW_PARAMS_HEIGHT = "height"; public static final String VIEW_PARAMS_MONTH = "month"; public static final String VIEW_PARAMS_YEAR = "year"; public static final String VIEW_PARAMS_WEEK_START = "week_start"; private static final int SELECTED_CIRCLE_ALPHA = 128; protected static int DEFAULT_HEIGHT = 32; // 默认一行的高度 protected static final int DEFAULT_NUM_ROWS = 6; protected static int DAY_SELECTED_RECT_SIZE; // 选中圆角矩形半径 protected static int ROW_SEPARATOR = 12; // 每行中间的间距 protected static int MINI_DAY_NUMBER_TEXT_SIZE; // 日期字体的最小尺寸 private static int TAG_TEXT_SIZE; // 标签字体大小 protected static int MIN_HEIGHT = 10; // 最小高度 // protected static int MONTH_DAY_LABEL_TEXT_SIZE; // 头部的星期几的字体大小 protected static int MONTH_HEADER_SIZE; // 头部的高度(包括年份月份,星期几) protected static int YEAR_MONTH_TEXT_SIZE; // 头部年份月份的字体大小 protected static int WEEK_TEXT_SIZE; // 头部年份月份的字体大小 // private final int mSelectType; // 类型 // private boolean mIsDisplayTag; // 是否显示标签 private List<SimpleMonthAdapter.CalendarDay> mInvalidDays; // 禁用的日期 private List<SimpleMonthAdapter.CalendarDay> mBusyDays; // 被占用的日期 private SimpleMonthAdapter.CalendarDay mNearestDay; // 比离入住日期大且是最近的已被占用或者无效日期 private List<SimpleMonthAdapter.CalendarDay> mCalendarTags; // 日期下面的标签 private String mDefTag = "标签"; protected int mPadding = 0; private String mDayOfWeekTypeface; private String mMonthTitleTypeface; protected Paint mWeekTextPaint; // 头部星期几的字体画笔 protected Paint mDayTextPaint; protected Paint mTagTextPaint; // 日期底部的文字画笔 // protected Paint mTitleBGPaint; protected Paint mYearMonthPaint; // 头部的画笔 protected Paint mSelectedDayBgPaint; protected Paint mBusyDayBgPaint; protected Paint mInValidDayBgPaint; // protected Paint mSelectedDayTextPaint; protected int mCurrentDayTextColor; // 今天的字体颜色 protected int mYearMonthTextColor; // 头部年份和月份字体颜色 protected int mWeekTextColor; // 头部星期几字体颜色 // protected int mDayTextColor; protected int mDayTextColor; // 日期字体颜色 protected int mSelectedDayTextColor; // 被选中的日期字体颜色 protected int mPreviousDayTextColor; // 过去的字体颜色 protected int mSelectedDaysBgColor; // 选中的日期背景颜色 protected int mBusyDaysBgColor; // 被占用的日期背景颜色 protected int mInValidDaysBgColor; // 禁用的日期背景颜色 protected int mBusyDaysTextColor; // 被占用的日期字体颜色 protected int mInValidDaysTextColor; // 禁用的日期字体颜色 private final StringBuilder mStringBuilder; protected boolean mHasToday = false; protected int mToday = -1; protected int mWeekStart = 1; // 一周的第一天(不同国家的一星期的第一天不同) protected int mNumDays = 7; // 一行几列 protected int mNumCells; // 一个月有多少天 private int mDayOfWeekStart = 0; // 日期对应星期几 // protected Boolean mDrawRect; // 圆角还是圆形 protected int mRowHeight = DEFAULT_HEIGHT; // 行高 protected int mWidth; // simpleMonthView的宽度 protected int mYear; protected int mMonth; final Time today; private final Calendar mCalendar; private final Calendar mDayLabelCalendar; // 用于显示星期几 private final Boolean isPrevDayEnabled; // 今天以前的日期是否能被操作 private int mNumRows; private DateFormatSymbols mDateFormatSymbols = new DateFormatSymbols(); private OnDayClickListener mOnDayClickListener; SimpleMonthAdapter.CalendarDay mStartDate; // 入住日期 SimpleMonthAdapter.CalendarDay mEndDate; // 退房日期 SimpleMonthAdapter.CalendarDay cellCalendar; // cell的对应的日期 /** * @param context * @param typedArray * @param dataModel */ public SimpleMonthView(Context context, TypedArray typedArray, DayPickerView.DataModel dataModel) { super(context); Resources resources = context.getResources(); mDayLabelCalendar = Calendar.getInstance(); mCalendar = Calendar.getInstance(); today = new Time(Time.getCurrentTimezone()); today.setToNow(); mDayOfWeekTypeface = resources.getString(R.string.sans_serif); mMonthTitleTypeface = resources.getString(R.string.sans_serif); mCurrentDayTextColor = typedArray.getColor(R.styleable.DayPickerView_colorCurrentDay, resources.getColor(R.color.normal_day)); mYearMonthTextColor = typedArray.getColor(R.styleable.DayPickerView_colorYearMonthText, resources.getColor(R.color.normal_day)); mWeekTextColor = typedArray.getColor(R.styleable.DayPickerView_colorWeekText, resources.getColor(R.color.normal_day)); // mDayTextColor = typedArray.getColor(R.styleable.DayPickerView_colorDayName, resources.getColor(R.color.normal_day)); mDayTextColor = typedArray.getColor(R.styleable.DayPickerView_colorNormalDayText, resources.getColor(R.color.normal_day)); mPreviousDayTextColor = typedArray.getColor(R.styleable.DayPickerView_colorPreviousDayText, resources.getColor(R.color.normal_day)); mSelectedDaysBgColor = typedArray.getColor(R.styleable.DayPickerView_colorSelectedDayBackground, resources.getColor(R.color.selected_day_background)); mSelectedDayTextColor = typedArray.getColor(R.styleable.DayPickerView_colorSelectedDayText, resources.getColor(R.color.selected_day_text)); mBusyDaysBgColor = typedArray.getColor(R.styleable.DayPickerView_colorBusyDaysBg, Color.GRAY); mInValidDaysBgColor = typedArray.getColor(R.styleable.DayPickerView_colorInValidDaysBg, Color.GRAY); mBusyDaysTextColor = typedArray.getColor(R.styleable.DayPickerView_colorBusyDaysText, resources.getColor(R.color.normal_day)); mInValidDaysTextColor = typedArray.getColor(R.styleable.DayPickerView_colorInValidDaysText, resources.getColor(R.color.normal_day)); // mDrawRect = typedArray.getBoolean(R.styleable.DayPickerView_drawRoundRect, true); mStringBuilder = new StringBuilder(50); MINI_DAY_NUMBER_TEXT_SIZE = typedArray.getDimensionPixelSize(R.styleable.DayPickerView_textSizeDay, resources.getDimensionPixelSize(R.dimen.text_size_day)); TAG_TEXT_SIZE = typedArray.getDimensionPixelSize(R.styleable.DayPickerView_textSizeTag, resources.getDimensionPixelSize(R.dimen.text_size_tag)); YEAR_MONTH_TEXT_SIZE = typedArray.getDimensionPixelSize(R.styleable.DayPickerView_textSizeYearMonth, resources.getDimensionPixelSize(R.dimen.text_size_month)); WEEK_TEXT_SIZE = typedArray.getDimensionPixelSize(R.styleable.DayPickerView_textSizeWeek, resources.getDimensionPixelSize(R.dimen.text_size_day_name)); MONTH_HEADER_SIZE = typedArray.getDimensionPixelOffset(R.styleable.DayPickerView_headerMonthHeight, resources.getDimensionPixelOffset(R.dimen.header_month_height)); DAY_SELECTED_RECT_SIZE = typedArray.getDimensionPixelSize(R.styleable.DayPickerView_selectedDayRadius, resources.getDimensionPixelOffset(R.dimen.selected_day_radius)); mRowHeight = ((typedArray.getDimensionPixelSize(R.styleable.DayPickerView_calendarHeight, resources.getDimensionPixelOffset(R.dimen.calendar_height)) - MONTH_HEADER_SIZE - ROW_SEPARATOR) / 6); isPrevDayEnabled = typedArray.getBoolean(R.styleable.DayPickerView_enablePreviousDay, false); mInvalidDays = dataModel.invalidDays; mBusyDays = dataModel.busyDays; mCalendarTags = dataModel.tags; mDefTag = dataModel.defTag; cellCalendar = new SimpleMonthAdapter.CalendarDay(); initView(); } /** * 计算每个月的日期占用的行数 * * @return */ private int calculateNumRows() { int offset = findDayOffset(); int dividend = (offset + mNumCells) / mNumDays; int remainder = (offset + mNumCells) % mNumDays; return (dividend + (remainder > 0 ? 1 : 0)); } /** * 绘制头部的一行星期几 * * @param canvas */ private void drawMonthDayLabels(Canvas canvas) { int y = MONTH_HEADER_SIZE - (WEEK_TEXT_SIZE / 2); // 一个cell的二分之宽度 int dayWidthHalf = (mWidth - mPadding * 2) / (mNumDays * 2); for (int i = 0; i < mNumDays; i++) { int calendarDay = (i + mWeekStart) % mNumDays; int x = (2 * i + 1) * dayWidthHalf + mPadding; mDayLabelCalendar.set(Calendar.DAY_OF_WEEK, calendarDay); canvas.drawText(mDateFormatSymbols.getShortWeekdays()[mDayLabelCalendar.get(Calendar.DAY_OF_WEEK)].toUpperCase(Locale.getDefault()), x, y, mWeekTextPaint); } } /** * 绘制头部(年份月份,星期几) * * @param canvas */ private void drawMonthTitle(Canvas canvas) { int x = (mWidth + 2 * mPadding) / 2; int y = (MONTH_HEADER_SIZE - WEEK_TEXT_SIZE) / 2 + (YEAR_MONTH_TEXT_SIZE / 3); StringBuilder stringBuilder = new StringBuilder(getMonthAndYearString().toLowerCase()); stringBuilder.setCharAt(0, Character.toUpperCase(stringBuilder.charAt(0))); canvas.drawText(stringBuilder.toString(), x, y, mYearMonthPaint); } /** * 每个月第一天是星期几 * * @return */ private int findDayOffset() { return (mDayOfWeekStart < mWeekStart ? (mDayOfWeekStart + mNumDays) : mDayOfWeekStart) - mWeekStart; } /** * 获取年份和月份 * * @return */ private String getMonthAndYearString() { int flags = DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_YEAR | DateUtils.FORMAT_NO_MONTH_DAY; mStringBuilder.setLength(0); long millis = mCalendar.getTimeInMillis(); return DateUtils.formatDateRange(getContext(), millis, millis, flags); } private void onDayClick(SimpleMonthAdapter.CalendarDay calendarDay) { if (mOnDayClickListener != null && (isPrevDayEnabled || !prevDay(calendarDay.day, today))) { mOnDayClickListener.onDayClick(this, calendarDay); } } private boolean sameDay(int monthDay, Time time) { return (mYear == time.year) && (mMonth == time.month) && (monthDay == time.monthDay); } /** * 判断是否是已经过去的日期 * * @param monthDay * @param time * @return */ private boolean prevDay(int monthDay, Time time) { return ((mYear < time.year)) || (mYear == time.year && mMonth < time.month) || (mYear == time.year && mMonth == time.month && monthDay < time.monthDay); } /** * 绘制所有的cell * * @param canvas */ protected void drawMonthCell(Canvas canvas) { // ? int y = MONTH_HEADER_SIZE + ROW_SEPARATOR + mRowHeight / 2; int paddingDay = (mWidth - 2 * mPadding) / (2 * mNumDays); int dayOffset = findDayOffset(); int day = 1; while (day <= mNumCells) { int x = paddingDay * (1 + dayOffset * 2) + mPadding; mDayTextPaint.setColor(mDayTextColor); mDayTextPaint.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL)); mTagTextPaint.setColor(mDayTextColor); cellCalendar.setDay(mYear, mMonth, day); // 当天 boolean isToady = false; if (mHasToday && (mToday == day)) { isToady = true; canvas.drawText("今天", x, getTextYCenter(mDayTextPaint, y - DAY_SELECTED_RECT_SIZE / 2), mDayTextPaint); } // 已过去的日期 boolean isPrevDay = false; if (!isPrevDayEnabled && prevDay(day, today)) { isPrevDay = true; mDayTextPaint.setColor(mPreviousDayTextColor); mDayTextPaint.setTypeface(Typeface.defaultFromStyle(Typeface.ITALIC)); canvas.drawText(String.format("%d", day), x, y, mDayTextPaint); } boolean isBeginDay = false; // 绘制起始日期的方格 if (mStartDate != null && cellCalendar.equals(mStartDate) && !mStartDate.equals(mEndDate)) { isBeginDay = true; drawDayBg(canvas, x, y, mSelectedDayBgPaint); mDayTextPaint.setColor(mSelectedDayTextColor); canvas.drawText("入住", x, getTextYCenter(mDayTextPaint, y + DAY_SELECTED_RECT_SIZE / 2), mDayTextPaint); } boolean isLastDay = false; // 绘制结束日期的方格 if (mEndDate != null && cellCalendar.equals(mEndDate) && !mStartDate.equals(mEndDate)) { isLastDay = true; drawDayBg(canvas, x, y, mSelectedDayBgPaint); mDayTextPaint.setColor(mSelectedDayTextColor); canvas.drawText("退房", x, getTextYCenter(mDayTextPaint, y + DAY_SELECTED_RECT_SIZE / 2), mDayTextPaint); } // 在入住和退房之间的日期 if (cellCalendar.after(mStartDate) && cellCalendar.before(mEndDate)) { mDayTextPaint.setColor(mSelectedDayTextColor); drawDayBg(canvas, x, y, mSelectedDayBgPaint); // 标签变为白色 mTagTextPaint.setColor(Color.WHITE); // canvas.drawText(String.format("%d", day), x, y - DAY_SELECTED_RECT_SIZE / 2, mDayTextPaint); } // 被占用的日期 boolean isBusyDay = false; for (SimpleMonthAdapter.CalendarDay calendarDay : mBusyDays) { if (cellCalendar.equals(calendarDay) && !isPrevDay) { isBusyDay = true; // RectF rectF = new RectF(x - DAY_SELECTED_RECT_SIZE, // (y - MINI_DAY_NUMBER_TEXT_SIZE / 3) - DAY_SELECTED_RECT_SIZE, // x + DAY_SELECTED_RECT_SIZE, (y - MINI_DAY_NUMBER_TEXT_SIZE / 3) + DAY_SELECTED_RECT_SIZE); // 选择了入住和退房日期,退房日期等于mNearestDay的情况 if (mStartDate != null && mEndDate != null && mNearestDay != null && mEndDate.equals(mNearestDay) && mEndDate.equals(calendarDay)) { } else { // 选择了入住日期,没有选择退房日期,mNearestDay变为可选且不变灰色 if (mStartDate != null && mEndDate == null && mNearestDay != null && cellCalendar.equals(mNearestDay)) { mDayTextPaint.setColor(mDayTextColor); } else { drawDayBg(canvas, x, y, mBusyDayBgPaint); // canvas.drawRoundRect(rectF, 10.0f, 10.0f, mBusyDayBgPaint); mDayTextPaint.setColor(mBusyDaysTextColor); } canvas.drawText(String.format("%d", day), x, getTextYCenter(mTagTextPaint, y - DAY_SELECTED_RECT_SIZE / 2), mDayTextPaint); canvas.drawText("已租", x, getTextYCenter(mBusyDayBgPaint, y + DAY_SELECTED_RECT_SIZE / 2), mDayTextPaint); } } } // 禁用的日期 boolean isInvalidDays = false; for (SimpleMonthAdapter.CalendarDay calendarDay : mInvalidDays) { if (cellCalendar.equals(calendarDay) && !isPrevDay) { isBusyDay = true; // RectF rectF = new RectF(x - DAY_SELECTED_RECT_SIZE, // (y - MINI_DAY_NUMBER_TEXT_SIZE / 3) - DAY_SELECTED_RECT_SIZE, // x + DAY_SELECTED_RECT_SIZE, (y - MINI_DAY_NUMBER_TEXT_SIZE / 3) + DAY_SELECTED_RECT_SIZE); // 选择了入住和退房日期,退房日期等于mNearestDay的情况 if (mStartDate != null && mEndDate != null && mNearestDay != null && mEndDate.equals(mNearestDay) && mEndDate.equals(calendarDay)) { } else { // 选择了入住日期,没有选择退房日期,mNearestDay变为可选且不变灰色 if (mStartDate != null && mEndDate == null && mNearestDay != null && cellCalendar.equals(mNearestDay)) { mDayTextPaint.setColor(mDayTextColor); } else { drawDayBg(canvas, x, y, mInValidDayBgPaint); // canvas.drawRoundRect(rectF, 10.0f, 10.0f, mBusyDayBgPaint); mDayTextPaint.setColor(mInValidDaysTextColor); } canvas.drawText(String.format("%d", day), x, getTextYCenter(mTagTextPaint, y - DAY_SELECTED_RECT_SIZE / 2), mDayTextPaint); canvas.drawText("禁用", x, getTextYCenter(mInValidDayBgPaint, y + DAY_SELECTED_RECT_SIZE / 2), mDayTextPaint); } } } // 把入住日期之前和不可用日期之后的日期全部灰掉(思路: // 1:入住日期和退房日期不能同一天 // 2:只选择了入住日期且没有选择退房日期 // 3:比入住日期小全部变灰且不可点击 // 4:比入住日期大且离入住日期最近的被禁用或者被占用的日期 if (mStartDate != null && mEndDate == null && !mStartDate.equals(mEndDate) && !isInvalidDays && !isBusyDay) { if (cellCalendar.before(mStartDate) || (mNearestDay != null && cellCalendar.after(mNearestDay))) { // RectF rectF = new RectF(x - DAY_SELECTED_RECT_SIZE, (y - MINI_DAY_NUMBER_TEXT_SIZE / 3) - DAY_SELECTED_RECT_SIZE, // x + DAY_SELECTED_RECT_SIZE, (y - MINI_DAY_NUMBER_TEXT_SIZE / 3) + DAY_SELECTED_RECT_SIZE); // canvas.drawRoundRect(rectF, 10.0f, 10.0f, mBusyDayBgPaint); drawDayBg(canvas, x, y, mBusyDayBgPaint); } } // 绘制标签 if (!isPrevDay && !isInvalidDays && !isBusyDay && !isBeginDay && !isLastDay) { boolean isCalendarTag = false; for (SimpleMonthAdapter.CalendarDay calendarDay : mCalendarTags) { if (cellCalendar.equals(calendarDay)) { isCalendarTag = true; canvas.drawText(calendarDay.tag, x, getTextYCenter(mTagTextPaint, y + DAY_SELECTED_RECT_SIZE / 2), mTagTextPaint); } } if (!isCalendarTag) { canvas.drawText(mDefTag, x, getTextYCenter(mTagTextPaint, y + DAY_SELECTED_RECT_SIZE / 2), mTagTextPaint); } } // 绘制日期 if (!isToady && !isPrevDay && !isInvalidDays && !isBusyDay) { canvas.drawText(String.format("%d", day), x, getTextYCenter(mTagTextPaint, y - DAY_SELECTED_RECT_SIZE / 2), mDayTextPaint); } dayOffset++; if (dayOffset == mNumDays) { dayOffset = 0; y += mRowHeight; } day++; } } /** * 根据坐标获取对应的日期 * @param x * @param y * @return */ public SimpleMonthAdapter.CalendarDay getDayFromLocation(float x, float y) { int padding = mPadding; if ((x < padding) || (x > mWidth - mPadding)) { return null; } int yDay = (int) (y - MONTH_HEADER_SIZE) / mRowHeight; int day = 1 + ((int) ((x - padding) * mNumDays / (mWidth - padding - mPadding)) - findDayOffset()) + yDay * mNumDays; if (mMonth > 11 || mMonth < 0 || CalendarUtils.getDaysInMonth(mMonth, mYear) < day || day < 1) return null; SimpleMonthAdapter.CalendarDay calendar = new SimpleMonthAdapter.CalendarDay(mYear, mMonth, day); // 获取日期下面的tag boolean flag = false; for (SimpleMonthAdapter.CalendarDay calendarTag : mCalendarTags) { if (calendarTag.compareTo(calendar) == 0) { flag = true; calendar = calendarTag; } } if (!flag) { calendar.tag = mDefTag; } return calendar; } /** * 初始化一些paint */ protected void initView() { // 头部年份和月份的字体paint mYearMonthPaint = new Paint(); mYearMonthPaint.setFakeBoldText(true); mYearMonthPaint.setAntiAlias(true); mYearMonthPaint.setTextSize(YEAR_MONTH_TEXT_SIZE); mYearMonthPaint.setTypeface(Typeface.create(mMonthTitleTypeface, Typeface.BOLD)); mYearMonthPaint.setColor(mYearMonthTextColor); mYearMonthPaint.setTextAlign(Align.CENTER); mYearMonthPaint.setStyle(Style.FILL); // 头部星期几字体paint mWeekTextPaint = new Paint(); mWeekTextPaint.setAntiAlias(true); mWeekTextPaint.setTextSize(WEEK_TEXT_SIZE); mWeekTextPaint.setColor(mWeekTextColor); mWeekTextPaint.setTypeface(Typeface.create(mDayOfWeekTypeface, Typeface.NORMAL)); mWeekTextPaint.setStyle(Style.FILL); mWeekTextPaint.setTextAlign(Align.CENTER); mWeekTextPaint.setFakeBoldText(true); // // 头部背景paint // mTitleBGPaint = new Paint(); // mTitleBGPaint.setFakeBoldText(true); // mTitleBGPaint.setAntiAlias(true); // mTitleBGPaint.setColor(mSelectedDayTextColor); // mTitleBGPaint.setTextAlign(Align.CENTER); // mTitleBGPaint.setStyle(Style.FILL); // 被选中的日期背景paint mSelectedDayBgPaint = new Paint(); mSelectedDayBgPaint.setFakeBoldText(true); mSelectedDayBgPaint.setAntiAlias(true); mSelectedDayBgPaint.setColor(mSelectedDaysBgColor); mSelectedDayBgPaint.setTextAlign(Align.CENTER); mSelectedDayBgPaint.setStyle(Style.FILL); mSelectedDayBgPaint.setAlpha(SELECTED_CIRCLE_ALPHA); // 被占用的日期paint mBusyDayBgPaint = new Paint(); mBusyDayBgPaint.setFakeBoldText(true); mBusyDayBgPaint.setAntiAlias(true); mBusyDayBgPaint.setColor(mBusyDaysBgColor); mBusyDayBgPaint.setTextSize(TAG_TEXT_SIZE); mBusyDayBgPaint.setTextAlign(Align.CENTER); mBusyDayBgPaint.setStyle(Style.FILL); mBusyDayBgPaint.setAlpha(SELECTED_CIRCLE_ALPHA); // 禁用的日期paint mInValidDayBgPaint = new Paint(); mInValidDayBgPaint.setFakeBoldText(true); mInValidDayBgPaint.setAntiAlias(true); mInValidDayBgPaint.setColor(mInValidDaysBgColor); mInValidDayBgPaint.setTextSize(TAG_TEXT_SIZE); mInValidDayBgPaint.setTextAlign(Align.CENTER); mInValidDayBgPaint.setStyle(Style.FILL); mInValidDayBgPaint.setAlpha(SELECTED_CIRCLE_ALPHA); // // 被选中的日期字体paint // mSelectedDayTextPaint = new Paint(); // mSelectedDayTextPaint.setAntiAlias(true); // mSelectedDayTextPaint.setTextSize(MONTH_DAY_LABEL_TEXT_SIZE); // mSelectedDayTextPaint.setColor(Color.WHITE); // mSelectedDayTextPaint.setTypeface(Typeface.create(mDayOfWeekTypeface, Typeface.NORMAL)); // mSelectedDayTextPaint.setStyle(Style.FILL); // mSelectedDayTextPaint.setTextAlign(Align.CENTER); // mSelectedDayTextPaint.setFakeBoldText(true); // 日期字体paint mDayTextPaint = new Paint(); mDayTextPaint.setAntiAlias(true); mDayTextPaint.setColor(mDayTextColor); mDayTextPaint.setTextSize(MINI_DAY_NUMBER_TEXT_SIZE); mDayTextPaint.setStyle(Style.FILL); mDayTextPaint.setTextAlign(Align.CENTER); mDayTextPaint.setFakeBoldText(false); // 标签字体paint mTagTextPaint = new Paint(); mTagTextPaint.setAntiAlias(true); mTagTextPaint.setColor(mDayTextColor); mTagTextPaint.setTextSize(TAG_TEXT_SIZE); mTagTextPaint.setStyle(Style.FILL); mTagTextPaint.setTextAlign(Align.CENTER); mTagTextPaint.setFakeBoldText(false); } @Override protected void onDraw(Canvas canvas) { drawMonthTitle(canvas); drawMonthDayLabels(canvas); drawMonthCell(canvas); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { // 设置simpleMonthView的宽度和高度 setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec), mRowHeight * mNumRows + MONTH_HEADER_SIZE + ROW_SEPARATOR); } protected void onSizeChanged(int w, int h, int oldw, int oldh) { mWidth = w; } public boolean onTouchEvent(MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_UP) { SimpleMonthAdapter.CalendarDay calendarDay = getDayFromLocation(event.getX(), event.getY()); // boolean isValidDay = false; if (calendarDay == null) { return true; } for (SimpleMonthAdapter.CalendarDay day : mInvalidDays) { // 选择了入住日期,这时候比入住日期大且离入住日期最近的不可用日期变为可选 if (calendarDay.equals(day) && !(mEndDate == null && mNearestDay != null && calendarDay.equals(mNearestDay))) { return true; } } for (SimpleMonthAdapter.CalendarDay day : mBusyDays) { // 选择了入住日期,这时候比入住日期大且离入住日期最近的不可用日期变为可选 if (calendarDay.equals(day) && !(mEndDate == null && mNearestDay != null && calendarDay.equals(mNearestDay))) { return true; } } onDayClick(calendarDay); } return true; } // public void reuse() { // mNumRows = DEFAULT_NUM_ROWS; // requestLayout(); // } /** * 设置传递进来的参数 * * @param params */ public void setMonthParams(HashMap<String, Object> params) { if (!params.containsKey(VIEW_PARAMS_MONTH) && !params.containsKey(VIEW_PARAMS_YEAR)) { throw new InvalidParameterException("You must specify month and year for this view"); } setTag(params); // if (params.containsKey(VIEW_PARAMS_HEIGHT)) { // mRowHeight = (int) params.get(VIEW_PARAMS_HEIGHT); // if (mRowHeight < MIN_HEIGHT) { // mRowHeight = MIN_HEIGHT; // } // } if (params.containsKey(VIEW_PARAMS_SELECTED_BEGIN_DATE)) { mStartDate = (SimpleMonthAdapter.CalendarDay) params.get(VIEW_PARAMS_SELECTED_BEGIN_DATE); } if (params.containsKey(VIEW_PARAMS_SELECTED_LAST_DATE)) { mEndDate = (SimpleMonthAdapter.CalendarDay) params.get(VIEW_PARAMS_SELECTED_LAST_DATE); } if (params.containsKey("mNearestDay")) { mNearestDay = (SimpleMonthAdapter.CalendarDay) params.get("mNearestDay"); } mMonth = (int) params.get(VIEW_PARAMS_MONTH); mYear = (int) params.get(VIEW_PARAMS_YEAR); mHasToday = false; mToday = -1; mCalendar.set(Calendar.MONTH, mMonth); mCalendar.set(Calendar.YEAR, mYear); mCalendar.set(Calendar.DAY_OF_MONTH, 1); mDayOfWeekStart = mCalendar.get(Calendar.DAY_OF_WEEK); if (params.containsKey(VIEW_PARAMS_WEEK_START)) { mWeekStart = (int) params.get(VIEW_PARAMS_WEEK_START); } else { mWeekStart = mCalendar.getFirstDayOfWeek(); } mNumCells = CalendarUtils.getDaysInMonth(mMonth, mYear); for (int i = 0; i < mNumCells; i++) { final int day = i + 1; if (sameDay(day, today)) { mHasToday = true; mToday = day; } } mNumRows = calculateNumRows(); } public void setOnDayClickListener(OnDayClickListener onDayClickListener) { mOnDayClickListener = onDayClickListener; } public interface OnDayClickListener { void onDayClick(SimpleMonthView simpleMonthView, SimpleMonthAdapter.CalendarDay calendarDay); } /** * 绘制cell * * @param canvas * @param x * @param y */ private void drawDayBg(Canvas canvas, int x, int y, Paint paint) { RectF rectF = new RectF(x - DAY_SELECTED_RECT_SIZE, y - DAY_SELECTED_RECT_SIZE, x + DAY_SELECTED_RECT_SIZE, y + DAY_SELECTED_RECT_SIZE); canvas.drawRoundRect(rectF, 10.0f, 10.0f, paint); } /** * 在使用drawText方法时文字不能根据y坐标居中,所以重新计算y坐标 * @param paint * @param y * @return */ private float getTextYCenter(Paint paint, int y) { Paint.FontMetrics fontMetrics = paint.getFontMetrics(); float fontTotalHeight = fontMetrics.bottom - fontMetrics.top; float offY = fontTotalHeight / 2 - fontMetrics.bottom; return y + offY; } }
fix bug
library/src/main/java/com/henry/calendarview/SimpleMonthView.java
fix bug
Java
apache-2.0
e6a55250037e766d5f65fc2a1222d17996d2fbca
0
apache/rampart,apache/rampart
/* * Copyright 2004,2005 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. */ package org.apache.rahas; import org.apache.axiom.om.OMElement; import org.apache.axiom.om.impl.builder.StAXOMBuilder; import org.apache.axiom.om.impl.dom.factory.OMDOMFactory; import org.apache.axiom.om.util.Base64; import org.apache.axis2.addressing.AddressingConstants; import org.apache.axis2.context.MessageContext; import org.apache.ws.security.WSConstants; import org.apache.ws.security.WSSecurityEngineResult; import org.apache.ws.security.WSSecurityException; import org.apache.ws.security.handler.WSHandlerConstants; import org.apache.ws.security.handler.WSHandlerResult; import org.apache.ws.security.message.token.SecurityTokenReference; import org.opensaml.SAMLAssertion; import org.w3c.dom.Element; import javax.xml.namespace.QName; import java.security.Principal; import java.security.cert.X509Certificate; import java.util.Vector; /** * Common data items on WS-Trust request messages */ public class RahasData { private MessageContext inMessageContext; private OMElement rstElement; private int version = -1; private String wstNs; private String requestType; private String tokenType; private String tokenId; private int keysize = -1; private String computedKeyAlgo; private String keyType; private String appliesToAddress; private OMElement appliesToEpr; private Principal principal; private X509Certificate clientCert; private byte[] ephmeralKey; private byte[] requestEntropy; private byte[] responseEntropy; private String addressingNs; private String soapNs; private OMElement claimElem; private String claimDialect; private SAMLAssertion assertion; /** * Create a new RahasData instance and populate it with the information from * the request. * * @throws TrustException <code>RequestSecurityToken</code> element is invalid. */ public RahasData(MessageContext inMessageContext) throws TrustException { this.inMessageContext = inMessageContext; //Check for an authenticated Principal this.processWSS4JSecurityResults(); // Find out the incoming addressing version this.addressingNs = (String) this.inMessageContext .getProperty(AddressingConstants.WS_ADDRESSING_VERSION); this.rstElement = this.inMessageContext.getEnvelope().getBody() .getFirstElement(); this.soapNs = this.inMessageContext.getEnvelope().getNamespace() .getNamespaceURI(); this.wstNs = this.rstElement.getNamespace().getNamespaceURI(); int ver = TrustUtil.getWSTVersion(this.wstNs); if (ver == -1) { throw new TrustException(TrustException.INVALID_REQUEST); } else { this.version = ver; } this.processRequestType(); this.processTokenType(); this.processKeyType(); this.processKeySize(); this.processAppliesTo(); this.processEntropy(); this.processClaims(); this.processValidateTarget(); this.processRenewTarget(); } /** * Processes the authenticated user information from the WSS4J security * results. * * @throws TrustException */ private void processWSS4JSecurityResults() throws TrustException { /* * User can be identifier using a UsernameToken or a certificate - If a * certificate is found then we use that to - identify the user and - * encrypt the response (if required) - If a UsernameToken is found then * we will not be encrypting the response */ Vector results; if ((results = (Vector) this.inMessageContext .getProperty(WSHandlerConstants.RECV_RESULTS)) == null) { throw new TrustException(TrustException.REQUEST_FAILED); } else { for (int i = 0; i < results.size(); i++) { WSHandlerResult rResult = (WSHandlerResult) results.get(i); Vector wsSecEngineResults = rResult.getResults(); for (int j = 0; j < wsSecEngineResults.size(); j++) { WSSecurityEngineResult wser = (WSSecurityEngineResult) wsSecEngineResults .get(j); Object principalObject = wser.get(WSSecurityEngineResult.TAG_PRINCIPAL); int act = ((Integer)wser.get(WSSecurityEngineResult.TAG_ACTION)). intValue(); if (act == WSConstants.SIGN && principalObject != null) { this.clientCert = (X509Certificate) wser .get(WSSecurityEngineResult.TAG_X509_CERTIFICATE); this.principal = (Principal)principalObject; } else if (act == WSConstants.UT && principalObject != null) { this.principal = (Principal)principalObject; } else if (act == WSConstants.BST) { final X509Certificate[] certificates = (X509Certificate[]) wser .get(WSSecurityEngineResult.TAG_X509_CERTIFICATES); this.clientCert = certificates[0]; this.principal = this.clientCert.getSubjectDN(); } else if (act == WSConstants.ST_UNSIGNED) { this.assertion = (SAMLAssertion) wser .get(WSSecurityEngineResult.TAG_SAML_ASSERTION); } } } // If the principal or a SAML assertion is missing if (this.principal == null && this.assertion == null) { throw new TrustException(TrustException.REQUEST_FAILED); } } } private void processAppliesTo() throws TrustException { OMElement appliesToElem = this.rstElement .getFirstChildWithName(new QName(RahasConstants.WSP_NS, RahasConstants.IssuanceBindingLocalNames. APPLIES_TO)); if (appliesToElem != null) { OMElement eprElem = appliesToElem.getFirstElement(); this.appliesToEpr = eprElem; // If there were no addressing headers // The find the addressing version using the EPR element if (this.addressingNs == null) { this.addressingNs = eprElem.getNamespace() .getNamespaceURI(); } if (eprElem != null) { //Of the epr is a web service then try to get the addr OMElement addrElem = eprElem .getFirstChildWithName(new QName( this.addressingNs, AddressingConstants.EPR_ADDRESS)); if (addrElem != null && addrElem.getText() != null && !"".equals(addrElem.getText().trim())) { this.appliesToAddress = addrElem.getText().trim(); } } else { throw new TrustException("invalidAppliesToElem"); } } } private void processRequestType() throws TrustException { OMElement reqTypeElem = this.rstElement .getFirstChildWithName(new QName(this.wstNs, RahasConstants.LocalNames.REQUEST_TYPE)); if (reqTypeElem == null || reqTypeElem.getText() == null || reqTypeElem.getText().trim().length() == 0) { throw new TrustException(TrustException.INVALID_REQUEST); } else { this.requestType = reqTypeElem.getText().trim(); } } private void processTokenType() { OMElement tokTypeElem = this.rstElement .getFirstChildWithName(new QName(this.wstNs, RahasConstants.LocalNames.TOKEN_TYPE)); if (tokTypeElem != null && tokTypeElem.getText() != null && !"".equals(tokTypeElem.getText().trim())) { this.tokenType = tokTypeElem.getText().trim(); } } /** * Find the value of the KeyType element of the RST */ private void processKeyType() { OMElement keyTypeElem = this.rstElement .getFirstChildWithName(new QName(this.wstNs, RahasConstants.IssuanceBindingLocalNames.KEY_TYPE)); if (keyTypeElem != null) { String text = keyTypeElem.getText(); if (text != null && !"".equals(text.trim())) { this.keyType = text.trim(); } } } /** * Finds the KeySize and creates an empty ephmeral key. * * @throws TrustException */ private void processKeySize() throws TrustException { OMElement keySizeElem = this.rstElement .getFirstChildWithName(new QName(this.wstNs, RahasConstants.IssuanceBindingLocalNames. KEY_SIZE)); if (keySizeElem != null) { String text = keySizeElem.getText(); if (text != null && !"".equals(text.trim())) { try { //Set key size this.keysize = Integer.parseInt(text.trim()); //Create an empty array to hold the key this.ephmeralKey = new byte[this.keysize/8]; } catch (NumberFormatException e) { throw new TrustException(TrustException.INVALID_REQUEST, new String[]{"invalid wst:Keysize value"}, e); } } } this.keysize = -1; } /** * Processes a claims. * */ private void processClaims() throws TrustException{ claimElem = this.rstElement .getFirstChildWithName(new QName(this.wstNs, RahasConstants.IssuanceBindingLocalNames.CLAIMS)); if(claimElem != null){ claimDialect = claimElem.getAttributeValue(new QName(this.wstNs, RahasConstants.ATTR_CLAIMS_DIALECT)); } } private void processValidateTarget()throws TrustException{ OMElement validateTargetElem = this.rstElement .getFirstChildWithName(new QName(this.wstNs, RahasConstants.LocalNames.VALIDATE_TARGET)); if (validateTargetElem != null) { OMElement strElem = validateTargetElem.getFirstChildWithName(new QName(WSConstants.WSSE_NS, "SecurityTokenReference")); Element elem = (Element)(new StAXOMBuilder(new OMDOMFactory(), strElem.getXMLStreamReader()).getDocumentElement()); try { SecurityTokenReference str = new SecurityTokenReference((Element)elem); if (str.containsReference()) { tokenId = str.getReference().getURI(); } else if(str.containsKeyIdentifier()){ tokenId = str.getKeyIdentifierValue(); } } catch (WSSecurityException e) { throw new TrustException("errorExtractingTokenId",e); } } } private void processRenewTarget()throws TrustException{ OMElement renewTargetElem = this.rstElement .getFirstChildWithName(new QName(this.wstNs, RahasConstants.LocalNames.RENEW_TARGET)); if (renewTargetElem != null) { OMElement strElem = renewTargetElem.getFirstChildWithName(new QName(WSConstants.WSSE_NS, "SecurityTokenReference")); Element elem = (Element)(new StAXOMBuilder(new OMDOMFactory(), strElem.getXMLStreamReader()).getDocumentElement()); try { SecurityTokenReference str = new SecurityTokenReference((Element)elem); if (str.containsReference()) { tokenId = str.getReference().getURI(); } else if(str.containsKeyIdentifier()){ tokenId = str.getKeyIdentifierValue(); } if(tokenId == null){ if(str.containsKeyIdentifier()){ tokenId = str.getKeyIdentifierValue(); } } } catch (WSSecurityException e) { throw new TrustException("errorExtractingTokenId",e); } } } /** * Process wst:Entropy element in the request. */ private void processEntropy() throws TrustException { OMElement entropyElem = this.rstElement .getFirstChildWithName(new QName(this.wstNs, RahasConstants.IssuanceBindingLocalNames.ENTROPY)); if (entropyElem != null) { OMElement binSecElem = entropyElem.getFirstElement(); if (binSecElem != null && binSecElem.getText() != null && !"".equals(binSecElem.getText())) { this.requestEntropy = Base64.decode(binSecElem.getText()); } else { throw new TrustException("malformedEntropyElement", new String[]{entropyElem.toString()}); } } } /** * @return Returns the appliesToAddress. */ public String getAppliesToAddress() { return appliesToAddress; } /** * @return Returns the clientCert. */ public X509Certificate getClientCert() { return clientCert; } /** * @return Returns the computedKeyAlgo. */ public String getComputedKeyAlgo() { return computedKeyAlgo; } /** * @return Returns the ephmeralKey. */ public byte[] getEphmeralKey() { return ephmeralKey; } /** * @return Returns the inMessageContext. */ public MessageContext getInMessageContext() { return inMessageContext; } /** * @return Returns the keysize. */ public int getKeysize() { return keysize; } /** * @return Returns the keyType. */ public String getKeyType() { return keyType; } /** * @return Returns the principal. */ public Principal getPrincipal() { return principal; } /** * @return Returns the requestEntropy. */ public byte[] getRequestEntropy() { return requestEntropy; } /** * @return Returns the requestType. */ public String getRequestType() { return requestType; } /** * @return Returns the responseEntropy. */ public byte[] getResponseEntropy() { return responseEntropy; } /** * @return Returns the rstElement. */ public OMElement getRstElement() { return rstElement; } /** * @return Returns the tokenType. */ public String getTokenType() { return tokenType; } /** * @return Returns the version. */ public int getVersion() { return version; } /** * @return Returns the addressingNs. */ public String getAddressingNs() { return addressingNs; } /** * @return Returns the wstNs. */ public String getWstNs() { return wstNs; } /** * @return Returns the soapNs. */ public String getSoapNs() { return soapNs; } /** * @return Returns the tokenId. */ public String getTokenId() { return tokenId; } /** * @param responseEntropy The responseEntropy to set. */ public void setResponseEntropy(byte[] responseEntropy) { this.responseEntropy = responseEntropy; } /** * @param ephmeralKey The ephmeralKey to set. */ public void setEphmeralKey(byte[] ephmeralKey) { this.ephmeralKey = ephmeralKey; } public String getClaimDialect() { return claimDialect; } public OMElement getClaimElem() { return claimElem; } public OMElement getAppliesToEpr() { return appliesToEpr; } }
modules/rampart-trust/src/main/java/org/apache/rahas/RahasData.java
/* * Copyright 2004,2005 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. */ package org.apache.rahas; import org.apache.axiom.om.OMElement; import org.apache.axiom.om.impl.builder.StAXOMBuilder; import org.apache.axiom.om.impl.dom.factory.OMDOMFactory; import org.apache.axiom.om.util.Base64; import org.apache.axis2.addressing.AddressingConstants; import org.apache.axis2.context.MessageContext; import org.apache.ws.security.WSConstants; import org.apache.ws.security.WSSecurityEngineResult; import org.apache.ws.security.WSSecurityException; import org.apache.ws.security.handler.WSHandlerConstants; import org.apache.ws.security.handler.WSHandlerResult; import org.apache.ws.security.message.token.SecurityTokenReference; import org.opensaml.SAMLAssertion; import org.w3c.dom.Element; import javax.xml.namespace.QName; import java.security.Principal; import java.security.cert.X509Certificate; import java.util.Vector; /** * Common data items on WS-Trust request messages */ public class RahasData { private MessageContext inMessageContext; private OMElement rstElement; private int version = -1; private String wstNs; private String requestType; private String tokenType; private String tokenId; private int keysize = -1; private String computedKeyAlgo; private String keyType; private String appliesToAddress; private OMElement appliesToEpr; private Principal principal; private X509Certificate clientCert; private byte[] ephmeralKey; private byte[] requestEntropy; private byte[] responseEntropy; private String addressingNs; private String soapNs; private OMElement claimElem; private String claimDialect; private SAMLAssertion assertion; /** * Create a new RahasData instance and populate it with the information from * the request. * * @throws TrustException <code>RequestSecurityToken</code> element is invalid. */ public RahasData(MessageContext inMessageContext) throws TrustException { this.inMessageContext = inMessageContext; //Check for an authenticated Principal this.processWSS4JSecurityResults(); // Find out the incoming addressing version this.addressingNs = (String) this.inMessageContext .getProperty(AddressingConstants.WS_ADDRESSING_VERSION); this.rstElement = this.inMessageContext.getEnvelope().getBody() .getFirstElement(); this.soapNs = this.inMessageContext.getEnvelope().getNamespace() .getNamespaceURI(); this.wstNs = this.rstElement.getNamespace().getNamespaceURI(); int ver = TrustUtil.getWSTVersion(this.wstNs); if (ver == -1) { throw new TrustException(TrustException.INVALID_REQUEST); } else { this.version = ver; } this.processRequestType(); this.processTokenType(); this.processKeyType(); this.processKeySize(); this.processAppliesTo(); this.processEntropy(); this.processClaims(); this.processValidateTarget(); this.processRenewTarget(); } /** * Processes the authenticated user information from the WSS4J security * results. * * @throws TrustException */ private void processWSS4JSecurityResults() throws TrustException { /* * User can be identifier using a UsernameToken or a certificate - If a * certificate is found then we use that to - identify the user and - * encrypt the response (if required) - If a UsernameToken is found then * we will not be encrypting the response */ Vector results; if ((results = (Vector) this.inMessageContext .getProperty(WSHandlerConstants.RECV_RESULTS)) == null) { throw new TrustException(TrustException.REQUEST_FAILED); } else { for (int i = 0; i < results.size(); i++) { WSHandlerResult rResult = (WSHandlerResult) results.get(i); Vector wsSecEngineResults = rResult.getResults(); for (int j = 0; j < wsSecEngineResults.size(); j++) { WSSecurityEngineResult wser = (WSSecurityEngineResult) wsSecEngineResults .get(j); Object principalObject = wser.get(WSSecurityEngineResult.TAG_PRINCIPAL); int act = ((Integer)wser.get(WSSecurityEngineResult.TAG_ACTION)). intValue(); if (act == WSConstants.SIGN && principalObject != null) { this.clientCert = (X509Certificate) wser .get(WSSecurityEngineResult.TAG_X509_CERTIFICATE); this.principal = (Principal)principalObject; } else if (act == WSConstants.UT && principalObject != null) { this.principal = (Principal)principalObject; } else if (act == WSConstants.BST) { final X509Certificate[] certificates = (X509Certificate[]) wser .get(WSSecurityEngineResult.TAG_X509_CERTIFICATES); this.clientCert = certificates[0]; this.principal = this.clientCert.getSubjectDN(); } else if (act == WSConstants.ST_UNSIGNED) { this.assertion = (SAMLAssertion) wser .get(WSSecurityEngineResult.TAG_SAML_ASSERTION); } } } // If the principal or a SAML assertion is missing if (this.principal == null && this.assertion == null) { throw new TrustException(TrustException.REQUEST_FAILED); } } } private void processAppliesTo() throws TrustException { OMElement appliesToElem = this.rstElement .getFirstChildWithName(new QName(RahasConstants.WSP_NS, RahasConstants.IssuanceBindingLocalNames. APPLIES_TO)); if (appliesToElem != null) { OMElement eprElem = appliesToElem.getFirstElement(); this.appliesToEpr = eprElem; // If there were no addressing headers // The find the addressing version using the EPR element if (this.addressingNs == null) { this.addressingNs = eprElem.getNamespace() .getNamespaceURI(); } if (eprElem != null) { //Of the epr is a web service then try to get the addr OMElement addrElem = eprElem .getFirstChildWithName(new QName( this.addressingNs, AddressingConstants.EPR_ADDRESS)); if (addrElem != null && addrElem.getText() != null && !"".equals(addrElem.getText().trim())) { this.appliesToAddress = addrElem.getText().trim(); } } else { throw new TrustException("invalidAppliesToElem"); } } } private void processRequestType() throws TrustException { OMElement reqTypeElem = this.rstElement .getFirstChildWithName(new QName(this.wstNs, RahasConstants.LocalNames.REQUEST_TYPE)); if (reqTypeElem == null || reqTypeElem.getText() == null || reqTypeElem.getText().trim().length() == 0) { throw new TrustException(TrustException.INVALID_REQUEST); } else { this.requestType = reqTypeElem.getText().trim(); } } private void processTokenType() { OMElement tokTypeElem = this.rstElement .getFirstChildWithName(new QName(this.wstNs, RahasConstants.LocalNames.TOKEN_TYPE)); if (tokTypeElem != null && tokTypeElem.getText() != null && !"".equals(tokTypeElem.getText().trim())) { this.tokenType = tokTypeElem.getText().trim(); } } /** * Find the value of the KeyType element of the RST */ private void processKeyType() { OMElement keyTypeElem = this.rstElement .getFirstChildWithName(new QName(this.wstNs, RahasConstants.IssuanceBindingLocalNames.KEY_TYPE)); if (keyTypeElem != null) { String text = keyTypeElem.getText(); if (text != null && !"".equals(text.trim())) { this.keyType = text.trim(); } } } /** * Finds the KeySize and creates an empty ephmeral key. * * @throws TrustException */ private void processKeySize() throws TrustException { OMElement keySizeElem = this.rstElement .getFirstChildWithName(new QName(this.wstNs, RahasConstants.IssuanceBindingLocalNames. KEY_SIZE)); if (keySizeElem != null) { String text = keySizeElem.getText(); if (text != null && !"".equals(text.trim())) { try { //Set key size this.keysize = Integer.parseInt(text.trim()); //Create an empty array to hold the key this.ephmeralKey = new byte[this.keysize/8]; } catch (NumberFormatException e) { throw new TrustException(TrustException.INVALID_REQUEST, new String[]{"invalid wst:Keysize value"}, e); } } } this.keysize = -1; } /** * Processes a claims. * */ private void processClaims() throws TrustException{ claimElem = this.rstElement .getFirstChildWithName(new QName(this.wstNs, RahasConstants.IssuanceBindingLocalNames.CLAIMS)); if(claimElem != null){ claimDialect = claimElem.getAttributeValue(new QName(this.wstNs, RahasConstants.ATTR_CLAIMS_DIALECT)); } } private void processValidateTarget()throws TrustException{ OMElement validateTargetElem = this.rstElement .getFirstChildWithName(new QName(this.wstNs, RahasConstants.LocalNames.VALIDATE_TARGET)); if (validateTargetElem != null) { OMElement strElem = validateTargetElem.getFirstChildWithName(new QName(WSConstants.WSSE_NS, "SecurityTokenReference")); Element elem = (Element)(new StAXOMBuilder(new OMDOMFactory(), strElem.getXMLStreamReader()).getDocumentElement()); try { SecurityTokenReference str = new SecurityTokenReference((Element)elem); if (str.containsReference()) { tokenId = str.getReference().getURI(); } } catch (WSSecurityException e) { throw new TrustException("errorExtractingTokenId",e); } } } private void processRenewTarget()throws TrustException{ OMElement renewTargetElem = this.rstElement .getFirstChildWithName(new QName(this.wstNs, RahasConstants.LocalNames.RENEW_TARGET)); if (renewTargetElem != null) { OMElement strElem = renewTargetElem.getFirstChildWithName(new QName(WSConstants.WSSE_NS, "SecurityTokenReference")); Element elem = (Element)(new StAXOMBuilder(new OMDOMFactory(), strElem.getXMLStreamReader()).getDocumentElement()); try { SecurityTokenReference str = new SecurityTokenReference((Element)elem); if (str.containsReference()) { tokenId = str.getReference().getURI(); } if(tokenId == null){ if(str.containsKeyIdentifier()){ tokenId = str.getKeyIdentifierValue(); } } } catch (WSSecurityException e) { throw new TrustException("errorExtractingTokenId",e); } } } /** * Process wst:Entropy element in the request. */ private void processEntropy() throws TrustException { OMElement entropyElem = this.rstElement .getFirstChildWithName(new QName(this.wstNs, RahasConstants.IssuanceBindingLocalNames.ENTROPY)); if (entropyElem != null) { OMElement binSecElem = entropyElem.getFirstElement(); if (binSecElem != null && binSecElem.getText() != null && !"".equals(binSecElem.getText())) { this.requestEntropy = Base64.decode(binSecElem.getText()); } else { throw new TrustException("malformedEntropyElement", new String[]{entropyElem.toString()}); } } } /** * @return Returns the appliesToAddress. */ public String getAppliesToAddress() { return appliesToAddress; } /** * @return Returns the clientCert. */ public X509Certificate getClientCert() { return clientCert; } /** * @return Returns the computedKeyAlgo. */ public String getComputedKeyAlgo() { return computedKeyAlgo; } /** * @return Returns the ephmeralKey. */ public byte[] getEphmeralKey() { return ephmeralKey; } /** * @return Returns the inMessageContext. */ public MessageContext getInMessageContext() { return inMessageContext; } /** * @return Returns the keysize. */ public int getKeysize() { return keysize; } /** * @return Returns the keyType. */ public String getKeyType() { return keyType; } /** * @return Returns the principal. */ public Principal getPrincipal() { return principal; } /** * @return Returns the requestEntropy. */ public byte[] getRequestEntropy() { return requestEntropy; } /** * @return Returns the requestType. */ public String getRequestType() { return requestType; } /** * @return Returns the responseEntropy. */ public byte[] getResponseEntropy() { return responseEntropy; } /** * @return Returns the rstElement. */ public OMElement getRstElement() { return rstElement; } /** * @return Returns the tokenType. */ public String getTokenType() { return tokenType; } /** * @return Returns the version. */ public int getVersion() { return version; } /** * @return Returns the addressingNs. */ public String getAddressingNs() { return addressingNs; } /** * @return Returns the wstNs. */ public String getWstNs() { return wstNs; } /** * @return Returns the soapNs. */ public String getSoapNs() { return soapNs; } /** * @return Returns the tokenId. */ public String getTokenId() { return tokenId; } /** * @param responseEntropy The responseEntropy to set. */ public void setResponseEntropy(byte[] responseEntropy) { this.responseEntropy = responseEntropy; } /** * @param ephmeralKey The ephmeralKey to set. */ public void setEphmeralKey(byte[] ephmeralKey) { this.ephmeralKey = ephmeralKey; } public String getClaimDialect() { return claimDialect; } public OMElement getClaimElem() { return claimElem; } public OMElement getAppliesToEpr() { return appliesToEpr; } }
Fixed the problem of renewing a STS token not working - RAMPART-274 git-svn-id: 3a0daac14c5e6bfdff62a55945ca5e1dd585acf7@1051532 13f79535-47bb-0310-9956-ffa450edef68
modules/rampart-trust/src/main/java/org/apache/rahas/RahasData.java
Fixed the problem of renewing a STS token not working - RAMPART-274
Java
bsd-2-clause
59f4df1d2d39e1dee5278626bd2efb16d4a56847
0
mwilliamson/java-mammoth
package org.zwobble.mammoth.tests.docx; import org.hamcrest.Matcher; import org.hamcrest.Matchers; import org.junit.jupiter.api.DynamicTest; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestFactory; import org.zwobble.mammoth.internal.archives.Archive; import org.zwobble.mammoth.internal.archives.InMemoryArchive; import org.zwobble.mammoth.internal.documents.*; import org.zwobble.mammoth.internal.docx.*; import org.zwobble.mammoth.internal.results.InternalResult; import org.zwobble.mammoth.internal.xml.XmlElement; import org.zwobble.mammoth.internal.xml.XmlNode; import org.zwobble.mammoth.internal.xml.XmlNodes; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.function.Function; import java.util.stream.Collectors; import static java.util.Arrays.asList; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; import static org.zwobble.mammoth.internal.documents.NoteReference.endnoteReference; import static org.zwobble.mammoth.internal.documents.NoteReference.footnoteReference; import static org.zwobble.mammoth.internal.util.Lists.eagerMap; import static org.zwobble.mammoth.internal.util.Lists.list; import static org.zwobble.mammoth.internal.util.Maps.map; import static org.zwobble.mammoth.internal.util.Streams.toByteArray; import static org.zwobble.mammoth.internal.xml.XmlNodes.element; import static org.zwobble.mammoth.tests.DeepReflectionMatcher.deepEquals; import static org.zwobble.mammoth.tests.ResultMatchers.*; import static org.zwobble.mammoth.tests.documents.DocumentElementMakers.*; import static org.zwobble.mammoth.tests.docx.BodyXmlReaderMakers.bodyReader; import static org.zwobble.mammoth.tests.docx.DocumentMatchers.*; import static org.zwobble.mammoth.tests.docx.OfficeXmlBuilders.*; public class BodyXmlTests { @Test public void textFromTextElementIsRead() { XmlElement element = textXml("Hello!"); assertThat(readSuccess(bodyReader(), element), isTextElement("Hello!")); } @Test public void canReadTextWithinRun() { XmlElement element = runXml(list(textXml("Hello!"))); assertThat( readSuccess(bodyReader(), element), isRun(run(withChildren(text("Hello!"))))); } @Test public void canReadTextWithinParagraph() { XmlElement element = paragraphXml(list(runXml(list(textXml("Hello!"))))); assertThat( readSuccess(bodyReader(), element), isParagraph(paragraph(withChildren(run(withChildren(text("Hello!"))))))); } @Test public void paragraphHasNoStyleIfItHasNoProperties() { XmlElement element = paragraphXml(); assertThat( readSuccess(bodyReader(), element), hasStyle(Optional.empty())); } @Test public void whenParagraphHasStyleIdInStylesThenStyleNameIsReadFromStyles() { XmlElement element = paragraphXml(list( element("w:pPr", list( element("w:pStyle", map("w:val", "Heading1")))))); Style style = new Style("Heading1", Optional.of("Heading 1")); Styles styles = new Styles( map("Heading1", style), map(), map(), map() ); assertThat( readSuccess(bodyReader(styles), element), hasStyle(Optional.of(style))); } @Test public void warningIsEmittedWhenParagraphStyleCannotBeFound() { XmlElement element = paragraphXml(list( element("w:pPr", list( element("w:pStyle", map("w:val", "Heading1")))))); assertThat( read(bodyReader(), element), isInternalResult( hasStyle(Optional.of(new Style("Heading1", Optional.empty()))), list("Paragraph style with ID Heading1 was referenced but not defined in the document"))); } @Nested public class ParagraphIndentTests { @Test public void whenWStartIsSetThenStartIndentIsReadFromWStart() { XmlElement paragraphXml = paragraphWithIndent(map("w:start", "720", "w:left", "40")); assertThat( readSuccess(bodyReader(), paragraphXml), hasIndent(hasIndentStart(Optional.of("720"))) ); } @Test public void whenWStartIsNotSetThenStartIndentIsReadFromWLeft() { XmlElement paragraphXml = paragraphWithIndent(map("w:left", "720")); assertThat( readSuccess(bodyReader(), paragraphXml), hasIndent(hasIndentStart(Optional.of("720"))) ); } @Test public void whenWEndIsSetThenEndIndentIsReadFromWEnd() { XmlElement paragraphXml = paragraphWithIndent(map("w:end", "720", "w:right", "40")); assertThat( readSuccess(bodyReader(), paragraphXml), hasIndent(hasIndentEnd(Optional.of("720"))) ); } @Test public void whenWEndIsNotSetThenEndIndentIsReadFromWRight() { XmlElement paragraphXml = paragraphWithIndent(map("w:right", "720")); assertThat( readSuccess(bodyReader(), paragraphXml), hasIndent(hasIndentEnd(Optional.of("720"))) ); } @Test public void paragraphHasIndentFirstLineReadFromParagraphPropertiesIfPresent() { XmlElement paragraphXml = paragraphWithIndent(map("w:firstLine", "720")); assertThat( readSuccess(bodyReader(), paragraphXml), hasIndent(hasIndentFirstLine(Optional.of("720"))) ); } @Test public void paragraphHasIndentHangingReadFromParagraphPropertiesIfPresent() { XmlElement paragraphXml = paragraphWithIndent(map("w:hanging", "720")); assertThat( readSuccess(bodyReader(), paragraphXml), hasIndent(hasIndentHanging(Optional.of("720"))) ); } @Test public void whenIndentAttributesArentSetThenIndentsAreNotSet() { XmlElement paragraphXml = paragraphWithIndent(map()); assertThat( readSuccess(bodyReader(), paragraphXml), hasIndent(allOf( hasIndentStart(Optional.empty()), hasIndentEnd(Optional.empty()), hasIndentFirstLine(Optional.empty()), hasIndentHanging(Optional.empty()) )) ); } private XmlElement paragraphWithIndent(Map<String, String> attributes) { return paragraphXml(list( element("w:pPr", list( element("w:ind", attributes) )) )); } } @Test public void paragraphHasNoNumberingIfItHasNoNumberingProperties() { XmlElement element = paragraphXml(); assertThat( readSuccess(bodyReader(), element), hasNumbering(Optional.empty())); } @Test public void paragraphHasNumberingPropertiesFromParagraphPropertiesIfPresent() { XmlElement element = paragraphXml(list( element("w:pPr", list( element("w:numPr", map(), list( element("w:ilvl", map("w:val", "1")), element("w:numId", map("w:val", "42")))))))); Numbering numbering = numberingMap(map("42", map("1", Numbering.AbstractNumLevel.ordered("1")))); assertThat( readSuccess(bodyReader(numbering), element), hasNumbering(NumberingLevel.ordered("1"))); } @Test public void numberingOnParagraphStyleTakesPrecedenceOverNumPr() { XmlElement element = paragraphXml(list( element("w:pPr", list( element("w:pStyle", map("w:val", "List")), element("w:numPr", map(), list( element("w:ilvl", map("w:val", "1")), element("w:numId", map("w:val", "42")) )) )) )); Numbering numbering = numberingMap(map( "42", map("1", new Numbering.AbstractNumLevel("1", false, Optional.empty())), "43", map("1", new Numbering.AbstractNumLevel("1", true, Optional.of("List"))) )); Styles styles = new Styles( map("List", new Style("List", Optional.empty())), map(), map(), map() ); assertThat( readSuccess(bodyReader(numbering, styles), element), hasNumbering(NumberingLevel.ordered("1")) ); } @Test public void numberingPropertiesAreIgnoredIfLevelIsMissing() { // TODO: emit warning XmlElement element = paragraphXml(list( element("w:pPr", list( element("w:numPr", map(), list( element("w:numId", map("w:val", "42")))))))); Numbering numbering = numberingMap(map("42", map("1", Numbering.AbstractNumLevel.ordered("1")))); assertThat( readSuccess(bodyReader(numbering), element), hasNumbering(Optional.empty())); } @Test public void numberingPropertiesAreIgnoredIfNumIdIsMissing() { // TODO: emit warning XmlElement element = paragraphXml(list( element("w:pPr", list( element("w:numPr", map(), list( element("w:ilvl", map("w:val", "1")))))))); Numbering numbering = numberingMap(map("42", map("1", Numbering.AbstractNumLevel.ordered("1")))); assertThat( readSuccess(bodyReader(numbering), element), hasNumbering(Optional.empty())); } @Nested public class ComplexFieldsTests { private final String URI = "http://example.com"; private final XmlElement BEGIN_COMPLEX_FIELD = element("w:r", list( element("w:fldChar", map("w:fldCharType", "begin")) )); private final XmlElement SEPARATE_COMPLEX_FIELD = element("w:r", list( element("w:fldChar", map("w:fldCharType", "separate")) )); private final XmlElement END_COMPLEX_FIELD = element("w:r", list( element("w:fldChar", map("w:fldCharType", "end")) )); private final XmlElement HYPERLINK_INSTRTEXT = element("w:instrText", list( XmlNodes.text(" HYPERLINK \"" + URI + '"') )); private Matcher<DocumentElement> isEmptyHyperlinkedRun() { return isHyperlinkedRun(hasChildren()); } @SafeVarargs private final Matcher<DocumentElement> isHyperlinkedRun(Matcher<? super Hyperlink>... matchers) { return isRun(hasChildren( isHyperlink(matchers) )); } @Test public void runsInAComplexFieldForHyperlinksAreReadAsHyperlinks() { XmlElement hyperlinkRunXml = runXml("this is a hyperlink"); XmlElement element = paragraphXml(list( BEGIN_COMPLEX_FIELD, HYPERLINK_INSTRTEXT, SEPARATE_COMPLEX_FIELD, hyperlinkRunXml, END_COMPLEX_FIELD )); DocumentElement paragraph = readSuccess(bodyReader(), element); assertThat(paragraph, isParagraph(hasChildren( isEmptyRun(), isEmptyHyperlinkedRun(), isHyperlinkedRun( hasHref(URI), hasChildren( isTextElement("this is a hyperlink") ) ), isEmptyRun() ))); } @Test public void runsAfterAComplexFieldForHyperlinksAreNotReadAsHyperlinks() { XmlElement afterEndXml = runXml("this will not be a hyperlink"); XmlElement element = paragraphXml(list( BEGIN_COMPLEX_FIELD, HYPERLINK_INSTRTEXT, SEPARATE_COMPLEX_FIELD, END_COMPLEX_FIELD, afterEndXml )); DocumentElement paragraph = readSuccess(bodyReader(), element); assertThat(paragraph, isParagraph(hasChildren( isEmptyRun(), isEmptyHyperlinkedRun(), isEmptyRun(), isRun(hasChildren( isTextElement("this will not be a hyperlink") )) ))); } @Test public void canHandleSplitInstrTextElements() { XmlElement hyperlinkRunXml = runXml("this is a hyperlink"); XmlElement element = paragraphXml(list( BEGIN_COMPLEX_FIELD, element("w:instrText", list( XmlNodes.text(" HYPE") )), element("w:instrText", list( XmlNodes.text("RLINK \"" + URI + '"') )), SEPARATE_COMPLEX_FIELD, hyperlinkRunXml, END_COMPLEX_FIELD )); DocumentElement paragraph = readSuccess(bodyReader(), element); assertThat(paragraph, isParagraph(hasChildren( isEmptyRun(), isEmptyHyperlinkedRun(), isHyperlinkedRun( hasHref(URI), hasChildren( isTextElement("this is a hyperlink") ) ), isEmptyRun() ))); } @Test public void hyperlinkIsNotEndedByEndOfNestedComplexField() { XmlElement authorInstrText = element("w:instrText", list( XmlNodes.text(" AUTHOR \"John Doe\"") )); XmlElement hyperlinkRunXml = runXml("this is a hyperlink"); XmlElement element = paragraphXml(list( BEGIN_COMPLEX_FIELD, HYPERLINK_INSTRTEXT, SEPARATE_COMPLEX_FIELD, BEGIN_COMPLEX_FIELD, authorInstrText, SEPARATE_COMPLEX_FIELD, END_COMPLEX_FIELD, hyperlinkRunXml, END_COMPLEX_FIELD )); DocumentElement paragraph = readSuccess(bodyReader(), element); assertThat(paragraph, isParagraph(hasChildren( isEmptyRun(), isEmptyHyperlinkedRun(), isEmptyHyperlinkedRun(), isEmptyHyperlinkedRun(), isEmptyHyperlinkedRun(), isHyperlinkedRun( hasHref(URI), hasChildren( isTextElement("this is a hyperlink") ) ), isEmptyRun() ))); } @Test public void complexFieldNestedWithinAHyperlinkComplexFieldIsWrappedWithTheHyperlink() { XmlElement authorInstrText = element("w:instrText", list( XmlNodes.text(" AUTHOR \"John Doe\"") )); XmlElement element = paragraphXml(list( BEGIN_COMPLEX_FIELD, HYPERLINK_INSTRTEXT, SEPARATE_COMPLEX_FIELD, BEGIN_COMPLEX_FIELD, authorInstrText, SEPARATE_COMPLEX_FIELD, runXml("John Doe"), END_COMPLEX_FIELD, END_COMPLEX_FIELD )); DocumentElement paragraph = readSuccess(bodyReader(), element); assertThat(paragraph, isParagraph(hasChildren( isEmptyRun(), isEmptyHyperlinkedRun(), isEmptyHyperlinkedRun(), isEmptyHyperlinkedRun(), isHyperlinkedRun( hasHref(URI), hasChildren( isTextElement("John Doe") ) ), isEmptyHyperlinkedRun(), isEmptyRun() ))); } @Test public void fieldWithoutSeparateFldCharIsIgnored() { XmlElement hyperlinkRunXml = runXml("this is a hyperlink"); XmlElement element = paragraphXml(list( BEGIN_COMPLEX_FIELD, HYPERLINK_INSTRTEXT, SEPARATE_COMPLEX_FIELD, BEGIN_COMPLEX_FIELD, END_COMPLEX_FIELD, hyperlinkRunXml, END_COMPLEX_FIELD )); DocumentElement paragraph = readSuccess(bodyReader(), element); assertThat(paragraph, isParagraph(hasChildren( isEmptyRun(), isEmptyHyperlinkedRun(), isEmptyHyperlinkedRun(), isEmptyHyperlinkedRun(), isHyperlinkedRun( hasHref(URI), hasChildren( isTextElement("this is a hyperlink") ) ), isEmptyRun() ))); } } @Test public void runHasNoStyleIfItHasNoProperties() { XmlElement element = runXml(list()); assertThat( readSuccess(bodyReader(), element), hasStyle(Optional.empty())); } @Test public void whenRunHasStyleIdInStylesThenStyleNameIsReadFromStyles() { XmlElement element = runXml(list( element("w:rPr", list( element("w:rStyle", map("w:val", "Heading1Char")))))); Style style = new Style("Heading1Char", Optional.of("Heading 1 Char")); Styles styles = new Styles( map(), map("Heading1Char", style), map(), map() ); assertThat( readSuccess(bodyReader(styles), element), hasStyle(Optional.of(style))); } @Test public void warningIsEmittedWhenRunStyleCannotBeFound() { XmlElement element = runXml(list( element("w:rPr", list( element("w:rStyle", map("w:val", "Heading1Char")))))); assertThat( read(bodyReader(), element), isInternalResult( hasStyle(Optional.of(new Style("Heading1Char", Optional.empty()))), list("Run style with ID Heading1Char was referenced but not defined in the document"))); } @Test public void runIsNotBoldIfBoldElementIsNotPresent() { XmlElement element = runXmlWithProperties(); assertThat( readSuccess(bodyReader(), element), hasProperty("bold", equalTo(false))); } @Test public void runIsBoldIfBoldElementIsPresent() { XmlElement element = runXmlWithProperties(element("w:b")); assertThat( readSuccess(bodyReader(), element), hasProperty("bold", equalTo(true))); } @Test public void runIsNotItalicIfItalicElementIsNotPresent() { XmlElement element = runXmlWithProperties(); assertThat( readSuccess(bodyReader(), element), hasProperty("italic", equalTo(false))); } @Test public void runIsItalicIfItalicElementIsPresent() { XmlElement element = runXmlWithProperties(element("w:i")); assertThat( readSuccess(bodyReader(), element), hasProperty("italic", equalTo(true))); } @Test public void runIsNotUnderlinedIfUnderlineElementIsNotPresent() { XmlElement element = runXmlWithProperties(); assertThat( readSuccess(bodyReader(), element), hasProperty("underline", equalTo(false)) ); } @Test public void runIsUnderlinedIfUnderlineElementIsPresentWithoutValAttribute() { XmlElement element = runXmlWithProperties(element("w:u")); assertThat( readSuccess(bodyReader(), element), hasProperty("underline", equalTo(true)) ); } @Test public void runIsNotUnderlinedIfUnderlineElementIsPresentAndValIsFalse() { XmlElement element = runXmlWithProperties(element("w:u", map("w:val", "false"))); assertThat( readSuccess(bodyReader(), element), hasProperty("underline", equalTo(false)) ); } @Test public void runIsNotUnderlinedIfUnderlineElementIsPresentAndValIs0() { XmlElement element = runXmlWithProperties(element("w:u", map("w:val", "0"))); assertThat( readSuccess(bodyReader(), element), hasProperty("underline", equalTo(false)) ); } @Test public void runIsNotUnderlinedIfUnderlineElementIsPresentAndValIsNone() { XmlElement element = runXmlWithProperties(element("w:u", map("w:val", "none"))); assertThat( readSuccess(bodyReader(), element), hasProperty("underline", equalTo(false)) ); } @Test public void runIsUnderlinedIfUnderlineElementIsPresentAndValIsNotNoneNorFalsy() { XmlElement element = runXmlWithProperties(element("w:u", map("w:val", "single"))); assertThat( readSuccess(bodyReader(), element), hasProperty("underline", equalTo(true)) ); } @Test public void runIsNotStruckthroughIfStrikethroughElementIsNotPresent() { XmlElement element = runXmlWithProperties(); assertThat( readSuccess(bodyReader(), element), hasProperty("strikethrough", equalTo(false))); } @Test public void runIsStruckthroughIfStrikethroughElementIsPresent() { XmlElement element = runXmlWithProperties(element("w:strike")); assertThat( readSuccess(bodyReader(), element), hasProperty("strikethrough", equalTo(true))); } @Test public void runIsNotSmallCapsIfSmallCapsElementIsNotPresent() { XmlElement element = runXmlWithProperties(); assertThat( readSuccess(bodyReader(), element), hasProperty("smallCaps", equalTo(false))); } @Test public void runIsSmallCapsIfSmallCapsElementIsPresent() { XmlElement element = runXmlWithProperties(element("w:smallCaps")); assertThat( readSuccess(bodyReader(), element), hasProperty("smallCaps", equalTo(true))); } @Nested public class RunBooleanPropertyTests { private class TestCase { final String propertyName; final String tagName; TestCase(String propertyName, String tagName) { this.propertyName = propertyName; this.tagName = tagName; } } private final List<TestCase> TEST_CASES = list( new TestCase("bold", "w:b"), new TestCase("underline", "w:u"), new TestCase("italic", "w:i"), new TestCase("strikethrough", "w:strike"), new TestCase("allCaps", "w:caps"), new TestCase("smallCaps", "w:smallCaps") ); @TestFactory public List<DynamicTest> runBooleanPropertyIsFalseIfElementIsPresentAndValIsFalse() { return eagerMap(TEST_CASES, testCase -> DynamicTest.dynamicTest( testCase.propertyName + " property is false if " + testCase.tagName + " element is present and val is false", () -> { XmlElement element = runXmlWithProperties( element(testCase.tagName, map("w:val", "false")) ); assertThat( readSuccess(bodyReader(), element), hasProperty(testCase.propertyName, equalTo(false))); }) ); } @TestFactory public List<DynamicTest> runBooleanPropertyIsFalseIfElementIsPresentAndValIs0() { return eagerMap(TEST_CASES, testCase -> DynamicTest.dynamicTest( testCase.propertyName + " property is false if " + testCase.tagName + " element is present and val is 0", () -> { XmlElement element = runXmlWithProperties( element(testCase.tagName, map("w:val", "0")) ); assertThat( readSuccess(bodyReader(), element), hasProperty(testCase.propertyName, equalTo(false))); }) ); } @TestFactory public List<DynamicTest> runBooleanPropertyIsFalseIfElementIsPresentAndValIsTrue() { return eagerMap(TEST_CASES, testCase -> DynamicTest.dynamicTest( testCase.propertyName + " property is true if " + testCase.tagName + " element is present and val is true", () -> { XmlElement element = runXmlWithProperties( element(testCase.tagName, map("w:val", "true")) ); assertThat( readSuccess(bodyReader(), element), hasProperty(testCase.propertyName, equalTo(true))); }) ); } @TestFactory public List<DynamicTest> runBooleanPropertyIsFalseIfElementIsPresentAndValIs1() { return eagerMap(TEST_CASES, testCase -> DynamicTest.dynamicTest( testCase.propertyName + " property is false if " + testCase.tagName + " element is present and val is 1", () -> { XmlElement element = runXmlWithProperties( element(testCase.tagName, map("w:val", "1")) ); assertThat( readSuccess(bodyReader(), element), hasProperty(testCase.propertyName, equalTo(true))); }) ); } } @Test public void runHasBaselineVerticalAlignmentIfVerticalAlignmentElementIsNotPresent() { XmlElement element = runXmlWithProperties(); assertThat( readSuccess(bodyReader(), element), hasProperty("verticalAlignment", equalTo(VerticalAlignment.BASELINE))); } @Test public void runIsSuperscriptIfVerticalAlignmentPropertyIsSetToSuperscript() { XmlElement element = runXmlWithProperties( element("w:vertAlign", map("w:val", "superscript"))); assertThat( readSuccess(bodyReader(), element), hasProperty("verticalAlignment", equalTo(VerticalAlignment.SUPERSCRIPT))); } @Test public void runIsSubscriptIfVerticalAlignmentPropertyIsSetToSubscript() { XmlElement element = runXmlWithProperties( element("w:vertAlign", map("w:val", "subscript"))); assertThat( readSuccess(bodyReader(), element), hasProperty("verticalAlignment", equalTo(VerticalAlignment.SUBSCRIPT))); } @Test public void canReadTabElement() { XmlElement element = element("w:tab"); assertThat( readSuccess(bodyReader(), element), equalTo(Tab.TAB)); } @Test public void noBreakHyphenElementIsReadAsNonBreakingHyphenCharacter() { XmlElement element = element("w:noBreakHyphen"); assertThat( readSuccess(bodyReader(), element), isTextElement("\u2011") ); } @Test public void softHyphenElementIsReadAsSoftHyphenCharacter() { XmlElement element = element("w:softHyphen"); assertThat( readSuccess(bodyReader(), element), isTextElement("\u00ad") ); } @Test public void symWithSupportedFontAndSupportedCodePointInAsciiRangeIsConvertedToText() { XmlElement element = element("w:sym", map("w:font", "Wingdings", "w:char", "28")); DocumentElement result = readSuccess(bodyReader(), element); assertThat( result, isTextElement("\uD83D\uDD7F") ); } @Test public void symWithSupportedFontAndSupportedCodePointInPrivateUseAreaIsConvertedToText() { XmlElement element = element("w:sym", map("w:font", "Wingdings", "w:char", "F028")); DocumentElement result = readSuccess(bodyReader(), element); assertThat( result, isTextElement("\uD83D\uDD7F") ); } @Test public void symWithUnsupportedFontAndCodePointProducesEmptyResultWithWarning() { XmlElement element = element("w:sym", map("w:font", "Dingwings", "w:char", "28")); InternalResult<List<DocumentElement>> result = readAll(bodyReader(), element); assertThat(result, isInternalResult( equalTo(list()), list("A w:sym element with an unsupported character was ignored: char 28 in font Dingwings") )); } @Test public void brWithoutExplicitTypeIsReadAsLineBreak() { XmlElement element = element("w:br"); assertThat( readSuccess(bodyReader(), element), equalTo(Break.LINE_BREAK)); } @Test public void brWithTextWrappingTypeIsReadAsLineBreak() { XmlElement element = element("w:br", map("w:type", "textWrapping")); assertThat( readSuccess(bodyReader(), element), equalTo(Break.LINE_BREAK) ); } @Test public void brWithPageTypeIsReadAsPageBreak() { XmlElement element = element("w:br", map("w:type", "page")); assertThat( readSuccess(bodyReader(), element), equalTo(Break.PAGE_BREAK) ); } @Test public void brWithColumnTypeIsReadAsColumnBreak() { XmlElement element = element("w:br", map("w:type", "column")); assertThat( readSuccess(bodyReader(), element), equalTo(Break.COLUMN_BREAK) ); } @Test public void warningOnBreaksThatArentRecognised() { XmlElement element = element("w:br", map("w:type", "unknownBreakType")); assertThat( readAll(bodyReader(), element), isInternalResult(equalTo(list()), list("Unsupported break type: unknownBreakType"))); } @Test public void canReadTableElements() { XmlElement element = element("w:tbl", list( element("w:tr", list( element("w:tc", list( element("w:p"))))))); assertThat( readSuccess(bodyReader(), element), isTable(hasChildren( deepEquals(tableRow(list( new TableCell(1, 1, list( paragraph() )) ))) )) ); } @Test public void tableHasNoStyleIfItHasNoProperties() { XmlElement element = element("w:tbl"); assertThat( readSuccess(bodyReader(), element), hasStyle(Optional.empty()) ); } @Test public void whenTableHasStyleIdInStylesThenStyleNameIsReadFromStyles() { XmlElement element = element("w:tbl", list( element("w:tblPr", list( element("w:tblStyle", map("w:val", "TableNormal")) )) )); Style style = new Style("TableNormal", Optional.of("Normal Table")); Styles styles = new Styles( map(), map(), map("TableNormal", style), map() ); assertThat( readSuccess(bodyReader(styles), element), hasStyle(Optional.of(style)) ); } @Test public void warningIsEmittedWhenTableStyleCannotBeFound() { XmlElement element = element("w:tbl", list( element("w:tblPr", list( element("w:tblStyle", map("w:val", "TableNormal")) )) )); assertThat( read(bodyReader(), element), isInternalResult( hasStyle(Optional.of(new Style("TableNormal", Optional.empty()))), list("Table style with ID TableNormal was referenced but not defined in the document") ) ); } @Test public void tblHeaderMarksTableRowAsHeader() { XmlElement element = element("w:tbl", list( element("w:tr", list( element("w:trPr", list( element("w:tblHeader") )) )), element("w:tr") )); assertThat( readSuccess(bodyReader(), element), isTable(hasChildren( isRow(isHeader(true)), isRow(isHeader(false)) )) ); } @Test public void gridspanIsReadAsColspanForTableCell() { XmlElement element = element("w:tbl", list( element("w:tr", list( element("w:tc", list( element("w:tcPr", list( element("w:gridSpan", map("w:val", "2")) )), element("w:p"))))))); assertThat( readSuccess(bodyReader(), element), deepEquals(table(list( tableRow(list( new TableCell(1, 2, list( paragraph() )) )) ))) ); } @Test public void vmergeIsReadAsRowspanForTableCell() { XmlElement element = element("w:tbl", list( wTr(wTc()), wTr(wTc(wTcPr(wVmerge("restart")))), wTr(wTc(wTcPr(wVmerge("continue")))), wTr(wTc(wTcPr(wVmerge("continue")))), wTr(wTc()) )); assertThat( readSuccess(bodyReader(), element), deepEquals(table(list( tableRow(list(new TableCell(1, 1, list()))), tableRow(list(new TableCell(3, 1, list()))), tableRow(list()), tableRow(list()), tableRow(list(new TableCell(1, 1, list()))) ))) ); } @Test public void vmergeWithoutValIsTreatedAsContinue() { XmlElement element = element("w:tbl", list( wTr(wTc(wTcPr(wVmerge("restart")))), wTr(wTc(wTcPr(element("w:vMerge")))) )); assertThat( readSuccess(bodyReader(), element), deepEquals(table(list( tableRow(list(new TableCell(2, 1, list()))), tableRow(list()) ))) ); } @Test public void vmergeAccountsForCellsSpanningColumns() { XmlElement element = element("w:tbl", list( wTr(wTc(), wTc(), wTc(wTcPr(wVmerge("restart")))), wTr(wTc(wTcPr(wGridspan("2"))), wTc(wTcPr(wVmerge("continue")))), wTr(wTc(), wTc(), wTc(wTcPr(wVmerge("continue")))), wTr(wTc(), wTc(), wTc()) )); assertThat( readSuccess(bodyReader(), element), deepEquals(table(list( tableRow(list(new TableCell(1, 1, list()), new TableCell(1, 1, list()), new TableCell(3, 1, list()))), tableRow(list(new TableCell(1, 2, list()))), tableRow(list(new TableCell(1, 1, list()), new TableCell(1, 1, list()))), tableRow(list(new TableCell(1, 1, list()), new TableCell(1, 1, list()), new TableCell(1, 1, list()))) ))) ); } @Test public void noVerticalCellMergingIfMergedCellsDoNotLineUp() { XmlElement element = element("w:tbl", list( wTr(wTc(wTcPr(wGridspan("2"))), wTc(wTcPr(wVmerge("restart")))), wTr(wTc(), wTc(wTcPr(wVmerge("continue")))) )); assertThat( readSuccess(bodyReader(), element), deepEquals(table(list( tableRow(list(new TableCell(1, 2, list()), new TableCell(1, 1, list()))), tableRow(list(new TableCell(1, 1, list()), new TableCell(1, 1, list()))) ))) ); } @Test public void warningIfNonRowInTable() { XmlElement element = element("w:tbl", list( element("w:p") )); assertThat( read(bodyReader(), element), isInternalResult( deepEquals(table(list(paragraph()))), list("unexpected non-row element in table, cell merging may be incorrect") ) ); } @Test public void warningIfNonCellInTableRow() { XmlElement element = element("w:tbl", list( wTr(element("w:p")) )); assertThat( read(bodyReader(), element), isInternalResult( deepEquals(table(list(tableRow(list(paragraph()))))), list("unexpected non-cell element in table row, cell merging may be incorrect") ) ); } @Test public void hyperlinkIsReadAsExternalHyperlinkIfItHasARelationshipId() { Relationships relationships = new Relationships(list( hyperlinkRelationship("r42", "http://example.com") )); XmlElement element = element("w:hyperlink", map("r:id", "r42"), list(runXml(list()))); assertThat( readSuccess(bodyReader(relationships), element), isHyperlink( hasHref("http://example.com"), hasNoAnchor(), hasChildren(isRun(hasChildren())) ) ); } @Test public void hyperlinkIsReadAsExternalHyperlinkIfItHasARelationshipIdAndAnAnchor() { Relationships relationships = new Relationships(list( hyperlinkRelationship("r42", "http://example.com/") )); XmlElement element = element("w:hyperlink", map("r:id", "r42", "w:anchor", "fragment"), list(runXml(list()))); assertThat( readSuccess(bodyReader(relationships), element), isHyperlink(hasHref("http://example.com/#fragment")) ); } @Test public void hyperlinkExistingFragmentIsReplacedWhenAnchorIsSetOnExternalLink() { Relationships relationships = new Relationships(list( hyperlinkRelationship("r42", "http://example.com/#previous") )); XmlElement element = element("w:hyperlink", map("r:id", "r42", "w:anchor", "fragment"), list(runXml(list()))); assertThat( readSuccess(bodyReader(relationships), element), isHyperlink(hasHref("http://example.com/#fragment")) ); } @Test public void hyperlinkIsReadAsInternalHyperlinkIfItHasAnAnchorAttribute() { XmlElement element = element("w:hyperlink", map("w:anchor", "start"), list(runXml(list()))); assertThat( readSuccess(bodyReader(), element), isHyperlink( hasAnchor("start"), hasNoHref() ) ); } @Test public void hyperlinkIsIgnoredIfItDoesNotHaveARelationshipIdNorAnchor() { XmlElement element = element("w:hyperlink", list(runXml(list()))); assertThat( readSuccess(bodyReader(), element), deepEquals(run(withChildren()))); } @Test public void hyperlinkTargetFrameIsRead() { XmlElement element = element("w:hyperlink", map( "w:anchor", "start", "w:tgtFrame", "_blank" )); assertThat( readSuccess(bodyReader(), element), isHyperlink(hasTargetFrame("_blank")) ); } @Test public void hyperlinkEmptyTargetFrameIsIgnored() { XmlElement element = element("w:hyperlink", map( "w:anchor", "start", "w:tgtFrame", "" )); assertThat( readSuccess(bodyReader(), element), isHyperlink(hasNoTargetFrame()) ); } @Test public void goBackBookmarkIsIgnored() { XmlElement element = element("w:bookmarkStart", map("w:name", "_GoBack")); assertThat( readAll(bodyReader(), element), isInternalResult(equalTo(list()), list())); } @Test public void bookmarkStartIsReadIfNameIsNotGoBack() { XmlElement element = element("w:bookmarkStart", map("w:name", "start")); assertThat( readSuccess(bodyReader(), element), deepEquals(new Bookmark("start"))); } @Test public void footnoteReferenceHasIdRead() { XmlElement element = element("w:footnoteReference", map("w:id", "4")); assertThat( readSuccess(bodyReader(), element), deepEquals(footnoteReference("4"))); } @Test public void endnoteReferenceHasIdRead() { XmlElement element = element("w:endnoteReference", map("w:id", "4")); assertThat( readSuccess(bodyReader(), element), deepEquals(endnoteReference("4"))); } @Test public void commentReferenceHasIdRead() { XmlElement element = element("w:commentReference", map("w:id", "4")); assertThat( readSuccess(bodyReader(), element), deepEquals(new CommentReference("4"))); } @Test public void textBoxesHaveContentAppendedAfterContainingParagraph() { XmlElement textBox = element("w:pict", list( element("v:shape", list( element("v:textbox", list( element("w:txbxContent", list( paragraphXml(list( runXml(list(textXml("[textbox-content]"))))))))))))); XmlElement paragraph = paragraphXml(list( runXml(list(textXml("[paragragh start]"))), runXml(list(textBox, textXml("[paragragh end]"))))); List<DocumentElement> expected = list( paragraph(withChildren( run(withChildren( new Text("[paragragh start]"))), run(withChildren( new Text("[paragragh end]"))))), paragraph(withChildren( run(withChildren( new Text("[textbox-content]")))))); assertThat( readAll(bodyReader(), paragraph), isInternalResult(deepEquals(expected), list())); } private static final String IMAGE_BYTES = "Not an image at all!"; private static final String IMAGE_RELATIONSHIP_ID = "rId5"; @Test public void canReadImagedataElementsWithIdAttribute() throws IOException { assertCanReadEmbeddedImage(image -> element("v:imagedata", map("r:id", image.relationshipId, "o:title", image.altText))); } @Test public void whenImagedataElementHasNoRelationshipIdThenItIsIgnoredWithWarning() throws IOException { XmlElement element = element("v:imagedata"); assertThat( readAll(bodyReader(), element), isInternalResult(equalTo(list()), list("A v:imagedata element without a relationship ID was ignored"))); } @Test public void canReadInlinePictures() throws IOException { assertCanReadEmbeddedImage(image -> inlineImageXml(embeddedBlipXml(image.relationshipId), image.altText)); } @Test public void altTextTitleIsUsedIfAltTextDescriptionIsBlank() throws IOException { XmlElement element = inlineImageXml( embeddedBlipXml(IMAGE_RELATIONSHIP_ID), Optional.of(" "), Optional.of("It's a hat") ); Image image = readEmbeddedImage(element); assertThat(image, hasProperty("altText", deepEquals(Optional.of("It's a hat")))); } @Test public void altTextTitleIsUsedIfAltTextDescriptionIsMissing() throws IOException { XmlElement element = inlineImageXml( embeddedBlipXml(IMAGE_RELATIONSHIP_ID), Optional.empty(), Optional.of("It's a hat") ); Image image = readEmbeddedImage(element); assertThat(image, hasProperty("altText", deepEquals(Optional.of("It's a hat")))); } @Test public void altTextDescriptionIsPreferredToAltTextTitle() throws IOException { XmlElement element = inlineImageXml( embeddedBlipXml(IMAGE_RELATIONSHIP_ID), Optional.of("It's a hat"), Optional.of("hat") ); Image image = readEmbeddedImage(element); assertThat(image, hasProperty("altText", deepEquals(Optional.of("It's a hat")))); } @Test public void canReadAnchoredPictures() throws IOException { assertCanReadEmbeddedImage(image -> anchoredImageXml(embeddedBlipXml(image.relationshipId), image.altText)); } private void assertCanReadEmbeddedImage(Function<EmbeddedImage, XmlElement> generateXml) throws IOException { XmlElement element = generateXml.apply(new EmbeddedImage(IMAGE_RELATIONSHIP_ID, "It's a hat")); Image image = readEmbeddedImage(element); assertThat(image, allOf( hasProperty("altText", deepEquals(Optional.of("It's a hat"))), hasProperty("contentType", deepEquals(Optional.of("image/png"))))); assertThat( toString(image.open()), equalTo(IMAGE_BYTES)); } private Image readEmbeddedImage(XmlElement element) { Relationships relationships = new Relationships(list( imageRelationship(IMAGE_RELATIONSHIP_ID, "media/hat.png") )); Archive file = InMemoryArchive.fromStrings(map("word/media/hat.png", IMAGE_BYTES)); return (Image) readSuccess( BodyXmlReaderMakers.bodyReader(relationships, file), element); } private static String toString(InputStream stream) throws IOException { return new String(toByteArray(stream), StandardCharsets.UTF_8); } private class EmbeddedImage { private final String relationshipId; private final String altText; public EmbeddedImage(String relationshipId, String altText) { this.relationshipId = relationshipId; this.altText = altText; } } @Test public void warningIfImageTypeIsUnsupportedByWebBrowsers() { XmlElement element = inlineImageXml(embeddedBlipXml(IMAGE_RELATIONSHIP_ID), ""); Relationships relationships = new Relationships(list( imageRelationship(IMAGE_RELATIONSHIP_ID, "media/hat.emf") )); Archive file = InMemoryArchive.fromStrings(map("word/media/hat.emf", IMAGE_BYTES)); ContentTypes contentTypes = new ContentTypes(map("emf", "image/x-emf"), map()); InternalResult<?> result = read( bodyReader(relationships, file, contentTypes), element); assertThat( result, hasWarnings(list("Image of type image/x-emf is unlikely to display in web browsers"))); } @Test public void canReadLinkedPictures() throws IOException { XmlElement element = inlineImageXml(linkedBlipXml(IMAGE_RELATIONSHIP_ID), ""); Relationships relationships = new Relationships(list( imageRelationship(IMAGE_RELATIONSHIP_ID, "file:///media/hat.png") )); Image image = (Image) readSuccess( bodyReader(relationships, new InMemoryFileReader(map("file:///media/hat.png", IMAGE_BYTES))), element); assertThat( toString(image.open()), equalTo(IMAGE_BYTES)); } private XmlElement inlineImageXml(XmlElement blip, String description) { return inlineImageXml(blip, Optional.of(description), Optional.empty()); } private XmlElement inlineImageXml(XmlElement blip, Optional<String> description, Optional<String> title) { return element("w:drawing", list( element("wp:inline", imageXml(blip, description, title)))); } private XmlElement anchoredImageXml(XmlElement blip, String description) { return element("w:drawing", list( element("wp:anchor", imageXml(blip, Optional.of(description), Optional.empty())))); } private List<XmlNode> imageXml(XmlElement blip, Optional<String> description, Optional<String> title) { Map<String, String> properties = new HashMap<>(); description.ifPresent(value -> properties.put("descr", value)); title.ifPresent(value -> properties.put("title", value)); return list( element("wp:docPr", properties), element("a:graphic", list( element("a:graphicData", list( element("pic:pic", list( element("pic:blipFill", list(blip))))))))); } private XmlElement embeddedBlipXml(String relationshipId) { return blipXml(map("r:embed", relationshipId)); } private XmlElement linkedBlipXml(String relationshipId) { return blipXml(map("r:link", relationshipId)); } private XmlElement blipXml(Map<String, String> attributes) { return element("a:blip", attributes); } @Test public void sdtIsReadUsingSdtContent() throws IOException { XmlElement element = element("w:sdt", list(element("w:sdtContent", list(textXml("Blackdown"))))); assertThat( readAll(bodyReader(), element), isInternalSuccess(deepEquals(list(text("Blackdown"))))); } @Test public void appropriateElementsHaveTheirChildrenReadNormally() { assertChildrenAreReadNormally("w:ins"); assertChildrenAreReadNormally("w:object"); assertChildrenAreReadNormally("w:smartTag"); assertChildrenAreReadNormally("w:drawing"); assertChildrenAreReadNormally("v:group"); assertChildrenAreReadNormally("v:rect"); assertChildrenAreReadNormally("v:roundrect"); assertChildrenAreReadNormally("v:shape"); assertChildrenAreReadNormally("v:textbox"); assertChildrenAreReadNormally("w:txbxContent"); } private void assertChildrenAreReadNormally(String name) { XmlElement element = element(name, list(paragraphXml())); assertThat( readSuccess(bodyReader(), element), deepEquals(paragraph())); } @Test public void ignoredElementsAreIgnoredWithoutWarning() { assertIsIgnored("office-word:wrap"); assertIsIgnored("v:shadow"); assertIsIgnored("v:shapetype"); assertIsIgnored("w:bookmarkEnd"); assertIsIgnored("w:sectPr"); assertIsIgnored("w:proofErr"); assertIsIgnored("w:lastRenderedPageBreak"); assertIsIgnored("w:commentRangeStart"); assertIsIgnored("w:commentRangeEnd"); assertIsIgnored("w:del"); assertIsIgnored("w:footnoteRef"); assertIsIgnored("w:endnoteRef"); assertIsIgnored("w:annotationRef"); assertIsIgnored("w:pPr"); assertIsIgnored("w:rPr"); assertIsIgnored("w:tblPr"); assertIsIgnored("w:tblGrid"); assertIsIgnored("w:tcPr"); } private void assertIsIgnored(String name) { XmlElement element = element(name, list(paragraphXml())); assertThat( readAll(bodyReader(), element), isInternalResult(equalTo(list()), list())); } @Test public void unrecognisedElementsAreIgnoredWithWarning() { XmlElement element = element("w:huh"); assertThat( readAll(bodyReader(), element), isInternalResult(equalTo(list()), list("An unrecognised element was ignored: w:huh"))); } @Test public void textNodesAreIgnoredWhenReadingChildren() { XmlElement element = runXml(list(XmlNodes.text("[text]"))); assertThat( readSuccess(bodyReader(), element), deepEquals(run(withChildren()))); } private static DocumentElement readSuccess(BodyXmlReader reader, XmlElement element) { InternalResult<DocumentElement> result = read(reader, element); assertThat(result.getWarnings(), emptyIterable()); return result.getValue(); } private static InternalResult<DocumentElement> read(BodyXmlReader reader, XmlElement element) { InternalResult<List<DocumentElement>> result = readAll(reader, element); assertThat(result.getValue(), Matchers.hasSize(1)); return result.map(elements -> elements.get(0)); } private static InternalResult<List<DocumentElement>> readAll(BodyXmlReader reader, XmlElement element) { return reader.readElement(element).toResult(); } private XmlElement paragraphXml() { return paragraphXml(list()); } private static XmlElement paragraphXml(List<XmlNode> children) { return element("w:p", children); } private static XmlElement runXml(String text) { return runXml(list(textXml(text))); } private static XmlElement runXml(List<XmlNode> children) { return element("w:r", children); } private static XmlElement runXmlWithProperties(XmlNode... children) { return element("w:r", list(element("w:rPr", asList(children)))); } private static XmlElement textXml(String value) { return element("w:t", list(XmlNodes.text(value))); } private Matcher<? super DocumentElement> hasStyle(Optional<Style> expected) { return hasProperty("style", deepEquals(expected)); } private Matcher<? super DocumentElement> hasNumbering(NumberingLevel expected) { return hasNumbering(Optional.of(expected)); } private Matcher<? super DocumentElement> hasNumbering(Optional<NumberingLevel> expected) { return hasProperty("numbering", deepEquals(expected)); } private Matcher<? super DocumentElement> hasIndent(Matcher<ParagraphIndent> expected) { return hasProperty("indent", expected); } private Matcher<ParagraphIndent> hasIndentStart(Optional<String> value) { return hasProperty("start", equalTo(value)); } private Matcher<ParagraphIndent> hasIndentEnd(Optional<String> value) { return hasProperty("end", equalTo(value)); } private Matcher<ParagraphIndent> hasIndentFirstLine(Optional<String> value) { return hasProperty("firstLine", equalTo(value)); } private Matcher<ParagraphIndent> hasIndentHanging(Optional<String> value) { return hasProperty("hanging", equalTo(value)); } private static Text text(String value) { return new Text(value); } private static Relationship hyperlinkRelationship(String relationshipId, String target) { return new Relationship(relationshipId, target, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink"); } private static Relationship imageRelationship(String relationshipId, String target) { return new Relationship(relationshipId, target, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image"); } private static Numbering numberingMap(Map<String, Map<String, Numbering.AbstractNumLevel>> numbering) { return new Numbering( numbering.entrySet().stream().collect(Collectors.toMap( entry -> entry.getKey(), entry -> new Numbering.AbstractNum(entry.getValue(), Optional.empty()) )), numbering.keySet().stream().collect(Collectors.toMap( numId -> numId, numId -> new Numbering.Num(Optional.of(numId)) )), Styles.EMPTY ); } }
src/test/java/org/zwobble/mammoth/tests/docx/BodyXmlTests.java
package org.zwobble.mammoth.tests.docx; import org.hamcrest.Matcher; import org.hamcrest.Matchers; import org.junit.jupiter.api.DynamicTest; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestFactory; import org.zwobble.mammoth.internal.archives.Archive; import org.zwobble.mammoth.internal.archives.InMemoryArchive; import org.zwobble.mammoth.internal.documents.*; import org.zwobble.mammoth.internal.docx.*; import org.zwobble.mammoth.internal.results.InternalResult; import org.zwobble.mammoth.internal.xml.XmlElement; import org.zwobble.mammoth.internal.xml.XmlNode; import org.zwobble.mammoth.internal.xml.XmlNodes; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.function.Function; import java.util.stream.Collectors; import static java.util.Arrays.asList; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; import static org.zwobble.mammoth.internal.documents.NoteReference.endnoteReference; import static org.zwobble.mammoth.internal.documents.NoteReference.footnoteReference; import static org.zwobble.mammoth.internal.util.Lists.eagerMap; import static org.zwobble.mammoth.internal.util.Lists.list; import static org.zwobble.mammoth.internal.util.Maps.map; import static org.zwobble.mammoth.internal.util.Streams.toByteArray; import static org.zwobble.mammoth.internal.xml.XmlNodes.element; import static org.zwobble.mammoth.tests.DeepReflectionMatcher.deepEquals; import static org.zwobble.mammoth.tests.ResultMatchers.*; import static org.zwobble.mammoth.tests.documents.DocumentElementMakers.*; import static org.zwobble.mammoth.tests.docx.BodyXmlReaderMakers.bodyReader; import static org.zwobble.mammoth.tests.docx.DocumentMatchers.*; import static org.zwobble.mammoth.tests.docx.OfficeXmlBuilders.*; public class BodyXmlTests { @Test public void textFromTextElementIsRead() { XmlElement element = textXml("Hello!"); assertThat(readSuccess(bodyReader(), element), isTextElement("Hello!")); } @Test public void canReadTextWithinRun() { XmlElement element = runXml(list(textXml("Hello!"))); assertThat( readSuccess(bodyReader(), element), isRun(run(withChildren(text("Hello!"))))); } @Test public void canReadTextWithinParagraph() { XmlElement element = paragraphXml(list(runXml(list(textXml("Hello!"))))); assertThat( readSuccess(bodyReader(), element), isParagraph(paragraph(withChildren(run(withChildren(text("Hello!"))))))); } @Test public void paragraphHasNoStyleIfItHasNoProperties() { XmlElement element = paragraphXml(); assertThat( readSuccess(bodyReader(), element), hasStyle(Optional.empty())); } @Test public void whenParagraphHasStyleIdInStylesThenStyleNameIsReadFromStyles() { XmlElement element = paragraphXml(list( element("w:pPr", list( element("w:pStyle", map("w:val", "Heading1")))))); Style style = new Style("Heading1", Optional.of("Heading 1")); Styles styles = new Styles( map("Heading1", style), map(), map(), map() ); assertThat( readSuccess(bodyReader(styles), element), hasStyle(Optional.of(style))); } @Test public void warningIsEmittedWhenParagraphStyleCannotBeFound() { XmlElement element = paragraphXml(list( element("w:pPr", list( element("w:pStyle", map("w:val", "Heading1")))))); assertThat( read(bodyReader(), element), isInternalResult( hasStyle(Optional.of(new Style("Heading1", Optional.empty()))), list("Paragraph style with ID Heading1 was referenced but not defined in the document"))); } @Nested public class ParagraphIndentTests { @Test public void whenWStartIsSetThenStartIndentIsReadFromWStart() { XmlElement paragraphXml = paragraphWithIndent(map("w:start", "720", "w:left", "40")); assertThat( readSuccess(bodyReader(), paragraphXml), hasIndent(hasIndentStart(Optional.of("720"))) ); } @Test public void whenWStartIsNotSetThenStartIndentIsReadFromWLeft() { XmlElement paragraphXml = paragraphWithIndent(map("w:left", "720")); assertThat( readSuccess(bodyReader(), paragraphXml), hasIndent(hasIndentStart(Optional.of("720"))) ); } @Test public void whenWEndIsSetThenEndIndentIsReadFromWEnd() { XmlElement paragraphXml = paragraphWithIndent(map("w:end", "720", "w:right", "40")); assertThat( readSuccess(bodyReader(), paragraphXml), hasIndent(hasIndentEnd(Optional.of("720"))) ); } @Test public void whenWEndIsNotSetThenEndIndentIsReadFromWRight() { XmlElement paragraphXml = paragraphWithIndent(map("w:right", "720")); assertThat( readSuccess(bodyReader(), paragraphXml), hasIndent(hasIndentEnd(Optional.of("720"))) ); } @Test public void paragraphHasIndentFirstLineReadFromParagraphPropertiesIfPresent() { XmlElement paragraphXml = paragraphWithIndent(map("w:firstLine", "720")); assertThat( readSuccess(bodyReader(), paragraphXml), hasIndent(hasIndentFirstLine(Optional.of("720"))) ); } @Test public void paragraphHasIndentHangingReadFromParagraphPropertiesIfPresent() { XmlElement paragraphXml = paragraphWithIndent(map("w:hanging", "720")); assertThat( readSuccess(bodyReader(), paragraphXml), hasIndent(hasIndentHanging(Optional.of("720"))) ); } @Test public void whenIndentAttributesArentSetThenIndentsAreNotSet() { XmlElement paragraphXml = paragraphWithIndent(map()); assertThat( readSuccess(bodyReader(), paragraphXml), hasIndent(allOf( hasIndentStart(Optional.empty()), hasIndentEnd(Optional.empty()), hasIndentFirstLine(Optional.empty()), hasIndentHanging(Optional.empty()) )) ); } private XmlElement paragraphWithIndent(Map<String, String> attributes) { return paragraphXml(list( element("w:pPr", list( element("w:ind", attributes) )) )); } } @Test public void paragraphHasNoNumberingIfItHasNoNumberingProperties() { XmlElement element = paragraphXml(); assertThat( readSuccess(bodyReader(), element), hasNumbering(Optional.empty())); } @Test public void paragraphHasNumberingPropertiesFromParagraphPropertiesIfPresent() { XmlElement element = paragraphXml(list( element("w:pPr", list( element("w:numPr", map(), list( element("w:ilvl", map("w:val", "1")), element("w:numId", map("w:val", "42")))))))); Numbering numbering = numberingMap(map("42", map("1", Numbering.AbstractNumLevel.ordered("1")))); assertThat( readSuccess(bodyReader(numbering), element), hasNumbering(NumberingLevel.ordered("1"))); } @Test public void numberingOnParagraphStyleTakesPrecedenceOverNumPr() { XmlElement element = paragraphXml(list( element("w:pPr", list( element("w:pStyle", map("w:val", "List")), element("w:numPr", map(), list( element("w:ilvl", map("w:val", "1")), element("w:numId", map("w:val", "42")) )) )) )); Numbering numbering = numberingMap(map( "42", map("1", new Numbering.AbstractNumLevel("1", false, Optional.empty())), "43", map("1", new Numbering.AbstractNumLevel("1", true, Optional.of("List"))) )); Styles styles = new Styles( map("List", new Style("List", Optional.empty())), map(), map(), map() ); assertThat( readSuccess(bodyReader(numbering, styles), element), hasNumbering(NumberingLevel.ordered("1")) ); } @Test public void numberingPropertiesAreIgnoredIfLevelIsMissing() { // TODO: emit warning XmlElement element = paragraphXml(list( element("w:pPr", list( element("w:numPr", map(), list( element("w:numId", map("w:val", "42")))))))); Numbering numbering = numberingMap(map("42", map("1", Numbering.AbstractNumLevel.ordered("1")))); assertThat( readSuccess(bodyReader(numbering), element), hasNumbering(Optional.empty())); } @Test public void numberingPropertiesAreIgnoredIfNumIdIsMissing() { // TODO: emit warning XmlElement element = paragraphXml(list( element("w:pPr", list( element("w:numPr", map(), list( element("w:ilvl", map("w:val", "1")))))))); Numbering numbering = numberingMap(map("42", map("1", Numbering.AbstractNumLevel.ordered("1")))); assertThat( readSuccess(bodyReader(numbering), element), hasNumbering(Optional.empty())); } @Nested public class ComplexFieldsTests { private final String URI = "http://example.com"; private final XmlElement BEGIN_COMPLEX_FIELD = element("w:r", list( element("w:fldChar", map("w:fldCharType", "begin")) )); private final XmlElement SEPARATE_COMPLEX_FIELD = element("w:r", list( element("w:fldChar", map("w:fldCharType", "separate")) )); private final XmlElement END_COMPLEX_FIELD = element("w:r", list( element("w:fldChar", map("w:fldCharType", "end")) )); private final XmlElement HYPERLINK_INSTRTEXT = element("w:instrText", list( XmlNodes.text(" HYPERLINK \"" + URI + '"') )); private Matcher<DocumentElement> isEmptyHyperlinkedRun() { return isHyperlinkedRun(hasChildren()); } @SafeVarargs private final Matcher<DocumentElement> isHyperlinkedRun(Matcher<? super Hyperlink>... matchers) { return isRun(hasChildren( allOf( isHyperlink(hasHref(URI)), isHyperlink(matchers) ) )); } @Test public void runsInAComplexFieldForHyperlinksAreReadAsHyperlinks() { XmlElement hyperlinkRunXml = runXml("this is a hyperlink"); XmlElement element = paragraphXml(list( BEGIN_COMPLEX_FIELD, HYPERLINK_INSTRTEXT, SEPARATE_COMPLEX_FIELD, hyperlinkRunXml, END_COMPLEX_FIELD )); DocumentElement paragraph = readSuccess(bodyReader(), element); assertThat(paragraph, isParagraph(hasChildren( isEmptyRun(), isEmptyHyperlinkedRun(), isHyperlinkedRun(hasChildren( isTextElement("this is a hyperlink") )), isEmptyRun() ))); } @Test public void runsAfterAComplexFieldForHyperlinksAreNotReadAsHyperlinks() { XmlElement afterEndXml = runXml("this will not be a hyperlink"); XmlElement element = paragraphXml(list( BEGIN_COMPLEX_FIELD, HYPERLINK_INSTRTEXT, SEPARATE_COMPLEX_FIELD, END_COMPLEX_FIELD, afterEndXml )); DocumentElement paragraph = readSuccess(bodyReader(), element); assertThat(paragraph, isParagraph(hasChildren( isEmptyRun(), isEmptyHyperlinkedRun(), isEmptyRun(), isRun(hasChildren( isTextElement("this will not be a hyperlink") )) ))); } @Test public void canHandleSplitInstrTextElements() { XmlElement hyperlinkRunXml = runXml("this is a hyperlink"); XmlElement element = paragraphXml(list( BEGIN_COMPLEX_FIELD, element("w:instrText", list( XmlNodes.text(" HYPE") )), element("w:instrText", list( XmlNodes.text("RLINK \"" + URI + '"') )), SEPARATE_COMPLEX_FIELD, hyperlinkRunXml, END_COMPLEX_FIELD )); DocumentElement paragraph = readSuccess(bodyReader(), element); assertThat(paragraph, isParagraph(hasChildren( isEmptyRun(), isEmptyHyperlinkedRun(), isHyperlinkedRun(hasChildren( isTextElement("this is a hyperlink") )), isEmptyRun() ))); } @Test public void hyperlinkIsNotEndedByEndOfNestedComplexField() { XmlElement authorInstrText = element("w:instrText", list( XmlNodes.text(" AUTHOR \"John Doe\"") )); XmlElement hyperlinkRunXml = runXml("this is a hyperlink"); XmlElement element = paragraphXml(list( BEGIN_COMPLEX_FIELD, HYPERLINK_INSTRTEXT, SEPARATE_COMPLEX_FIELD, BEGIN_COMPLEX_FIELD, authorInstrText, SEPARATE_COMPLEX_FIELD, END_COMPLEX_FIELD, hyperlinkRunXml, END_COMPLEX_FIELD )); DocumentElement paragraph = readSuccess(bodyReader(), element); assertThat(paragraph, isParagraph(hasChildren( isEmptyRun(), isEmptyHyperlinkedRun(), isEmptyHyperlinkedRun(), isEmptyHyperlinkedRun(), isEmptyHyperlinkedRun(), isHyperlinkedRun(hasChildren( isTextElement("this is a hyperlink") )), isEmptyRun() ))); } @Test public void complexFieldNestedWithinAHyperlinkComplexFieldIsWrappedWithTheHyperlink() { XmlElement authorInstrText = element("w:instrText", list( XmlNodes.text(" AUTHOR \"John Doe\"") )); XmlElement element = paragraphXml(list( BEGIN_COMPLEX_FIELD, HYPERLINK_INSTRTEXT, SEPARATE_COMPLEX_FIELD, BEGIN_COMPLEX_FIELD, authorInstrText, SEPARATE_COMPLEX_FIELD, runXml("John Doe"), END_COMPLEX_FIELD, END_COMPLEX_FIELD )); DocumentElement paragraph = readSuccess(bodyReader(), element); assertThat(paragraph, isParagraph(hasChildren( isEmptyRun(), isEmptyHyperlinkedRun(), isEmptyHyperlinkedRun(), isEmptyHyperlinkedRun(), isHyperlinkedRun(hasChildren( isTextElement("John Doe") )), isEmptyHyperlinkedRun(), isEmptyRun() ))); } @Test public void fieldWithoutSeparateFldCharIsIgnored() { XmlElement hyperlinkRunXml = runXml("this is a hyperlink"); XmlElement element = paragraphXml(list( BEGIN_COMPLEX_FIELD, HYPERLINK_INSTRTEXT, SEPARATE_COMPLEX_FIELD, BEGIN_COMPLEX_FIELD, END_COMPLEX_FIELD, hyperlinkRunXml, END_COMPLEX_FIELD )); DocumentElement paragraph = readSuccess(bodyReader(), element); assertThat(paragraph, isParagraph(hasChildren( isEmptyRun(), isEmptyHyperlinkedRun(), isEmptyHyperlinkedRun(), isEmptyHyperlinkedRun(), isHyperlinkedRun(hasChildren( isTextElement("this is a hyperlink") )), isEmptyRun() ))); } } @Test public void runHasNoStyleIfItHasNoProperties() { XmlElement element = runXml(list()); assertThat( readSuccess(bodyReader(), element), hasStyle(Optional.empty())); } @Test public void whenRunHasStyleIdInStylesThenStyleNameIsReadFromStyles() { XmlElement element = runXml(list( element("w:rPr", list( element("w:rStyle", map("w:val", "Heading1Char")))))); Style style = new Style("Heading1Char", Optional.of("Heading 1 Char")); Styles styles = new Styles( map(), map("Heading1Char", style), map(), map() ); assertThat( readSuccess(bodyReader(styles), element), hasStyle(Optional.of(style))); } @Test public void warningIsEmittedWhenRunStyleCannotBeFound() { XmlElement element = runXml(list( element("w:rPr", list( element("w:rStyle", map("w:val", "Heading1Char")))))); assertThat( read(bodyReader(), element), isInternalResult( hasStyle(Optional.of(new Style("Heading1Char", Optional.empty()))), list("Run style with ID Heading1Char was referenced but not defined in the document"))); } @Test public void runIsNotBoldIfBoldElementIsNotPresent() { XmlElement element = runXmlWithProperties(); assertThat( readSuccess(bodyReader(), element), hasProperty("bold", equalTo(false))); } @Test public void runIsBoldIfBoldElementIsPresent() { XmlElement element = runXmlWithProperties(element("w:b")); assertThat( readSuccess(bodyReader(), element), hasProperty("bold", equalTo(true))); } @Test public void runIsNotItalicIfItalicElementIsNotPresent() { XmlElement element = runXmlWithProperties(); assertThat( readSuccess(bodyReader(), element), hasProperty("italic", equalTo(false))); } @Test public void runIsItalicIfItalicElementIsPresent() { XmlElement element = runXmlWithProperties(element("w:i")); assertThat( readSuccess(bodyReader(), element), hasProperty("italic", equalTo(true))); } @Test public void runIsNotUnderlinedIfUnderlineElementIsNotPresent() { XmlElement element = runXmlWithProperties(); assertThat( readSuccess(bodyReader(), element), hasProperty("underline", equalTo(false)) ); } @Test public void runIsUnderlinedIfUnderlineElementIsPresentWithoutValAttribute() { XmlElement element = runXmlWithProperties(element("w:u")); assertThat( readSuccess(bodyReader(), element), hasProperty("underline", equalTo(true)) ); } @Test public void runIsNotUnderlinedIfUnderlineElementIsPresentAndValIsFalse() { XmlElement element = runXmlWithProperties(element("w:u", map("w:val", "false"))); assertThat( readSuccess(bodyReader(), element), hasProperty("underline", equalTo(false)) ); } @Test public void runIsNotUnderlinedIfUnderlineElementIsPresentAndValIs0() { XmlElement element = runXmlWithProperties(element("w:u", map("w:val", "0"))); assertThat( readSuccess(bodyReader(), element), hasProperty("underline", equalTo(false)) ); } @Test public void runIsNotUnderlinedIfUnderlineElementIsPresentAndValIsNone() { XmlElement element = runXmlWithProperties(element("w:u", map("w:val", "none"))); assertThat( readSuccess(bodyReader(), element), hasProperty("underline", equalTo(false)) ); } @Test public void runIsUnderlinedIfUnderlineElementIsPresentAndValIsNotNoneNorFalsy() { XmlElement element = runXmlWithProperties(element("w:u", map("w:val", "single"))); assertThat( readSuccess(bodyReader(), element), hasProperty("underline", equalTo(true)) ); } @Test public void runIsNotStruckthroughIfStrikethroughElementIsNotPresent() { XmlElement element = runXmlWithProperties(); assertThat( readSuccess(bodyReader(), element), hasProperty("strikethrough", equalTo(false))); } @Test public void runIsStruckthroughIfStrikethroughElementIsPresent() { XmlElement element = runXmlWithProperties(element("w:strike")); assertThat( readSuccess(bodyReader(), element), hasProperty("strikethrough", equalTo(true))); } @Test public void runIsNotSmallCapsIfSmallCapsElementIsNotPresent() { XmlElement element = runXmlWithProperties(); assertThat( readSuccess(bodyReader(), element), hasProperty("smallCaps", equalTo(false))); } @Test public void runIsSmallCapsIfSmallCapsElementIsPresent() { XmlElement element = runXmlWithProperties(element("w:smallCaps")); assertThat( readSuccess(bodyReader(), element), hasProperty("smallCaps", equalTo(true))); } @Nested public class RunBooleanPropertyTests { private class TestCase { final String propertyName; final String tagName; TestCase(String propertyName, String tagName) { this.propertyName = propertyName; this.tagName = tagName; } } private final List<TestCase> TEST_CASES = list( new TestCase("bold", "w:b"), new TestCase("underline", "w:u"), new TestCase("italic", "w:i"), new TestCase("strikethrough", "w:strike"), new TestCase("allCaps", "w:caps"), new TestCase("smallCaps", "w:smallCaps") ); @TestFactory public List<DynamicTest> runBooleanPropertyIsFalseIfElementIsPresentAndValIsFalse() { return eagerMap(TEST_CASES, testCase -> DynamicTest.dynamicTest( testCase.propertyName + " property is false if " + testCase.tagName + " element is present and val is false", () -> { XmlElement element = runXmlWithProperties( element(testCase.tagName, map("w:val", "false")) ); assertThat( readSuccess(bodyReader(), element), hasProperty(testCase.propertyName, equalTo(false))); }) ); } @TestFactory public List<DynamicTest> runBooleanPropertyIsFalseIfElementIsPresentAndValIs0() { return eagerMap(TEST_CASES, testCase -> DynamicTest.dynamicTest( testCase.propertyName + " property is false if " + testCase.tagName + " element is present and val is 0", () -> { XmlElement element = runXmlWithProperties( element(testCase.tagName, map("w:val", "0")) ); assertThat( readSuccess(bodyReader(), element), hasProperty(testCase.propertyName, equalTo(false))); }) ); } @TestFactory public List<DynamicTest> runBooleanPropertyIsFalseIfElementIsPresentAndValIsTrue() { return eagerMap(TEST_CASES, testCase -> DynamicTest.dynamicTest( testCase.propertyName + " property is true if " + testCase.tagName + " element is present and val is true", () -> { XmlElement element = runXmlWithProperties( element(testCase.tagName, map("w:val", "true")) ); assertThat( readSuccess(bodyReader(), element), hasProperty(testCase.propertyName, equalTo(true))); }) ); } @TestFactory public List<DynamicTest> runBooleanPropertyIsFalseIfElementIsPresentAndValIs1() { return eagerMap(TEST_CASES, testCase -> DynamicTest.dynamicTest( testCase.propertyName + " property is false if " + testCase.tagName + " element is present and val is 1", () -> { XmlElement element = runXmlWithProperties( element(testCase.tagName, map("w:val", "1")) ); assertThat( readSuccess(bodyReader(), element), hasProperty(testCase.propertyName, equalTo(true))); }) ); } } @Test public void runHasBaselineVerticalAlignmentIfVerticalAlignmentElementIsNotPresent() { XmlElement element = runXmlWithProperties(); assertThat( readSuccess(bodyReader(), element), hasProperty("verticalAlignment", equalTo(VerticalAlignment.BASELINE))); } @Test public void runIsSuperscriptIfVerticalAlignmentPropertyIsSetToSuperscript() { XmlElement element = runXmlWithProperties( element("w:vertAlign", map("w:val", "superscript"))); assertThat( readSuccess(bodyReader(), element), hasProperty("verticalAlignment", equalTo(VerticalAlignment.SUPERSCRIPT))); } @Test public void runIsSubscriptIfVerticalAlignmentPropertyIsSetToSubscript() { XmlElement element = runXmlWithProperties( element("w:vertAlign", map("w:val", "subscript"))); assertThat( readSuccess(bodyReader(), element), hasProperty("verticalAlignment", equalTo(VerticalAlignment.SUBSCRIPT))); } @Test public void canReadTabElement() { XmlElement element = element("w:tab"); assertThat( readSuccess(bodyReader(), element), equalTo(Tab.TAB)); } @Test public void noBreakHyphenElementIsReadAsNonBreakingHyphenCharacter() { XmlElement element = element("w:noBreakHyphen"); assertThat( readSuccess(bodyReader(), element), isTextElement("\u2011") ); } @Test public void softHyphenElementIsReadAsSoftHyphenCharacter() { XmlElement element = element("w:softHyphen"); assertThat( readSuccess(bodyReader(), element), isTextElement("\u00ad") ); } @Test public void symWithSupportedFontAndSupportedCodePointInAsciiRangeIsConvertedToText() { XmlElement element = element("w:sym", map("w:font", "Wingdings", "w:char", "28")); DocumentElement result = readSuccess(bodyReader(), element); assertThat( result, isTextElement("\uD83D\uDD7F") ); } @Test public void symWithSupportedFontAndSupportedCodePointInPrivateUseAreaIsConvertedToText() { XmlElement element = element("w:sym", map("w:font", "Wingdings", "w:char", "F028")); DocumentElement result = readSuccess(bodyReader(), element); assertThat( result, isTextElement("\uD83D\uDD7F") ); } @Test public void symWithUnsupportedFontAndCodePointProducesEmptyResultWithWarning() { XmlElement element = element("w:sym", map("w:font", "Dingwings", "w:char", "28")); InternalResult<List<DocumentElement>> result = readAll(bodyReader(), element); assertThat(result, isInternalResult( equalTo(list()), list("A w:sym element with an unsupported character was ignored: char 28 in font Dingwings") )); } @Test public void brWithoutExplicitTypeIsReadAsLineBreak() { XmlElement element = element("w:br"); assertThat( readSuccess(bodyReader(), element), equalTo(Break.LINE_BREAK)); } @Test public void brWithTextWrappingTypeIsReadAsLineBreak() { XmlElement element = element("w:br", map("w:type", "textWrapping")); assertThat( readSuccess(bodyReader(), element), equalTo(Break.LINE_BREAK) ); } @Test public void brWithPageTypeIsReadAsPageBreak() { XmlElement element = element("w:br", map("w:type", "page")); assertThat( readSuccess(bodyReader(), element), equalTo(Break.PAGE_BREAK) ); } @Test public void brWithColumnTypeIsReadAsColumnBreak() { XmlElement element = element("w:br", map("w:type", "column")); assertThat( readSuccess(bodyReader(), element), equalTo(Break.COLUMN_BREAK) ); } @Test public void warningOnBreaksThatArentRecognised() { XmlElement element = element("w:br", map("w:type", "unknownBreakType")); assertThat( readAll(bodyReader(), element), isInternalResult(equalTo(list()), list("Unsupported break type: unknownBreakType"))); } @Test public void canReadTableElements() { XmlElement element = element("w:tbl", list( element("w:tr", list( element("w:tc", list( element("w:p"))))))); assertThat( readSuccess(bodyReader(), element), isTable(hasChildren( deepEquals(tableRow(list( new TableCell(1, 1, list( paragraph() )) ))) )) ); } @Test public void tableHasNoStyleIfItHasNoProperties() { XmlElement element = element("w:tbl"); assertThat( readSuccess(bodyReader(), element), hasStyle(Optional.empty()) ); } @Test public void whenTableHasStyleIdInStylesThenStyleNameIsReadFromStyles() { XmlElement element = element("w:tbl", list( element("w:tblPr", list( element("w:tblStyle", map("w:val", "TableNormal")) )) )); Style style = new Style("TableNormal", Optional.of("Normal Table")); Styles styles = new Styles( map(), map(), map("TableNormal", style), map() ); assertThat( readSuccess(bodyReader(styles), element), hasStyle(Optional.of(style)) ); } @Test public void warningIsEmittedWhenTableStyleCannotBeFound() { XmlElement element = element("w:tbl", list( element("w:tblPr", list( element("w:tblStyle", map("w:val", "TableNormal")) )) )); assertThat( read(bodyReader(), element), isInternalResult( hasStyle(Optional.of(new Style("TableNormal", Optional.empty()))), list("Table style with ID TableNormal was referenced but not defined in the document") ) ); } @Test public void tblHeaderMarksTableRowAsHeader() { XmlElement element = element("w:tbl", list( element("w:tr", list( element("w:trPr", list( element("w:tblHeader") )) )), element("w:tr") )); assertThat( readSuccess(bodyReader(), element), isTable(hasChildren( isRow(isHeader(true)), isRow(isHeader(false)) )) ); } @Test public void gridspanIsReadAsColspanForTableCell() { XmlElement element = element("w:tbl", list( element("w:tr", list( element("w:tc", list( element("w:tcPr", list( element("w:gridSpan", map("w:val", "2")) )), element("w:p"))))))); assertThat( readSuccess(bodyReader(), element), deepEquals(table(list( tableRow(list( new TableCell(1, 2, list( paragraph() )) )) ))) ); } @Test public void vmergeIsReadAsRowspanForTableCell() { XmlElement element = element("w:tbl", list( wTr(wTc()), wTr(wTc(wTcPr(wVmerge("restart")))), wTr(wTc(wTcPr(wVmerge("continue")))), wTr(wTc(wTcPr(wVmerge("continue")))), wTr(wTc()) )); assertThat( readSuccess(bodyReader(), element), deepEquals(table(list( tableRow(list(new TableCell(1, 1, list()))), tableRow(list(new TableCell(3, 1, list()))), tableRow(list()), tableRow(list()), tableRow(list(new TableCell(1, 1, list()))) ))) ); } @Test public void vmergeWithoutValIsTreatedAsContinue() { XmlElement element = element("w:tbl", list( wTr(wTc(wTcPr(wVmerge("restart")))), wTr(wTc(wTcPr(element("w:vMerge")))) )); assertThat( readSuccess(bodyReader(), element), deepEquals(table(list( tableRow(list(new TableCell(2, 1, list()))), tableRow(list()) ))) ); } @Test public void vmergeAccountsForCellsSpanningColumns() { XmlElement element = element("w:tbl", list( wTr(wTc(), wTc(), wTc(wTcPr(wVmerge("restart")))), wTr(wTc(wTcPr(wGridspan("2"))), wTc(wTcPr(wVmerge("continue")))), wTr(wTc(), wTc(), wTc(wTcPr(wVmerge("continue")))), wTr(wTc(), wTc(), wTc()) )); assertThat( readSuccess(bodyReader(), element), deepEquals(table(list( tableRow(list(new TableCell(1, 1, list()), new TableCell(1, 1, list()), new TableCell(3, 1, list()))), tableRow(list(new TableCell(1, 2, list()))), tableRow(list(new TableCell(1, 1, list()), new TableCell(1, 1, list()))), tableRow(list(new TableCell(1, 1, list()), new TableCell(1, 1, list()), new TableCell(1, 1, list()))) ))) ); } @Test public void noVerticalCellMergingIfMergedCellsDoNotLineUp() { XmlElement element = element("w:tbl", list( wTr(wTc(wTcPr(wGridspan("2"))), wTc(wTcPr(wVmerge("restart")))), wTr(wTc(), wTc(wTcPr(wVmerge("continue")))) )); assertThat( readSuccess(bodyReader(), element), deepEquals(table(list( tableRow(list(new TableCell(1, 2, list()), new TableCell(1, 1, list()))), tableRow(list(new TableCell(1, 1, list()), new TableCell(1, 1, list()))) ))) ); } @Test public void warningIfNonRowInTable() { XmlElement element = element("w:tbl", list( element("w:p") )); assertThat( read(bodyReader(), element), isInternalResult( deepEquals(table(list(paragraph()))), list("unexpected non-row element in table, cell merging may be incorrect") ) ); } @Test public void warningIfNonCellInTableRow() { XmlElement element = element("w:tbl", list( wTr(element("w:p")) )); assertThat( read(bodyReader(), element), isInternalResult( deepEquals(table(list(tableRow(list(paragraph()))))), list("unexpected non-cell element in table row, cell merging may be incorrect") ) ); } @Test public void hyperlinkIsReadAsExternalHyperlinkIfItHasARelationshipId() { Relationships relationships = new Relationships(list( hyperlinkRelationship("r42", "http://example.com") )); XmlElement element = element("w:hyperlink", map("r:id", "r42"), list(runXml(list()))); assertThat( readSuccess(bodyReader(relationships), element), isHyperlink( hasHref("http://example.com"), hasNoAnchor(), hasChildren(isRun(hasChildren())) ) ); } @Test public void hyperlinkIsReadAsExternalHyperlinkIfItHasARelationshipIdAndAnAnchor() { Relationships relationships = new Relationships(list( hyperlinkRelationship("r42", "http://example.com/") )); XmlElement element = element("w:hyperlink", map("r:id", "r42", "w:anchor", "fragment"), list(runXml(list()))); assertThat( readSuccess(bodyReader(relationships), element), isHyperlink(hasHref("http://example.com/#fragment")) ); } @Test public void hyperlinkExistingFragmentIsReplacedWhenAnchorIsSetOnExternalLink() { Relationships relationships = new Relationships(list( hyperlinkRelationship("r42", "http://example.com/#previous") )); XmlElement element = element("w:hyperlink", map("r:id", "r42", "w:anchor", "fragment"), list(runXml(list()))); assertThat( readSuccess(bodyReader(relationships), element), isHyperlink(hasHref("http://example.com/#fragment")) ); } @Test public void hyperlinkIsReadAsInternalHyperlinkIfItHasAnAnchorAttribute() { XmlElement element = element("w:hyperlink", map("w:anchor", "start"), list(runXml(list()))); assertThat( readSuccess(bodyReader(), element), isHyperlink( hasAnchor("start"), hasNoHref() ) ); } @Test public void hyperlinkIsIgnoredIfItDoesNotHaveARelationshipIdNorAnchor() { XmlElement element = element("w:hyperlink", list(runXml(list()))); assertThat( readSuccess(bodyReader(), element), deepEquals(run(withChildren()))); } @Test public void hyperlinkTargetFrameIsRead() { XmlElement element = element("w:hyperlink", map( "w:anchor", "start", "w:tgtFrame", "_blank" )); assertThat( readSuccess(bodyReader(), element), isHyperlink(hasTargetFrame("_blank")) ); } @Test public void hyperlinkEmptyTargetFrameIsIgnored() { XmlElement element = element("w:hyperlink", map( "w:anchor", "start", "w:tgtFrame", "" )); assertThat( readSuccess(bodyReader(), element), isHyperlink(hasNoTargetFrame()) ); } @Test public void goBackBookmarkIsIgnored() { XmlElement element = element("w:bookmarkStart", map("w:name", "_GoBack")); assertThat( readAll(bodyReader(), element), isInternalResult(equalTo(list()), list())); } @Test public void bookmarkStartIsReadIfNameIsNotGoBack() { XmlElement element = element("w:bookmarkStart", map("w:name", "start")); assertThat( readSuccess(bodyReader(), element), deepEquals(new Bookmark("start"))); } @Test public void footnoteReferenceHasIdRead() { XmlElement element = element("w:footnoteReference", map("w:id", "4")); assertThat( readSuccess(bodyReader(), element), deepEquals(footnoteReference("4"))); } @Test public void endnoteReferenceHasIdRead() { XmlElement element = element("w:endnoteReference", map("w:id", "4")); assertThat( readSuccess(bodyReader(), element), deepEquals(endnoteReference("4"))); } @Test public void commentReferenceHasIdRead() { XmlElement element = element("w:commentReference", map("w:id", "4")); assertThat( readSuccess(bodyReader(), element), deepEquals(new CommentReference("4"))); } @Test public void textBoxesHaveContentAppendedAfterContainingParagraph() { XmlElement textBox = element("w:pict", list( element("v:shape", list( element("v:textbox", list( element("w:txbxContent", list( paragraphXml(list( runXml(list(textXml("[textbox-content]"))))))))))))); XmlElement paragraph = paragraphXml(list( runXml(list(textXml("[paragragh start]"))), runXml(list(textBox, textXml("[paragragh end]"))))); List<DocumentElement> expected = list( paragraph(withChildren( run(withChildren( new Text("[paragragh start]"))), run(withChildren( new Text("[paragragh end]"))))), paragraph(withChildren( run(withChildren( new Text("[textbox-content]")))))); assertThat( readAll(bodyReader(), paragraph), isInternalResult(deepEquals(expected), list())); } private static final String IMAGE_BYTES = "Not an image at all!"; private static final String IMAGE_RELATIONSHIP_ID = "rId5"; @Test public void canReadImagedataElementsWithIdAttribute() throws IOException { assertCanReadEmbeddedImage(image -> element("v:imagedata", map("r:id", image.relationshipId, "o:title", image.altText))); } @Test public void whenImagedataElementHasNoRelationshipIdThenItIsIgnoredWithWarning() throws IOException { XmlElement element = element("v:imagedata"); assertThat( readAll(bodyReader(), element), isInternalResult(equalTo(list()), list("A v:imagedata element without a relationship ID was ignored"))); } @Test public void canReadInlinePictures() throws IOException { assertCanReadEmbeddedImage(image -> inlineImageXml(embeddedBlipXml(image.relationshipId), image.altText)); } @Test public void altTextTitleIsUsedIfAltTextDescriptionIsBlank() throws IOException { XmlElement element = inlineImageXml( embeddedBlipXml(IMAGE_RELATIONSHIP_ID), Optional.of(" "), Optional.of("It's a hat") ); Image image = readEmbeddedImage(element); assertThat(image, hasProperty("altText", deepEquals(Optional.of("It's a hat")))); } @Test public void altTextTitleIsUsedIfAltTextDescriptionIsMissing() throws IOException { XmlElement element = inlineImageXml( embeddedBlipXml(IMAGE_RELATIONSHIP_ID), Optional.empty(), Optional.of("It's a hat") ); Image image = readEmbeddedImage(element); assertThat(image, hasProperty("altText", deepEquals(Optional.of("It's a hat")))); } @Test public void altTextDescriptionIsPreferredToAltTextTitle() throws IOException { XmlElement element = inlineImageXml( embeddedBlipXml(IMAGE_RELATIONSHIP_ID), Optional.of("It's a hat"), Optional.of("hat") ); Image image = readEmbeddedImage(element); assertThat(image, hasProperty("altText", deepEquals(Optional.of("It's a hat")))); } @Test public void canReadAnchoredPictures() throws IOException { assertCanReadEmbeddedImage(image -> anchoredImageXml(embeddedBlipXml(image.relationshipId), image.altText)); } private void assertCanReadEmbeddedImage(Function<EmbeddedImage, XmlElement> generateXml) throws IOException { XmlElement element = generateXml.apply(new EmbeddedImage(IMAGE_RELATIONSHIP_ID, "It's a hat")); Image image = readEmbeddedImage(element); assertThat(image, allOf( hasProperty("altText", deepEquals(Optional.of("It's a hat"))), hasProperty("contentType", deepEquals(Optional.of("image/png"))))); assertThat( toString(image.open()), equalTo(IMAGE_BYTES)); } private Image readEmbeddedImage(XmlElement element) { Relationships relationships = new Relationships(list( imageRelationship(IMAGE_RELATIONSHIP_ID, "media/hat.png") )); Archive file = InMemoryArchive.fromStrings(map("word/media/hat.png", IMAGE_BYTES)); return (Image) readSuccess( BodyXmlReaderMakers.bodyReader(relationships, file), element); } private static String toString(InputStream stream) throws IOException { return new String(toByteArray(stream), StandardCharsets.UTF_8); } private class EmbeddedImage { private final String relationshipId; private final String altText; public EmbeddedImage(String relationshipId, String altText) { this.relationshipId = relationshipId; this.altText = altText; } } @Test public void warningIfImageTypeIsUnsupportedByWebBrowsers() { XmlElement element = inlineImageXml(embeddedBlipXml(IMAGE_RELATIONSHIP_ID), ""); Relationships relationships = new Relationships(list( imageRelationship(IMAGE_RELATIONSHIP_ID, "media/hat.emf") )); Archive file = InMemoryArchive.fromStrings(map("word/media/hat.emf", IMAGE_BYTES)); ContentTypes contentTypes = new ContentTypes(map("emf", "image/x-emf"), map()); InternalResult<?> result = read( bodyReader(relationships, file, contentTypes), element); assertThat( result, hasWarnings(list("Image of type image/x-emf is unlikely to display in web browsers"))); } @Test public void canReadLinkedPictures() throws IOException { XmlElement element = inlineImageXml(linkedBlipXml(IMAGE_RELATIONSHIP_ID), ""); Relationships relationships = new Relationships(list( imageRelationship(IMAGE_RELATIONSHIP_ID, "file:///media/hat.png") )); Image image = (Image) readSuccess( bodyReader(relationships, new InMemoryFileReader(map("file:///media/hat.png", IMAGE_BYTES))), element); assertThat( toString(image.open()), equalTo(IMAGE_BYTES)); } private XmlElement inlineImageXml(XmlElement blip, String description) { return inlineImageXml(blip, Optional.of(description), Optional.empty()); } private XmlElement inlineImageXml(XmlElement blip, Optional<String> description, Optional<String> title) { return element("w:drawing", list( element("wp:inline", imageXml(blip, description, title)))); } private XmlElement anchoredImageXml(XmlElement blip, String description) { return element("w:drawing", list( element("wp:anchor", imageXml(blip, Optional.of(description), Optional.empty())))); } private List<XmlNode> imageXml(XmlElement blip, Optional<String> description, Optional<String> title) { Map<String, String> properties = new HashMap<>(); description.ifPresent(value -> properties.put("descr", value)); title.ifPresent(value -> properties.put("title", value)); return list( element("wp:docPr", properties), element("a:graphic", list( element("a:graphicData", list( element("pic:pic", list( element("pic:blipFill", list(blip))))))))); } private XmlElement embeddedBlipXml(String relationshipId) { return blipXml(map("r:embed", relationshipId)); } private XmlElement linkedBlipXml(String relationshipId) { return blipXml(map("r:link", relationshipId)); } private XmlElement blipXml(Map<String, String> attributes) { return element("a:blip", attributes); } @Test public void sdtIsReadUsingSdtContent() throws IOException { XmlElement element = element("w:sdt", list(element("w:sdtContent", list(textXml("Blackdown"))))); assertThat( readAll(bodyReader(), element), isInternalSuccess(deepEquals(list(text("Blackdown"))))); } @Test public void appropriateElementsHaveTheirChildrenReadNormally() { assertChildrenAreReadNormally("w:ins"); assertChildrenAreReadNormally("w:object"); assertChildrenAreReadNormally("w:smartTag"); assertChildrenAreReadNormally("w:drawing"); assertChildrenAreReadNormally("v:group"); assertChildrenAreReadNormally("v:rect"); assertChildrenAreReadNormally("v:roundrect"); assertChildrenAreReadNormally("v:shape"); assertChildrenAreReadNormally("v:textbox"); assertChildrenAreReadNormally("w:txbxContent"); } private void assertChildrenAreReadNormally(String name) { XmlElement element = element(name, list(paragraphXml())); assertThat( readSuccess(bodyReader(), element), deepEquals(paragraph())); } @Test public void ignoredElementsAreIgnoredWithoutWarning() { assertIsIgnored("office-word:wrap"); assertIsIgnored("v:shadow"); assertIsIgnored("v:shapetype"); assertIsIgnored("w:bookmarkEnd"); assertIsIgnored("w:sectPr"); assertIsIgnored("w:proofErr"); assertIsIgnored("w:lastRenderedPageBreak"); assertIsIgnored("w:commentRangeStart"); assertIsIgnored("w:commentRangeEnd"); assertIsIgnored("w:del"); assertIsIgnored("w:footnoteRef"); assertIsIgnored("w:endnoteRef"); assertIsIgnored("w:annotationRef"); assertIsIgnored("w:pPr"); assertIsIgnored("w:rPr"); assertIsIgnored("w:tblPr"); assertIsIgnored("w:tblGrid"); assertIsIgnored("w:tcPr"); } private void assertIsIgnored(String name) { XmlElement element = element(name, list(paragraphXml())); assertThat( readAll(bodyReader(), element), isInternalResult(equalTo(list()), list())); } @Test public void unrecognisedElementsAreIgnoredWithWarning() { XmlElement element = element("w:huh"); assertThat( readAll(bodyReader(), element), isInternalResult(equalTo(list()), list("An unrecognised element was ignored: w:huh"))); } @Test public void textNodesAreIgnoredWhenReadingChildren() { XmlElement element = runXml(list(XmlNodes.text("[text]"))); assertThat( readSuccess(bodyReader(), element), deepEquals(run(withChildren()))); } private static DocumentElement readSuccess(BodyXmlReader reader, XmlElement element) { InternalResult<DocumentElement> result = read(reader, element); assertThat(result.getWarnings(), emptyIterable()); return result.getValue(); } private static InternalResult<DocumentElement> read(BodyXmlReader reader, XmlElement element) { InternalResult<List<DocumentElement>> result = readAll(reader, element); assertThat(result.getValue(), Matchers.hasSize(1)); return result.map(elements -> elements.get(0)); } private static InternalResult<List<DocumentElement>> readAll(BodyXmlReader reader, XmlElement element) { return reader.readElement(element).toResult(); } private XmlElement paragraphXml() { return paragraphXml(list()); } private static XmlElement paragraphXml(List<XmlNode> children) { return element("w:p", children); } private static XmlElement runXml(String text) { return runXml(list(textXml(text))); } private static XmlElement runXml(List<XmlNode> children) { return element("w:r", children); } private static XmlElement runXmlWithProperties(XmlNode... children) { return element("w:r", list(element("w:rPr", asList(children)))); } private static XmlElement textXml(String value) { return element("w:t", list(XmlNodes.text(value))); } private Matcher<? super DocumentElement> hasStyle(Optional<Style> expected) { return hasProperty("style", deepEquals(expected)); } private Matcher<? super DocumentElement> hasNumbering(NumberingLevel expected) { return hasNumbering(Optional.of(expected)); } private Matcher<? super DocumentElement> hasNumbering(Optional<NumberingLevel> expected) { return hasProperty("numbering", deepEquals(expected)); } private Matcher<? super DocumentElement> hasIndent(Matcher<ParagraphIndent> expected) { return hasProperty("indent", expected); } private Matcher<ParagraphIndent> hasIndentStart(Optional<String> value) { return hasProperty("start", equalTo(value)); } private Matcher<ParagraphIndent> hasIndentEnd(Optional<String> value) { return hasProperty("end", equalTo(value)); } private Matcher<ParagraphIndent> hasIndentFirstLine(Optional<String> value) { return hasProperty("firstLine", equalTo(value)); } private Matcher<ParagraphIndent> hasIndentHanging(Optional<String> value) { return hasProperty("hanging", equalTo(value)); } private static Text text(String value) { return new Text(value); } private static Relationship hyperlinkRelationship(String relationshipId, String target) { return new Relationship(relationshipId, target, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink"); } private static Relationship imageRelationship(String relationshipId, String target) { return new Relationship(relationshipId, target, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image"); } private static Numbering numberingMap(Map<String, Map<String, Numbering.AbstractNumLevel>> numbering) { return new Numbering( numbering.entrySet().stream().collect(Collectors.toMap( entry -> entry.getKey(), entry -> new Numbering.AbstractNum(entry.getValue(), Optional.empty()) )), numbering.keySet().stream().collect(Collectors.toMap( numId -> numId, numId -> new Numbering.Num(Optional.of(numId)) )), Styles.EMPTY ); } }
Explicitly set expected href in tests
src/test/java/org/zwobble/mammoth/tests/docx/BodyXmlTests.java
Explicitly set expected href in tests
Java
bsd-2-clause
8317959a7e1c2bb25bac73c9a58c7dd04db7a061
0
girtel/Net2Plan,girtel/Net2Plan,girtel/Net2Plan
/******************************************************************************* * Copyright (c) 2016 Pablo Pavon-Marino. * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v2.1 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * Contributors: * Pablo Pavon-Marino - Jose-Luis Izquierdo-Zaragoza, up to version 0.3.1 * Pablo Pavon-Marino - from version 0.4.0 onwards ******************************************************************************/ package com.net2plan.interfaces.networkDesign; import java.awt.geom.Point2D; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import javax.xml.stream.FactoryConfigurationError; import javax.xml.stream.XMLStreamException; import javax.xml.stream.events.XMLEvent; import org.apache.commons.lang3.mutable.MutableLong; import org.codehaus.stax2.XMLInputFactory2; import org.codehaus.stax2.XMLOutputFactory2; import org.codehaus.stax2.XMLStreamReader2; import org.codehaus.stax2.XMLStreamWriter2; import org.jgrapht.experimental.dag.DirectedAcyclicGraph; import com.net2plan.internal.AttributeMap; import com.net2plan.internal.ErrorHandling; import com.net2plan.internal.Version; import com.net2plan.internal.XMLUtils; import com.net2plan.libraries.GraphUtils; import com.net2plan.libraries.GraphUtils.ClosedCycleRoutingException; import com.net2plan.libraries.SRGUtils; import com.net2plan.utils.CollectionUtils; import com.net2plan.utils.Constants.RoutingCycleType; import com.net2plan.utils.Constants.RoutingType; import com.net2plan.utils.DoubleUtils; import com.net2plan.utils.Pair; import com.net2plan.utils.StringUtils; import cern.colt.function.tdouble.DoubleFunction; import cern.colt.list.tdouble.DoubleArrayList; import cern.colt.list.tint.IntArrayList; import cern.colt.matrix.tdouble.DoubleFactory1D; import cern.colt.matrix.tdouble.DoubleFactory2D; import cern.colt.matrix.tdouble.DoubleMatrix1D; import cern.colt.matrix.tdouble.DoubleMatrix2D; /** * <p>Class defining a complete multi-layer network structure. Layers may * contain links, demands, routes and protection segments or forwarding rules, * while nodes and SRGs are defined with a network-wide scope, that is, they * appear in all layers. To simplify handling of single-layer designs, methods that may refer to * layer-specific elements have an optiona input parameter of type {@link com.net2plan.interfaces.networkDesign.NetworkLayer NetworkLayer}. * In case of not using this optional parameter, the action * will be applied to the default layer (by default it is first defined layer), * which can be modified using the {@link #setNetworkLayerDefault(NetworkLayer)} setNetworkLayerDefault())} * method.</p> * * <p>Internal representation of the {@code NetPlan} object is based on:</p> * <ul> * <li>{@link com.net2plan.interfaces.networkDesign.NetworkLayer NetworkLayer} objects.</li> * <li>{@link com.net2plan.interfaces.networkDesign.Node Node} objects.</li> * <li>{@link com.net2plan.interfaces.networkDesign.Link Link} objects.</li> * <li>{@link com.net2plan.interfaces.networkDesign.Route Route} objects (depending on the selected {@link com.net2plan.utils.Constants.RoutingCycleType Routing Type}.</li> * <li>{@link com.net2plan.interfaces.networkDesign.Demand Unicast} or {@link com.net2plan.interfaces.networkDesign.MulticastDemand Multicast} demand objects. </li> * <li>{@link com.net2plan.interfaces.networkDesign.ProtectionSegment Protection Segment} objects.</li> * <li>{@link com.net2plan.interfaces.networkDesign.SharedRiskGroup Shared Risk Group} objects</li> * </ul> * * <p>Each element has a unique identifier (represented as {@code long}) assigned the moment they are created, and two elements * (irregardless of their type) cannot share this identifier. This id is incremental (but not necessarily consecutive) and perpetual (i.e after removing an element identifiers are no renumbered).</p> * <p>Also, elements have an index number that identify them among their own type (nodes, links, etc.). Indexes are renumbered when an element is removed and are zero base, that is the first * element of its type is always 0 and the last is N-1 (where N is the total number of elements of the same type).</p> * * <p>An instance of a NetPlan object can be set as unmodifiable through the * {@link NetPlan#setModifiableState(boolean)} setModifiableState())} method. The instance will work * transparently as {@code NetPlan} object unless you try to change it. Calling * any method that can potentially change the network (e.g. add/set/remove methods) * throws an {@code UnsupportedOperationException}.</p> * * @author Pablo Pavon-Marino, Jose-Luis Izquierdo-Zaragoza * @since 0.2.0 */ public class NetPlan extends NetworkElement { final static String TEMPLATE_CROSS_LAYER_UNITS_NOT_MATCHING = "Link capacity units at layer %d (%s) do not match demand traffic units at layer %d (%s)"; final static String TEMPLATE_NO_MORE_NETWORK_ELEMENTS_ALLOWED = "Maximum number of identifiers in the design reached"; final static String TEMPLATE_NO_MORE_NODES_ALLOWED = "Maximum node identifier reached"; final static String TEMPLATE_NO_MORE_LINKS_ALLOWED = "Maximum link identifier for layer %d reached"; final static String TEMPLATE_NO_MORE_DEMANDS_ALLOWED = "Maximum demand identifier for layer %d reached"; final static String TEMPLATE_NO_MORE_MULTICASTDEMANDS_ALLOWED = "Maximum multicast demand identifier for layer %d reached"; final static String TEMPLATE_NO_MORE_ROUTES_ALLOWED = "Maximum route identifier for layer %d reached"; final static String TEMPLATE_NO_MORE_MULTICASTTREES_ALLOWED = "Maximum multicast tree identifier for layer %d reached"; final static String TEMPLATE_NO_MORE_SEGMENTS_ALLOWED = "Maximum protection segment identifier for layer %d reached"; final static String TEMPLATE_NO_MORE_SRGS_ALLOWED = "Maximum SRG identifier reached"; final static String TEMPLATE_NOT_ACTIVE_LAYER = "Layer %d is not in the network"; final static String TEMPLATE_NOT_ACTIVE_NODE = "Node %d is not in the network"; final static String TEMPLATE_NOT_ACTIVE_LINK = "Link %d is not in the network"; final static String TEMPLATE_NOT_ACTIVE_DEMAND = "Demand %d is not in the network"; final static String TEMPLATE_NOT_ACTIVE_MULTICASTDEMAND = "Multicast demand %d is not in the network"; final static String TEMPLATE_NOT_ACTIVE_ROUTE = "Route %d is not in the network"; final static String TEMPLATE_NOT_ACTIVE_MULTICASTTREE = "Multicast tree %d is not in the network"; final static String TEMPLATE_NOT_ACTIVE_FORWARDING_RULE = "Forwarding rule (%d, %d) is not in the network"; final static String TEMPLATE_NOT_ACTIVE_SEGMENT = "Protection segment %d is not in the network"; final static String TEMPLATE_NOT_ACTIVE_SRG = "SRG %d is not in the network"; final static String TEMPLATE_DEMAND_NOT_ACTIVE_IN_LAYER = "Demand %d is not in layer %d"; final static String TEMPLATE_LINK_NOT_ACTIVE_IN_LAYER = "Link %d is not in layer %d"; final static String TEMPLATE_ROUTE_NOT_ACTIVE_IN_LAYER = "Route %d is not in layer %d"; final static String TEMPLATE_MULTICASTDEMAND_NOT_ACTIVE_IN_LAYER = "Multicast demand %d is not in layer %d"; final static String TEMPLATE_MULTICASTTREE_NOT_ACTIVE_IN_LAYER = "Multicast tree %d is not in layer %d"; final static String TEMPLATE_PROTECTIONSEGMENT_NOT_ACTIVE_IN_LAYER = "Protection segment %d is not in layer %d"; final static String TEMPLATE_FORWARDINGRULE_NOT_ACTIVE_IN_LAYER = "Forwarding rule %d is not in layer %d"; final static String TEMPLATE_ROUTE_NOT_ALL_LINKS_SAME_LAYER = "Not all of the links of the route belong to the same layer"; final static String TEMPLATE_SEGMENT_NOT_ALL_LINKS_SAME_LAYER = "Not all of the links of the protection segment belong to the same layer"; final static String TEMPLATE_MULTICASTTREE_NOT_ALL_LINKS_SAME_LAYER = "Not all of the links of the multicast tree belong to the same layer"; final static String TEMPLATE_NOT_OF_THE_SAME_LAYER_ROUTE_AND_SEGMENT = "The route %d and the segment %d are of different layers (%d, %d)"; final static String UNMODIFIABLE_EXCEPTION_STRING = "Unmodifiable NetState object - can't be changed"; final static String KEY_STRING_BIDIRECTIONALCOUPLE = "bidirectionalCouple"; RoutingType DEFAULT_ROUTING_TYPE = RoutingType.SOURCE_ROUTING; boolean isModifiable; String networkDescription; String networkName; NetworkLayer defaultLayer; MutableLong nextElementId; ArrayList<NetworkLayer> layers; ArrayList<Node> nodes; ArrayList<SharedRiskGroup> srgs; HashSet<Node> cache_nodesDown; Map<Long,Node> cache_id2NodeMap; Map<Long,NetworkLayer> cache_id2LayerMap; Map<Long,Link> cache_id2LinkMap; Map<Long,Demand> cache_id2DemandMap; Map<Long,MulticastDemand> cache_id2MulticastDemandMap; Map<Long,Route> cache_id2RouteMap; Map<Long,MulticastTree> cache_id2MulticastTreeMap; Map<Long,ProtectionSegment> cache_id2ProtectionSegmentMap; Map<Long,SharedRiskGroup> cache_id2srgMap; DirectedAcyclicGraph<NetworkLayer, DemandLinkMapping> interLayerCoupling; /** * <p>Default constructor. Creates an empty design</p> * * @since 0.4.0 */ public NetPlan() { super (null , 0 , 0 , new AttributeMap()); this.netPlan = this; DEFAULT_ROUTING_TYPE = RoutingType.SOURCE_ROUTING; isModifiable = true; networkDescription = ""; networkName = ""; nextElementId = new MutableLong(1); layers = new ArrayList<NetworkLayer> (); nodes = new ArrayList<Node> (); srgs= new ArrayList<SharedRiskGroup> (); cache_nodesDown = new HashSet<Node> (); this.cache_id2NodeMap = new HashMap <Long,Node> (); this.cache_id2LayerMap = new HashMap <Long,NetworkLayer> (); this.cache_id2srgMap= new HashMap<Long,SharedRiskGroup> (); this.cache_id2LinkMap = new HashMap<Long,Link> (); this.cache_id2DemandMap = new HashMap<Long,Demand> (); this.cache_id2MulticastDemandMap = new HashMap<Long,MulticastDemand> (); this.cache_id2RouteMap = new HashMap<Long,Route> (); this.cache_id2MulticastTreeMap = new HashMap<Long,MulticastTree> (); this.cache_id2ProtectionSegmentMap = new HashMap<Long,ProtectionSegment> (); interLayerCoupling = new DirectedAcyclicGraph<NetworkLayer, DemandLinkMapping>(DemandLinkMapping.class); defaultLayer = addLayer("Layer 0", null, null, null, null); } /********************************************************************************************************/ /********************************************************************************************************/ /********************************* INIT BLOCK ***********************************************************************/ /********************************************************************************************************/ /********************************************************************************************************/ /********************************************************************************************************/ /********************************************************************************************************/ /** * <p>Generates a new network design from a given {@code .n2p} file.</p> * * @param file {@code .n2p} file * @since 0.2.0 */ public NetPlan(File file) { this(); NetPlan np = loadFromFile(file); if (ErrorHandling.isDebugEnabled()) np.checkCachesConsistency(); assignFrom(np); if (ErrorHandling.isDebugEnabled()) this.checkCachesConsistency(); // System.out.println ("End NetPlan(File file): " + netPlan + " ----------- "); } /** * <p>Generates a new network design from an input stream.</p> * * @param inputStream Input stream * @since 0.3.1 */ public NetPlan(InputStream inputStream) { this(); try { XMLInputFactory2 xmlInputFactory = (XMLInputFactory2) XMLInputFactory2.newInstance(); XMLStreamReader2 xmlStreamReader = (XMLStreamReader2) xmlInputFactory.createXMLStreamReader(inputStream); while(xmlStreamReader.hasNext()) { int eventType = xmlStreamReader.next(); switch (eventType) { case XMLEvent.START_ELEMENT: String elementName = xmlStreamReader.getName().toString(); if (!elementName.equals("network")) throw new RuntimeException("Root element must be 'network'"); IReaderNetPlan netPlanFormat; int index = xmlStreamReader.getAttributeIndex(null, "version"); if (index == -1) { System.out.println ("Version 1"); netPlanFormat = new ReaderNetPlan_v1(); } else { int version = xmlStreamReader.getAttributeAsInt(index); switch(version) { case 2: System.out.println ("Version 2"); netPlanFormat = new ReaderNetPlan_v2(); break; case 3: System.out.println ("Version 3"); netPlanFormat = new ReaderNetPlan_v3(); break; case 4: System.out.println ("Version 4"); netPlanFormat = new ReaderNetPlan_v4 (); break; default: throw new Net2PlanException("Wrong version number"); } } netPlanFormat.create(this, xmlStreamReader); if (ErrorHandling.isDebugEnabled()) this.checkCachesConsistency(); return; default: break; } } } catch (Net2PlanException e) { if (ErrorHandling.isDebugEnabled()) ErrorHandling.printStackTrace(e); throw(e); } catch (FactoryConfigurationError | Exception e) { if (ErrorHandling.isDebugEnabled()) ErrorHandling.printStackTrace(e); throw new RuntimeException(e); } throw new Net2PlanException("Not a valid .n2p file"); } /** * <p>Returns the unique ids of the provided network elements.</p> * @param collection Network elements * @return Unique ids of the provided network elements. If the input {@code Collection} is a {@code Set}, the returned collection is a {@code HashSet}. If the input * {@code Collection} is a {@code List}, an {@code ArrayList} is returned}. */ public static Collection<Long> getIds (Collection<? extends NetworkElement> collection) { Collection<Long> res = (collection instanceof Set)? new HashSet<Long> () : new ArrayList<Long> (collection.size ()); for (NetworkElement e : collection) res.add (e.id); return res; } /** * <p>Returns the indexes of the provided network elements. </p> * @param collection Network elements * @return Indexes of the provided network elements. If the input {@code Collection} is a {@code Set}, the returned collection is a {@code HashSet}. If the input * {@code Collection} is a {@code List}, an {@code ArrayList} is returned}. */ public static Collection<Integer> getIndexes (Collection<? extends NetworkElement> collection) { Collection<Integer> res = (collection instanceof Set)? new HashSet<Integer> () : new ArrayList<Integer> (collection.size ()); for (NetworkElement e : collection) res.add (e.index); return res; } /** * <p>Static factory method to get a {@link com.net2plan.interfaces.networkDesign.NetPlan NetPlan} object from a {@code .n2p} file.</p> * @param file Input file * @return A network design */ public static NetPlan loadFromFile(File file) { try { InputStream inputStream = new FileInputStream(file); NetPlan np = new NetPlan(inputStream); if (ErrorHandling.isDebugEnabled()) np.checkCachesConsistency(); return np; } catch(FileNotFoundException e) { throw new Net2PlanException(e.getMessage()); } } /** * <p>Removes the network element contained in the list which has the given index, and shifts the indexes of the rest of the elements accordingly.</p> * @param x Network elements * @param indexToRemove Index to remove */ static void removeNetworkElementAndShiftIndexes (ArrayList<? extends NetworkElement> x , int indexToRemove) { x.remove(indexToRemove); for (int newIndex = indexToRemove ; newIndex < x.size () ; newIndex ++) { x.get(newIndex).index = newIndex; } } /** * <p>Adds new traffic demands froma traffic matrix given as a {@code DoubleMatrix2D} object.</p> * * <p><b>Important: </b>Previous demands will be removed.</p> * <p><b>Important</b>: Self-demands are not allowed.</p> * * @param trafficMatrix Traffix matrix where i-th row is the ingress node, the j-th column the egress node and each entry the offered traffic * @param optionalLayerParameter Network layer to which to add the demands (optional) * @return A list with the newly created demands * @see com.net2plan.interfaces.networkDesign.Demand */ public List<Demand> addDemandsFromTrafficMatrix (DoubleMatrix2D trafficMatrix , NetworkLayer ... optionalLayerParameter) { trafficMatrix = NetPlan.adjustToTolerance(trafficMatrix); checkIsModifiable(); NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); List<Demand> demands = new LinkedList<Demand> (); if ((trafficMatrix.rows () != nodes.size ()) || (trafficMatrix.columns () != nodes.size ())) throw new Net2PlanException ("Wrong matrix size"); for (int n1 = 0 ; n1 < nodes.size () ; n1 ++) for (int n2 = 0 ; n2 < nodes.size () ; n2 ++) if (n1 != n2) demands.add (addDemand (nodes.get(n1) , nodes.get(n2) , trafficMatrix.get(n1,n2) , null , layer)); if (ErrorHandling.isDebugEnabled()) this.checkCachesConsistency(); return demands; } /** * <p>Adds a new traffic demand.</p> * * <p><b>Important</b>: Self-demands are not allowed.</p> * * @param optionalLayerParameter Network layer to which add the demand (optional) * @param ingressNode Ingress node * @param egressNode Egress node * @param offeredTraffic Offered traffic by this demand. It must be greater or equal than zero * @param attributes Map for user-defined attributes ({@code null} means 'no attribute'). Each key represents the attribute name, whereas value represents the attribute value * @return The newly added demand object * @see com.net2plan.interfaces.networkDesign.Demand */ public Demand addDemand(Node ingressNode, Node egressNode, double offeredTraffic, Map<String, String> attributes , NetworkLayer ... optionalLayerParameter) { offeredTraffic = NetPlan.adjustToTolerance(offeredTraffic); checkIsModifiable(); NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); checkInThisNetPlan(ingressNode); checkInThisNetPlan(egressNode); if (ingressNode.equals (egressNode)) throw new Net2PlanException("Self-demands are not allowed"); if (offeredTraffic < 0) throw new Net2PlanException ("Offered traffic must be non-negative"); final long demandId = nextElementId.longValue(); nextElementId.increment(); Demand demand = new Demand (this , demandId , layer.demands.size () , layer , ingressNode , egressNode , offeredTraffic , new AttributeMap (attributes)); cache_id2DemandMap.put (demandId , demand); layer.demands.add (demand); egressNode.cache_nodeIncomingDemands.add (demand); ingressNode.cache_nodeOutgoingDemands.add (demand); if (layer.routingType == RoutingType.HOP_BY_HOP_ROUTING) { layer.forwardingRules_f_de = DoubleFactory2D.sparse.appendRow(layer.forwardingRules_f_de , DoubleFactory1D.sparse.make (layer.links.size ())); layer.forwardingRules_x_de = DoubleFactory2D.sparse.appendRow(layer.forwardingRules_x_de , DoubleFactory1D.sparse.make (layer.links.size ())); } if (ErrorHandling.isDebugEnabled()) this.checkCachesConsistency(); return demand; } /** * <p>Adds two demands, one in each direction,.</p> * * <p><b>Important</b>: Self-demands are not allowed.</p> * * @param ingressNode Identifier of the ingress node * @param egressNode Identifier of the egress node * @param offeredTraffic Offered traffic by this demand. It must be greater or equal than zero * @param attributes Map for user-defined attributes ({@code null} means 'no attribute'). Each key represents the attribute name, whereas value represents the attribute value * @param optionalLayerParameter Network layer to which add the demand (optional) * @see com.net2plan.interfaces.networkDesign.Demand * @see com.net2plan.utils.Pair * @return A pair object with the two newly created demands */ public Pair<Demand, Demand> addDemandBidirectional(Node ingressNode, Node egressNode, double offeredTraffic, Map<String, String> attributes , NetworkLayer ... optionalLayerParameter) { offeredTraffic = NetPlan.adjustToTolerance(offeredTraffic); checkIsModifiable(); NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); checkInThisNetPlan(ingressNode); checkInThisNetPlan(egressNode); if (ingressNode.equals (egressNode)) throw new Net2PlanException("Self-demands are not allowed"); if (offeredTraffic < 0) throw new Net2PlanException ("Offered traffic must be non-negative"); Demand d1 = addDemand (ingressNode, egressNode, offeredTraffic , attributes , layer); Demand d2 = addDemand (egressNode, ingressNode, offeredTraffic , attributes , layer); d1.setAttribute(KEY_STRING_BIDIRECTIONALCOUPLE , "" + d2.id); d2.setAttribute(KEY_STRING_BIDIRECTIONALCOUPLE , "" + d1.id); if (ErrorHandling.isDebugEnabled()) this.checkCachesConsistency(); return Pair.of (d1,d2); } /** * <p>Adds a new layer.</p> * * @param name Layer name ({@code null} means empty) * @param description Layer description ({@code null} means empty) * @param linkCapacityUnitsName Textual description of link capacity units ({@code null} means empty) * @param demandTrafficUnitsName Textual description of demand traffic units ({@code null} means empty) * @param attributes Map for user-defined attributes ({@code null} means 'no attribute'). Each key represents the attribute name, whereas value represents the attribute value * @return The newly created layer object * @see com.net2plan.interfaces.networkDesign.NetworkLayer */ public NetworkLayer addLayer(String name, String description, String linkCapacityUnitsName, String demandTrafficUnitsName, Map<String, String> attributes) { checkIsModifiable(); if (name == null) name = ""; if (description == null) description = ""; if (linkCapacityUnitsName == null) linkCapacityUnitsName = ""; if (demandTrafficUnitsName == null) demandTrafficUnitsName = ""; final long id = nextElementId.longValue(); nextElementId.increment(); NetworkLayer layer = new NetworkLayer (this , id, layers.size() , demandTrafficUnitsName, description, name, linkCapacityUnitsName, new AttributeMap (attributes)); interLayerCoupling.addVertex(layer); cache_id2LayerMap.put (id , layer); layers.add (layer); if (layers.size () == 1) defaultLayer = layer; if (ErrorHandling.isDebugEnabled()) this.checkCachesConsistency(); return layer; } /** * <p>Creates a new layer and adds the links, routes etc. from the input layer. The number of nodes in the two designs must be the same (the unique ids may differ). * Any coupling information in the origin layer is omitted. Links, demands, multicast demands, routes, multicast trees and protecion segments * will have the same index within the layer in the origin and in the copied layers, but may have different unique ids.</p> * @param origin Layer to be copied * @return The newly created layer object * @see com.net2plan.interfaces.networkDesign.NetworkLayer * @see com.net2plan.interfaces.networkDesign.Node */ public NetworkLayer addLayerFrom (NetworkLayer origin) { checkIsModifiable(); checkInThisNetPlan(origin); ArrayList<Node> originNodes = origin.netPlan.nodes; if (originNodes.size () != nodes.size ()) throw new Net2PlanException ("The number of nodes in the origin design and this design must be the same"); NetworkLayer newLayer = addLayer(origin.name, origin.description, origin.linkCapacityUnitsName, origin.demandTrafficUnitsName, origin.getAttributes()); for (Link originLink : origin.links) this.addLink(nodes.get(originLink.originNode.index) , nodes.get(originLink.destinationNode.index) , originLink.capacity , originLink.lengthInKm , originLink.propagationSpeedInKmPerSecond , originLink.attributes , newLayer); for (Demand originDemand : origin.demands) this.addDemand(nodes.get(originDemand.ingressNode.index) , nodes.get(originDemand.egressNode.index) , originDemand.offeredTraffic , originDemand.attributes , newLayer); for (MulticastDemand originDemand : origin.multicastDemands) { Set<Node> newEgressNodes = new HashSet<Node> (); for (Node originEgress : originDemand.egressNodes) newEgressNodes.add (nodes.get(originEgress.index)); this.addMulticastDemand(nodes.get(originDemand.ingressNode.index) , newEgressNodes , originDemand.offeredTraffic , originDemand.attributes , newLayer); } for (ProtectionSegment originSegment: origin.protectionSegments) { List<Link> newSeqLinks = new LinkedList<Link> (); for (Link originLink : originSegment.seqLinks) newSeqLinks.add (newLayer.links.get (originLink.index)); this.addProtectionSegment(newSeqLinks , originSegment.capacity , originSegment.attributes); } for (Route originRoute : origin.routes) { List<Link> newSeqLinksRealPath = new LinkedList<Link> (); for (Link originLink : originRoute.seqLinksRealPath) newSeqLinksRealPath.add (newLayer.links.get (originLink.index)); Route newRoute = this.addRoute(newLayer.demands.get(originRoute.demand.index) , originRoute.carriedTraffic , originRoute.occupiedLinkCapacity , newSeqLinksRealPath , originRoute.attributes); List<Link> newSeqLinksAndProtectionSegment = new LinkedList<Link> (); for (Link originLink : originRoute.seqLinksAndProtectionSegments) if (originLink instanceof ProtectionSegment) newSeqLinksAndProtectionSegment.add (newLayer.protectionSegments.get (originLink.index)); else newSeqLinksAndProtectionSegment.add (newLayer.links.get (originLink.index)); newRoute.setSeqLinksAndProtectionSegments(newSeqLinksAndProtectionSegment); } for (MulticastTree originTree: origin.multicastTrees) { Set<Link> newSetLinks = new HashSet<Link> (); for (Link originLink : originTree.linkSet) newSetLinks.add (newLayer.links.get (originLink.index)); this.addMulticastTree(newLayer.multicastDemands.get(originTree.demand.index) , originTree.carriedTraffic , originTree.occupiedLinkCapacity , newSetLinks , originTree.attributes); } if (ErrorHandling.isDebugEnabled()) this.checkCachesConsistency(); return newLayer; } /** * <p>Adds a new link.</p> * * <p><b>Important</b>: Self-links are not allowed.</p> * * @param originNode Link origin node * @param destinationNode Link destination node * @param capacity Link capacity. It must be greather or equal to zero * @param lengthInKm Link length. It must be greater or equal than zero. Physical distance between node pais can be otainer through the {@link #getNodePairEuclideanDistance(Node, Node) getNodePairEuclideanDistance} * (for Euclidean distance) or {@link #getNodePairHaversineDistanceInKm(Node, Node) getNodePairHaversineDistanceInKm} (for airlinea distance) methods. * @param propagationSpeedInKmPerSecond Link propagation speed in km/s. It must be greater than zero ({@code Double.MAX_VALUE} means no propagation delay, a non-positive value is changed into * 200000 km/seg, a typical speed of light in the wires) * @param attributes Map for user-defined attributes ({@code null} means 'no attribute'). Each key represents the attribute name, whereas value represents the attribute value * @param optionalLayerParameter Network layer to which add the link (optional) * @return The newly created link object * @see com.net2plan.interfaces.networkDesign.Link * @see com.net2plan.interfaces.networkDesign.Node */ public Link addLink(Node originNode, Node destinationNode , double capacity, double lengthInKm, double propagationSpeedInKmPerSecond, Map<String, String> attributes , NetworkLayer ... optionalLayerParameter) { capacity = NetPlan.adjustToTolerance(capacity); checkIsModifiable(); NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); checkInThisNetPlan(originNode); checkInThisNetPlan(destinationNode); if (originNode.equals (destinationNode)) throw new Net2PlanException("Self-links are not allowed"); if (capacity < 0) throw new Net2PlanException ("Link capacity must be non-negative"); if (lengthInKm < 0) throw new Net2PlanException ("Link length must be non-negative"); if (propagationSpeedInKmPerSecond <= 0) throw new Net2PlanException ("Propagation speed must be positive"); final long linkId = nextElementId.longValue(); nextElementId.increment(); Link link = new Link (this, linkId , layer.links.size (), layer , originNode, destinationNode , lengthInKm , propagationSpeedInKmPerSecond , capacity , new AttributeMap (attributes)); cache_id2LinkMap.put (linkId , link); layer.links.add (link); originNode.cache_nodeOutgoingLinks.add (link); destinationNode.cache_nodeIncomingLinks.add (link); if (layer.routingType == RoutingType.HOP_BY_HOP_ROUTING) { layer.forwardingRules_f_de = DoubleFactory2D.sparse.appendColumn(layer.forwardingRules_f_de , DoubleFactory1D.sparse.make (layer.demands.size ())); layer.forwardingRules_x_de = DoubleFactory2D.sparse.appendColumn(layer.forwardingRules_x_de , DoubleFactory1D.sparse.make (layer.demands.size ())); layer.forwardingRules_Aout_ne = DoubleFactory2D.sparse.appendColumn(layer.forwardingRules_Aout_ne , DoubleFactory1D.sparse.make (netPlan.nodes.size ())); layer.forwardingRules_Ain_ne = DoubleFactory2D.sparse.appendColumn(layer.forwardingRules_Ain_ne , DoubleFactory1D.sparse.make (netPlan.nodes.size ())); layer.forwardingRules_Aout_ne.set(originNode.index, layer.forwardingRules_Aout_ne.columns()-1, 1.0); layer.forwardingRules_Ain_ne.set(destinationNode.index, layer.forwardingRules_Ain_ne.columns()-1, 1.0); } if (ErrorHandling.isDebugEnabled()) this.checkCachesConsistency(); return link; } /** * <p>Adds two links, one in each direction.</p> * <p><b>Important</b>: Self-links are not allowed.</p> * * @param originNode Link origin node * @param destinationNode Link destination node * @param capacity Link capacity. It must be greather or equal to zero * @param lengthInKm Link length. It must be greater or equal than zero. Physical distance between node pais can be otainer through the {@link #getNodePairEuclideanDistance(Node, Node) getNodePairEuclideanDistance} * (for Euclidean distance) or {@link #getNodePairHaversineDistanceInKm(Node, Node) getNodePairHaversineDistanceInKm} (for airlinea distance) methods. * @param propagationSpeedInKmPerSecond Link propagation speed in km/s. It must be greater than zero ({@code Double.MAX_VALUE} means no propagation delay, a non-positive value is changed into * 200000 km/seg, a typical speed of light in the wires) * @param attributes Map for user-defined attributes ({@code null} means 'no attribute'). Each key represents the attribute name, whereas value represents the attribute value * @param optionalLayerParameter Network layer to which add the links (optional) * @return A {@code Pair} object with the two newly created links * @see com.net2plan.interfaces.networkDesign.Link * @see com.net2plan.utils.Pair * @see com.net2plan.interfaces.networkDesign.Node */ public Pair<Link, Link> addLinkBidirectional(Node originNode, Node destinationNode , double capacity, double lengthInKm, double propagationSpeedInKmPerSecond, Map<String, String> attributes , NetworkLayer ... optionalLayerParameter) { capacity = NetPlan.adjustToTolerance(capacity); checkIsModifiable(); NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); checkInThisNetPlan(originNode); checkInThisNetPlan(destinationNode); if (originNode.equals (destinationNode)) throw new Net2PlanException("Self-links are not allowed"); if (capacity < 0) throw new Net2PlanException ("Link capacity must be non-negative"); if (lengthInKm < 0) throw new Net2PlanException ("Link length must be non-negative"); if (propagationSpeedInKmPerSecond <= 0) throw new Net2PlanException ("Propagation speed must be positive"); Link link1 = addLink (originNode, destinationNode , capacity, lengthInKm, propagationSpeedInKmPerSecond, attributes , layer); Link link2 = addLink (destinationNode , originNode , capacity, lengthInKm, propagationSpeedInKmPerSecond, attributes , layer); link1.setAttribute(KEY_STRING_BIDIRECTIONALCOUPLE , "" + link2.id); link2.setAttribute(KEY_STRING_BIDIRECTIONALCOUPLE , "" + link1.id); if (ErrorHandling.isDebugEnabled()) this.checkCachesConsistency(); return Pair.of (link1,link2); } /** * <p>Adds a new multicast traffic demand.</p> * <p><b>Important</b>: Ingress node cannot be also an egress node.</p> * * @param ingressNode Ingress node * @param egressNodes Egress node * @param offeredTraffic Offered traffic of the demand. It must be greater or equal than zero * @param attributes Map for user-defined attributes ({@code null} means 'no attribute'). Each key represents the attribute name, whereas value represents the attribute value * @param optionalLayerParameter Network layer to which add the demand (optional) * @return The newly created multicast demand * @see com.net2plan.interfaces.networkDesign.MulticastDemand * @see com.net2plan.interfaces.networkDesign.Node */ public MulticastDemand addMulticastDemand(Node ingressNode , Set<Node> egressNodes , double offeredTraffic, Map<String, String> attributes , NetworkLayer ... optionalLayerParameter) { offeredTraffic = NetPlan.adjustToTolerance(offeredTraffic); checkIsModifiable(); NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); checkInThisNetPlan(ingressNode); checkInThisNetPlan(egressNodes); if (egressNodes.contains (ingressNode)) throw new Net2PlanException("The ingress node cannot be also an egress node"); if (offeredTraffic < 0) throw new Net2PlanException ("Offered traffics must be non-negative"); for (Node n : egressNodes) n.checkAttachedToNetPlanObject(this); if (egressNodes.contains(ingressNode)) throw new Net2PlanException("The ingress node is also an egress node of the multicast demand"); if (offeredTraffic < 0) throw new Net2PlanException ("Offered traffic must be non-negative"); final long demandId = nextElementId.longValue(); nextElementId.increment(); MulticastDemand demand = new MulticastDemand (this , demandId , layer.multicastDemands.size () , layer , ingressNode , egressNodes , offeredTraffic , new AttributeMap (attributes)); cache_id2MulticastDemandMap.put (demandId , demand); layer.multicastDemands.add (demand); for (Node n : egressNodes) n.cache_nodeIncomingMulticastDemands.add (demand); ingressNode.cache_nodeOutgoingMulticastDemands.add (demand); if (ErrorHandling.isDebugEnabled()) this.checkCachesConsistency(); return demand; } /** * <p>Adds a new traffic multicast tree.</p> * * <p><b>Important</b>: Routing type must be {@link com.net2plan.utils.Constants.RoutingType#SOURCE_ROUTING SOURCE_ROUTING}.</p> * * @param demand Multi cast demand to be associated with the tree * @param carriedTraffic Carried traffic. It must be greater or equal than zero * @param occupiedLinkCapacity Occupied link capacity. If -1, it will be assumed to be equal to the carried traffic. Otherwise, it must be greater or equal than zero * @param linkSet {@code Set} of links of the multicast tree * @param attributes Map for user-defined attributes ({@code null} means 'no attribute'). Each key represents the attribute name, whereas value represents the attribute value * @return The newly reated multicast tree * @see com.net2plan.interfaces.networkDesign.MulticastTree * @see com.net2plan.interfaces.networkDesign.MulticastDemand * @see com.net2plan.interfaces.networkDesign.Link */ public MulticastTree addMulticastTree(MulticastDemand demand , double carriedTraffic, double occupiedLinkCapacity, Set<Link> linkSet , Map<String, String> attributes) { carriedTraffic = NetPlan.adjustToTolerance(carriedTraffic); occupiedLinkCapacity = NetPlan.adjustToTolerance(occupiedLinkCapacity); checkIsModifiable(); checkInThisNetPlan(demand); checkMulticastTreeValidityForDemand(linkSet , demand); if (carriedTraffic < 0) throw new Net2PlanException ("Carried traffic must be non-negative"); if (occupiedLinkCapacity < 0) occupiedLinkCapacity = carriedTraffic; NetworkLayer layer = demand.layer; final long treeId = nextElementId.longValue(); nextElementId.increment(); MulticastTree tree = new MulticastTree(this, treeId , layer.multicastTrees.size() , demand, linkSet , new AttributeMap(attributes)); cache_id2MulticastTreeMap.put(treeId, tree); layer.multicastTrees.add(tree); boolean treeIsUp = true; for (Node node : tree.cache_traversedNodes) { node.cache_nodeAssociatedulticastTrees.add (tree); if (!node.isUp) treeIsUp = false; } for (Link link : linkSet) { if (!link.isUp) treeIsUp = false; link.cache_traversingTrees.add (tree); } if (!treeIsUp) layer.cache_multicastTreesDown.add (tree); demand.cache_multicastTrees.add (tree); tree.setCarriedTraffic(carriedTraffic , occupiedLinkCapacity); if (ErrorHandling.isDebugEnabled()) this.checkCachesConsistency(); return tree; } /** * <p>Adds a new node to the network. Nodes are associated to all layers.</p> * @param xCoord Node position in x-axis * @param yCoord Node position in y-axis * @param name Node name ({@code null} will be converted to "Node " + node identifier) * @param attributes Map for user-defined attributes ({@code null} means 'no attribute'). Each key represents the attribute name, whereas value represents the attribute value * @return The newly created node object * @see com.net2plan.interfaces.networkDesign.Node */ public Node addNode(double xCoord, double yCoord, String name, Map<String, String> attributes) { checkIsModifiable(); final long nodeId = nextElementId.longValue(); nextElementId.increment(); Node node = new Node(this, nodeId, nodes.size(), xCoord, yCoord, name, new AttributeMap(attributes)); nodes.add (node); cache_id2NodeMap.put (nodeId , node); for (NetworkLayer layer : layers) { final int E = layer.links.size(); if (layer.routingType == RoutingType.HOP_BY_HOP_ROUTING) { layer.forwardingRules_Aout_ne = DoubleFactory2D.sparse.appendRow(layer.forwardingRules_Aout_ne , DoubleFactory1D.sparse.make (E)); layer.forwardingRules_Ain_ne = DoubleFactory2D.sparse.appendRow(layer.forwardingRules_Ain_ne , DoubleFactory1D.sparse.make (E)); } } if (ErrorHandling.isDebugEnabled()) this.checkCachesConsistency(); return node; } /** * <p>Adds a new protection segment. All the links must belong to the same layer</p> * * <p><b>Important</b>: Routing type must be {@link com.net2plan.utils.Constants.RoutingType#SOURCE_ROUTING SOURCE_ROUTING}.</p> * @param sequenceOfLinks Sequence of links * @param reservedCapacity Reserved capacity in each link from {@code sequenceOfLinks}. It must be greater or equal than zero * @param attributes Map for user-defined attributes ({@code null} means 'no attribute'). Each key represents the attribute name, whereas value represents the attribute value * @return The newly created protetion segment object * @see com.net2plan.interfaces.networkDesign.ProtectionSegment * @see com.net2plan.interfaces.networkDesign.Link */ public ProtectionSegment addProtectionSegment(List<Link> sequenceOfLinks, double reservedCapacity, Map<String, String> attributes) { reservedCapacity = NetPlan.adjustToTolerance(reservedCapacity); checkIsModifiable(); NetworkLayer layer = checkContiguousPath (sequenceOfLinks , null , null , null); checkInThisNetPlanAndLayer(sequenceOfLinks , layer); layer.checkRoutingType(RoutingType.SOURCE_ROUTING); if (reservedCapacity < 0) throw new Net2PlanException ("Reserved capacity must be non-negative"); if (sequenceOfLinks.size () != new HashSet<Link> (sequenceOfLinks).size()) throw new Net2PlanException ("Protection segments cannot traverse the same link more than once"); final long segmentId = nextElementId.longValue(); nextElementId.increment(); ProtectionSegment segment = new ProtectionSegment (this, segmentId , layer.protectionSegments.size (), sequenceOfLinks , reservedCapacity , new AttributeMap (attributes)); cache_id2ProtectionSegmentMap.put (segmentId , segment); layer.protectionSegments.add (segment); boolean segmentIsUp = true; for (Link link : sequenceOfLinks) { link.cache_traversingSegments.add (segment); if (!link.isUp) segmentIsUp = false; } for (Node node : segment.seqNodes) {node.cache_nodeAssociatedSegments.add (segment) ; if (!node.isUp) segmentIsUp = false; } if (!segmentIsUp) layer.cache_segmentsDown.add (segment); if (ErrorHandling.isDebugEnabled()) this.checkCachesConsistency(); return segment; } /** * <p>Adds a new traffic route </p> * * <p><b>Important</b>: Routing type must be {@link com.net2plan.utils.Constants.RoutingType#SOURCE_ROUTING SOURCE_ROUTING}.</p> * @param demand Demand associated to the route * @param carriedTraffic Carried traffic. It must be greater or equal than zero * @param occupiedLinkCapacity Occupied link capacity, it must be greater or equal than zero. * @param sequenceOfLinks Sequence of links traversed by the route * @param attributes Map for user-defined attributes ({@code null} means 'no attribute'). Each key represents the attribute name, whereas value represents the attribute value * @return The newly created route object * @see com.net2plan.interfaces.networkDesign.Route * @see com.net2plan.interfaces.networkDesign.Demand * @see com.net2plan.interfaces.networkDesign.Link */ public Route addRoute(Demand demand , double carriedTraffic, double occupiedLinkCapacity, List<Link> sequenceOfLinks, Map<String, String> attributes) { carriedTraffic = NetPlan.adjustToTolerance(carriedTraffic); occupiedLinkCapacity = NetPlan.adjustToTolerance(occupiedLinkCapacity); checkIsModifiable(); checkInThisNetPlan(demand); checkPathValidityForDemand(sequenceOfLinks, demand); demand.layer.checkRoutingType(RoutingType.SOURCE_ROUTING); if (carriedTraffic < 0) throw new Net2PlanException ("Carried traffic must be non-negative"); if (occupiedLinkCapacity < 0) occupiedLinkCapacity = carriedTraffic; NetworkLayer layer = demand.layer; final long routeId = nextElementId.longValue(); nextElementId.increment(); Route route = new Route(this, routeId, layer.routes.size(), demand , sequenceOfLinks , new AttributeMap(attributes)); layer.routes.add(route); cache_id2RouteMap.put (routeId,route); boolean isUpThisRoute = true; for (Node node : route.seqNodesRealPath) { node.cache_nodeAssociatedRoutes.add (route); if (!node.isUp) isUpThisRoute = false; } for (Link link : route.seqLinksRealPath) { Integer numPassingTimes = link.cache_traversingRoutes.get (route); if (numPassingTimes == null) numPassingTimes = 1; else numPassingTimes ++; link.cache_traversingRoutes.put (route , numPassingTimes); if (!link.isUp) isUpThisRoute = false; } demand.cache_routes.add (route); if (!isUpThisRoute) layer.cache_routesDown.add (route); route.setCarriedTraffic(carriedTraffic , occupiedLinkCapacity); if (ErrorHandling.isDebugEnabled()) this.checkCachesConsistency(); return route; } /** * <p>Adds traffic routes specified by those paths that satisfy the candidate path list options described below. Existing routes will not be removed.</p> * * <p><b>Important</b>: Routing type must be {@link com.net2plan.utils.Constants.RoutingType#SOURCE_ROUTING SOURCE_ROUTING}.</p> * * <p>The candidate path list elaborated contains a set of paths * computed for each unicast demand in the network, based on the k-shortest path idea. In general, for every demand k * paths are computed with the shortest weight according to some weights * assigned to the links.</p> * <p>The computation of paths can be configured via {@code "parameter=value"} options. There are several options to * configure, which can be combined:</p> * * <ul> * <li>{@code K}: Number of desired loopless shortest paths (default: 3). If <i>K'</i>&lt;{@code K} different paths are found between the demand node pairs, then only <i>K'</i> paths are * included in the candidate path list</li> * <li>{@code maxLengthInKm}: Maximum path length measured in kilometers allowed (default: Double.MAX_VALUE)</li> * <li>{@code maxNumHops}: Maximum number of hops allowed (default: Integer.MAX_VALUE)</li> * <li>{@code maxPropDelayInMs}: Maximum propagation delay in miliseconds allowed in a path (default: Double.MAX_VALUE)</li> * <li>{@code maxRouteCost}: Maximum path weight allowed (default: Double.MAX_VALUE)</li> * <li>{@code maxRouteCostFactorRespectToShortestPath}: Maximum path weight factor with respect to the shortest path weight (default: Double.MAX_VALUE)</li> * <li>{@code maxRouteCostRespectToShortestPath}: Maximum path weight with respect to the shortest path weight (default: Double.MAX_VALUE). While the previous one is a multiplicative factor, this one is an additive factor</li> * </ul> * * @param costs Link weight vector for the shortest path algorithm * @param paramValuePairs Parameters to be passed to the class to tune its operation. An even number of {@code String} is to be passed. For each {@code String} pair, first {@code String} * must be the name of the parameter, second a {@code String} with its value. If no name-value pairs are set, default values are used * @return Map with all the computed paths (values) per demands (keys) */ public Map<Demand,List<List<Link>>> computeUnicastCandidatePathList (double [] costs , String... paramValuePairs) { return computeUnicastCandidatePathList(defaultLayer, costs, paramValuePairs); } /** * <p>Computes a list of disjoint path pairs for each demand, using the paths in the input candidate path list given.</p> * * @param cpl Candidate path list per demand * @param disjointType Type of disjointness: 0 for SRG-disjoint, 1 for link and node disjoint, other value means link disjoint * @return List of disjoint path pairs for each demand * @since 0.4.0 */ public static Map<Demand,List<Pair<List<Link>,List<Link>>>> computeUnicastCandidate11PathList (Map<Demand,List<List<Link>>> cpl , int disjointType) { final boolean srgDisjoint = disjointType == 0; final boolean linkAndNodeDisjoint = disjointType == 1; final boolean linkDisjoint = !srgDisjoint && !linkAndNodeDisjoint; Map<Demand,List<Pair<List<Link>,List<Link>>>> result = new HashMap<Demand,List<Pair<List<Link>,List<Link>>>> (); for (Demand d : cpl.keySet()) { for (List<Link> path : cpl.get(d)) d.netPlan.checkInThisNetPlanAndLayer(path , d.layer); List<Pair<List<Link>,List<Link>>> pairs11ThisDemand = new ArrayList<Pair<List<Link>,List<Link>>> (); final List<List<Link>> paths = new ArrayList<List<Link>> (cpl.get(d)); final int P_d = paths.size (); for (int firstPathIndex = 0; firstPathIndex < P_d-1 ; firstPathIndex ++) { final List<Link> firstPath = paths.get(firstPathIndex); final Set<Link> firstPathLinks = new HashSet<Link> (firstPath); Set<Node> firstPathNodesButLastAndFirst = null; Set<SharedRiskGroup> firstPathSRGs = null; if (linkAndNodeDisjoint) { List<Node> firstPathSeqNodes = GraphUtils.convertSequenceOfLinksToSequenceOfNodes(firstPath); firstPathNodesButLastAndFirst = new HashSet<Node> (firstPathSeqNodes); firstPathNodesButLastAndFirst.remove(d.ingressNode); firstPathNodesButLastAndFirst.remove(d.egressNode); } else if (srgDisjoint) { firstPathSRGs = SRGUtils.getAffectingSRGs(firstPathLinks); } for (int secondPathIndex = firstPathIndex + 1; secondPathIndex < P_d ; secondPathIndex ++) { List<Link> secondPath = paths.get(secondPathIndex); boolean disjoint = true; boolean firstLink = true; if (linkDisjoint) { for (Link e : secondPath) if (firstPathLinks.contains(e)) { disjoint = false; break; } } else if (linkAndNodeDisjoint) { for (Link e : secondPath) { if (firstPathLinks.contains(e)) { disjoint = false; break; } if (firstLink) firstLink = false; else { if (firstPathNodesButLastAndFirst.contains(e.originNode)) disjoint = false; break; } } } else if (srgDisjoint) { for (SharedRiskGroup srg : SRGUtils.getAffectingSRGs(secondPath)) if (firstPathSRGs.contains(srg)) { disjoint = false; break; } } if (disjoint) { checkDisjointness (firstPath , secondPath , disjointType); pairs11ThisDemand.add (Pair.of(firstPath, secondPath)); } } } result.put (d , pairs11ThisDemand); } return result; } private static void checkDisjointness (List<Link> p1 , List<Link> p2 , int disjointnessType) { if ((p1 == null) || (p2 == null)) throw new RuntimeException ("Bad"); if (disjointnessType == 0) // SRG disjoint { Set<SharedRiskGroup> srg1 = new HashSet<SharedRiskGroup> (); for (Link e : p1) srg1.addAll (e.getSRGs()); for (Link e : p2) for (SharedRiskGroup srg : e.getSRGs()) if (srg1.contains(srg)) throw new RuntimeException ("Bad"); } else if (disjointnessType == 1) // link and node { Set<NetworkElement> resourcesP1 = new HashSet<NetworkElement> (); boolean firstLink = true; for (Link e : p1) { resourcesP1.add (e); if (firstLink) firstLink = false; else resourcesP1.add (e.getOriginNode()); } for (Link e : p2) if (resourcesP1.contains(e)) throw new RuntimeException ("Bad"); } else if (disjointnessType == 2) // link { Set<Link> linksP1 = new HashSet<Link> (p1); for (Link e : p2) if (linksP1.contains (e)) throw new RuntimeException ("Bad: p1: " + p1 + ", p2: " + p2); } else throw new RuntimeException ("Bad"); } /** * <p>Adds traffic routes specified by those paths that satisfy the candidate path list options described below. Existing routes will not be removed.</p> * * <p><b>Important</b>: Routing type must be {@link com.net2plan.utils.Constants.RoutingType#SOURCE_ROUTING SOURCE_ROUTING}.</p> * * <p>The candidate path list elaborated contains a set of paths * computed for each unicast demand in the network, based on the k-shortest path idea. In general, for every demand k * paths are computed with the shortest weight according to some weights * assigned to the links.</p> * <p>The computation of paths can be configured via {@code "parameter=value"} options. There are several options to * configure, which can be combined:</p> * * <ul> * <li>{@code K}: Number of desired loopless shortest paths (default: 3). If <i>K'&lt;</i>{@code K} different paths are found between the demand node pairs, then only <i>K'</i> paths are * included in the candidate path list</li> * <li>{@code maxLengthInKm}: Maximum path length measured in kilometers allowed (default: Double.MAX_VALUE)</li> * <li>{@code maxNumHops}: Maximum number of hops allowed (default: Integer.MAX_VALUE)</li> * <li>{@code maxPropDelayInMs}: Maximum propagation delay in miliseconds allowed in a path (default: Double.MAX_VALUE)</li> * <li>{@code maxRouteCost}: Maximum path weight allowed (default: Double.MAX_VALUE)</li> * <li>{@code maxRouteCostFactorRespectToShortestPath}: Maximum path weight factor with respect to the shortest path weight (default: Double.MAX_VALUE)</li> * <li>{@code maxRouteCostRespectToShortestPath}: Maximum path weight with respect to the shortest path weight (default: Double.MAX_VALUE). While the previous one is a multiplicative factor, this one is an additive factor</li> * </ul> * * @param layer Network layer * @param costs Link weight vector for the shortest path algorithm. If null, all the links have cost one * @param paramValuePairs Parameters to be passed to the class to tune its operation. An even number of {@code String} is to be passed. For each {@code String} pair, first {@code String} * must be the name of the parameter, second a {@code String} with its value. If no name-value pairs are set, default values are used * @return Map with all the computed paths (values) per demands (keys) */ public Map<Demand,List<List<Link>>> computeUnicastCandidatePathList (NetworkLayer layer , double [] costs , String... paramValuePairs) { checkIsModifiable(); checkInThisNetPlan(layer); layer.checkRoutingType(RoutingType.SOURCE_ROUTING); if (costs != null) if (costs.length != layer.links.size()) throw new Net2PlanException ("The array of costs must have the same length as the number of links in the layer"); int K = 3; double maxLengthInKm = Double.MAX_VALUE; int maxNumHops = Integer.MAX_VALUE; double maxPropDelayInMs = Double.MAX_VALUE; double maxRouteCost = Double.MAX_VALUE; double maxRouteCostFactorRespectToShortestPath = Double.MAX_VALUE; double maxRouteCostRespectToShortestPath = Double.MAX_VALUE; int numParameters = (int) (paramValuePairs.length / 2); if (numParameters * 2 != paramValuePairs.length) throw new Net2PlanException("A parameter has not assigned its value"); for (int contParam = 0; contParam < numParameters; contParam++) { String parameter = paramValuePairs[contParam * 2]; String value = paramValuePairs[contParam * 2 + 1]; if (parameter.equalsIgnoreCase("K")) { K = Integer.parseInt(value); if (K <= 0) throw new Net2PlanException("'K' parameter must be greater than zero"); } else if (parameter.equalsIgnoreCase("maxLengthInKm")) maxLengthInKm = Double.parseDouble(value) <= 0? Double.MAX_VALUE : Double.parseDouble(value); else if (parameter.equalsIgnoreCase("maxPropDelayInMs")) maxPropDelayInMs = Double.parseDouble(value) <= 0? Double.MAX_VALUE : Double.parseDouble(value); else if (parameter.equalsIgnoreCase("maxNumHops")) maxNumHops = Integer.parseInt(value) <= 0? Integer.MAX_VALUE : Integer.parseInt(value); else if (parameter.equalsIgnoreCase("maxRouteCost")) maxRouteCost = Double.parseDouble(value) <= 0? Double.MAX_VALUE : Double.parseDouble(value); else if (parameter.equalsIgnoreCase("maxRouteCostFactorRespectToShortestPath")) maxRouteCostFactorRespectToShortestPath = Double.parseDouble(value) <= 0? Double.MAX_VALUE : Double.parseDouble(value); else if (parameter.equalsIgnoreCase("maxRouteCostRespectToShortestPath")) maxRouteCostRespectToShortestPath = Double.parseDouble(value) <= 0? Double.MAX_VALUE : Double.parseDouble(value); else throw new RuntimeException("Unknown parameter " + parameter); } Map<Demand,List<List<Link>>> cpl = new HashMap<Demand,List<List<Link>>> (); Map<Link,Double> linkCostMap = new HashMap<Link,Double> (); for (Link e : layer.links) linkCostMap.put (e , costs == null? 1.0 : costs [e.index]); for(Demand d : layer.demands) cpl.put (d , GraphUtils.getKLooplessShortestPaths(nodes , layer.links , d.ingressNode , d.egressNode , linkCostMap , K , maxLengthInKm, maxNumHops, maxPropDelayInMs , maxRouteCost , maxRouteCostFactorRespectToShortestPath , maxRouteCostRespectToShortestPath )); return cpl; } /** * <p>Adds multiples routes from a Candidate Path List.</p> * @param cpl {@code Map} where the keys are demands and the values a list of sequence of links (each sequence is a route) */ public void addRoutesFromCandidatePathList (Map<Demand,List<List<Link>>> cpl) { checkIsModifiable(); List<Route> routes = new LinkedList<Route> (); try { for(Entry<Demand,List<List<Link>>> entry : cpl.entrySet()) for (List<Link> seqLinks : entry.getValue()) routes.add (addRoute(entry.getKey() , 0 , 0 , seqLinks , null)); } catch (Exception e) { for (Route r : routes) r.remove (); throw e; } if (ErrorHandling.isDebugEnabled()) this.checkCachesConsistency(); } /** * <p>Same as {@code addRoutesFromCandidatePathList(computeUnicastCandidatePathList(layer , costs , paramValuePairs);} * @param layer Network layer * @param costs Link weight vector for the shortest path algorithm * @param paramValuePairs Parameters to be passed to the class to tune its operation. An even number of {@code String} is to be passed. For each {@code String} pair, first {@code String} * must be the name of the parameter, second a {@code String} with its value. If no name-value pairs are set, default values are used */ public void addRoutesFromCandidatePathList (NetworkLayer layer , double [] costs , String... paramValuePairs) { addRoutesFromCandidatePathList(computeUnicastCandidatePathList(layer , costs , paramValuePairs)); } /** * <p>Same as {@code addRoutesFromCandidatePathList(computeUnicastCandidatePathList(costs , paramValuePairs);} * @param costs Link weight vector for the shortest path algorithm * @param paramValuePairs Parameters to be passed to the class to tune its operation. An even number of {@code String} is to be passed. For each {@code String} pair, first {@code String} * must be the name of the parameter, second a {@code String} with its value. If no name-value pairs are set, default values are used */ public void addRoutesFromCandidatePathList (double [] costs , String... paramValuePairs) { addRoutesFromCandidatePathList(computeUnicastCandidatePathList(costs , paramValuePairs)); } public void addRoutesAndProtectionSegmentFromCandidate11PathList (Map<Demand,List<Pair<List<Link>,List<Link>>>> cpl11) { checkIsModifiable(); List<Route> routes = new LinkedList<Route> (); List<ProtectionSegment> segments = new LinkedList<ProtectionSegment> (); try { for(Entry<Demand,List<Pair<List<Link>,List<Link>>>> entry : cpl11.entrySet()) for (Pair<List<Link>,List<Link>> pathPair : entry.getValue()) { final Route newRoute = addRoute(entry.getKey() , 0 , 0 , pathPair.getFirst() , null); routes.add (newRoute); final ProtectionSegment newSegment = addProtectionSegment(pathPair.getSecond(), 0, null); segments.add (newSegment); newRoute.addProtectionSegment(newSegment); } } catch (Exception e) { for (Route r : routes) r.remove (); for (ProtectionSegment s : segments) s.remove (); throw e; } if (ErrorHandling.isDebugEnabled()) this.checkCachesConsistency(); } // public void addMulticastTreesFromCandidateTreeList (double [] costs , String solverName , String solverLibraryName , double maxSolverTimeInSecondsPerTree , String... paramValuePairs) // { // addMulticastTreesFromCandidateTreeList (defaultLayer , costs , solverName , solverLibraryName , maxSolverTimeInSecondsPerTree , paramValuePairs); // } // /** * The same as {@code computeMulticastCandidatePathList} for the default layer * @param costs see {@code computeMulticastCandidatePathList} * @param solverName see {@code computeMulticastCandidatePathList} * @param solverLibraryName see {@code computeMulticastCandidatePathList} * @param maxSolverTimeInSecondsPerTree see {@code computeMulticastCandidatePathList} * @param candidateTreeListParamValuePairs see {@code computeMulticastCandidatePathList} * @return see {@code computeMulticastCandidatePathList} */ public Map<MulticastDemand,List<Set<Link>>> computeMulticastCandidatePathList (DoubleMatrix1D costs , String solverName , String solverLibraryName , double maxSolverTimeInSecondsPerTree , String... candidateTreeListParamValuePairs) { return computeMulticastCandidatePathList (defaultLayer , costs , solverName , solverLibraryName , maxSolverTimeInSecondsPerTree , candidateTreeListParamValuePairs); } /** * <p>Adds multicast trees specified by those trees that satisfy the options described below. Existing multicast trees will not be removed.</p> * * <p>The candidate tree list elaborated contains a set of multicast trees (each one is a set of links) computed for each multicast demand * in the network. To compute it, a ILP formulation is solved for each new multicast tree. In general, for every multicast demand k * trees are computed ranked according to its cost (weight) according to some link weights.</p> * <p>The computation of paths can be configured via {@code "parameter=value"} options. There are several options to * configure, which can be combined:</p> * * <ul> * <li>{@code K}: Number of desired multicast trees per demand (default: 3). If <i>K'&lt;</i>{@code K} different trees are found for the multicast demand, then only <i>K'</i> are * included in the candidate list</li> * <li>{@code maxCopyCapability}: the maximum number of copies of an input traffic a node can make. Then, a node can have at most this number of ouput links carrying traffic of a multicast tree (default: Double.MAX_VALUE)</li> * <li>{@code maxE2ELengthInKm}: Maximum path length measured in kilometers allowed for any tree, from the origin node, to any destination node (default: Double.MAX_VALUE)</li> * <li>{@code maxE2ENumHops}: Maximum number of hops allowed for any tree, from the origin node, to any destination node (default: Integer.MAX_VALUE)</li> * <li>{@code maxE2EPropDelayInMs}: Maximum propagation delay in miliseconds allowed in a path, for any tree, from the origin node, to any destination node (default: Double.MAX_VALUE)</li> * <li>{@code maxTreeCost}: Maximum tree weight allowed, summing the weights of the links (default: Double.MAX_VALUE)</li> * <li>{@code maxTreeCostFactorRespectToMinimumCostTree}: Trees with higher weight (cost) than the cost of the minimum cost tree, multiplied by this factor, are not returned (default: Double.MAX_VALUE)</li> * <li>{@code maxTreeCostRespectToMinimumCostTree}: Trees with higher weight (cost) than the cost of the minimum cost tree, plus this factor, are not returned (default: Double.MAX_VALUE). While the previous one is a multiplicative factor, this one is an additive factor</li> * </ul> * * @param layer the layer for which the candidate multicast tree list is computed * @param linkCosts Link weight vector for the shortest path algorithm. If {@code null}, a vector of ones is assumed * @param solverName the name of the solver to call for the internal formulation of the algorithm * @param solverLibraryName the solver library name * @param maxSolverTimeInSecondsPerTree the maximum time the solver is allowed for each of the internal formulations (one for each new tree). * The best solution found so far is returned. If non-positive, no time limit is set * @param candidateTreeListParamValuePairs Parameters to be passed to the class to tune its operation. An even number of {@code String} is to be passed. For each {@code String} pair, first {@code String} * must be the name of the parameter, second a {@code String} with its value. If no name-value pairs are set, default values are used * @return Map with a list of all the computed trees (a tree is a set of links) per multicast demands */ public Map<MulticastDemand,List<Set<Link>>> computeMulticastCandidatePathList (NetworkLayer layer, DoubleMatrix1D linkCosts , String solverName , String solverLibraryName , double maxSolverTimeInSecondsPerTree , String... candidateTreeListParamValuePairs) { checkInThisNetPlan(layer); if (linkCosts == null) linkCosts = DoubleFactory1D.dense.make (layer.links.size () , 1); if (linkCosts.size () != layer.links.size()) throw new Net2PlanException ("The array of costs must have the same length as the number of links in the layer"); Map<MulticastDemand,List<Set<Link>>> cpl = new HashMap<MulticastDemand,List<Set<Link>>> (); int K = 3; int maxCopyCapability = Integer.MAX_VALUE; double maxE2ELengthInKm = Double.MAX_VALUE; int maxE2ENumHops = Integer.MAX_VALUE; double maxE2EPropDelayInMs = Double.MAX_VALUE; double maxTreeCost = Double.MAX_VALUE; double maxTreeCostFactorRespectToMinimumCostTree = Double.MAX_VALUE; double maxTreeCostRespectToMinimumCostTree = Double.MAX_VALUE; int numParameters = (int) (candidateTreeListParamValuePairs.length / 2); if (numParameters * 2 != candidateTreeListParamValuePairs.length) throw new Net2PlanException("A parameter has not assigned its value"); for (int contParam = 0; contParam < numParameters; contParam++) { String parameter = candidateTreeListParamValuePairs[contParam * 2]; String value = candidateTreeListParamValuePairs[contParam * 2 + 1]; if (parameter.equalsIgnoreCase("K")) { K = Integer.parseInt(value); if (K <= 0) throw new Net2PlanException("'K' parameter must be greater than zero"); } else if (parameter.equalsIgnoreCase("maxCopyCapability")) maxCopyCapability = Integer.parseInt (value) <= 0? Integer.MAX_VALUE : Integer.parseInt (value); else if (parameter.equalsIgnoreCase("maxE2ELengthInKm")) maxE2ELengthInKm = Double.parseDouble(value) <= 0? Double.MAX_VALUE : Double.parseDouble(value); else if (parameter.equalsIgnoreCase("maxE2EPropDelayInMs")) maxE2EPropDelayInMs = Double.parseDouble(value) <= 0? Double.MAX_VALUE : Double.parseDouble(value); else if (parameter.equalsIgnoreCase("maxE2ENumHops")) maxE2ENumHops = Integer.parseInt (value) <= 0? Integer.MAX_VALUE : Integer.parseInt (value); else if (parameter.equalsIgnoreCase("maxTreeCost")) maxTreeCost = Double.parseDouble(value) <= 0? Double.MAX_VALUE : Double.parseDouble(value); else if (parameter.equalsIgnoreCase("maxTreeCostFactorRespectToMinimumCostTree")) maxTreeCostFactorRespectToMinimumCostTree = Double.parseDouble(value) <= 0? Double.MAX_VALUE : Double.parseDouble(value); else if (parameter.equalsIgnoreCase("maxTreeCostRespectToMinimumCostTree")) maxTreeCostRespectToMinimumCostTree = Double.parseDouble(value) <= 0? Double.MAX_VALUE : Double.parseDouble(value); else throw new RuntimeException("Unknown parameter " + parameter); } final DoubleMatrix2D Aout_ne = (layer.routingType == RoutingType.SOURCE_ROUTING)? getMatrixNodeLinkOutgoingIncidence(layer) : layer.forwardingRules_Aout_ne; final DoubleMatrix2D Ain_ne = (layer.routingType == RoutingType.SOURCE_ROUTING)? getMatrixNodeLinkIncomingIncidence(layer) : layer.forwardingRules_Ain_ne; for (MulticastDemand d : layer.multicastDemands) { List<Set<Link>> trees = GraphUtils.getKMinimumCostMulticastTrees(layer.links , d.getIngressNode() , d.getEgressNodes() , Aout_ne , Ain_ne , linkCosts , solverName , solverLibraryName , maxSolverTimeInSecondsPerTree , K , maxCopyCapability , maxE2ELengthInKm , maxE2ENumHops, maxE2EPropDelayInMs , maxTreeCost , maxTreeCostFactorRespectToMinimumCostTree , maxTreeCostRespectToMinimumCostTree); cpl.put(d, trees); } return cpl; } /** * <p>Adds multiple multicast trees from a Candidate Tree list.</p> * @param cpl {@code Map} where the keys are multicast demands and the values lists of link sets * @see com.net2plan.interfaces.networkDesign.MulticastDemand * @see com.net2plan.interfaces.networkDesign.Link */ public void addMulticastTreesFromCandidateTreeList (Map<MulticastDemand,List<Set<Link>>> cpl) { checkIsModifiable(); List<MulticastTree> trees = new LinkedList<MulticastTree> (); try { for(Entry<MulticastDemand,List<Set<Link>>> entry : cpl.entrySet()) for (Set<Link> linkSet : entry.getValue()) trees.add(addMulticastTree(entry.getKey(), 0, 0, linkSet, null)); } catch (Exception e) { for (MulticastTree t : trees) t.remove (); throw e; } if (ErrorHandling.isDebugEnabled()) this.checkCachesConsistency(); } /** * <p>Adds a new SRG.</p> * @param mttfInHours Mean Time To Fail (in hours). Must be greater than zero * @param mttrInHours Mean Time To Repair (in hours). Must be greater than zero * @param attributes Map for user-defined attributes ({@code null} means 'no attribute'). Each key represents the attribute name, whereas value represents the attribute value * @return The newly created shared risk group object * @see com.net2plan.interfaces.networkDesign.SharedRiskGroup */ public SharedRiskGroup addSRG(double mttfInHours, double mttrInHours, Map<String, String> attributes) { checkIsModifiable(); if (mttfInHours <= 0) throw new Net2PlanException ("Mean Time To Fail must be a positive value"); if (mttrInHours <= 0) throw new Net2PlanException ("Mean Time To Repair must be a positive value"); final long srgId = nextElementId.longValue(); nextElementId.increment(); SharedRiskGroup srg = new SharedRiskGroup(this, srgId, srgs.size(), new HashSet<Node> (), new HashSet<Link> () , mttfInHours , mttrInHours , new AttributeMap(attributes)); srgs.add (srg); cache_id2srgMap.put (srgId , srg); if (ErrorHandling.isDebugEnabled()) this.checkCachesConsistency(); return srg; } /** * <p>Assigns the information from the input {@code NetPlan}.</p> * * <p><b>Important</b>: A shadow copy is made, so changes in the input object will be reflected in this one. For deep copies use {@link #copyFrom(com.net2plan.interfaces.networkDesign.NetPlan) copyFrom()}</p> * * @param netPlan Network plan to be copied * @since 0.3.0 */ public void assignFrom(NetPlan netPlan) { checkIsModifiable(); this.DEFAULT_ROUTING_TYPE = netPlan.DEFAULT_ROUTING_TYPE; this.isModifiable = netPlan.isModifiable; this.networkDescription = netPlan.networkDescription; this.networkName = netPlan.networkName; this.defaultLayer = netPlan.defaultLayer; this.nextElementId = netPlan.nextElementId; this.layers = netPlan.layers; this.nodes = netPlan.nodes; this.srgs = netPlan.srgs; this.cache_nodesDown = netPlan.cache_nodesDown; this.cache_id2LayerMap = netPlan.cache_id2LayerMap; this.cache_id2NodeMap = netPlan.cache_id2NodeMap; this.cache_id2LinkMap = netPlan.cache_id2LinkMap; this.cache_id2DemandMap = netPlan.cache_id2DemandMap; this.cache_id2MulticastDemandMap = netPlan.cache_id2MulticastDemandMap; this.cache_id2RouteMap = netPlan.cache_id2RouteMap; this.cache_id2MulticastTreeMap = netPlan.cache_id2MulticastTreeMap; this.cache_id2ProtectionSegmentMap = netPlan.cache_id2ProtectionSegmentMap; this.cache_id2srgMap = netPlan.cache_id2srgMap; this.interLayerCoupling = netPlan.interLayerCoupling; this.attributes.clear (); this.attributes.putAll(netPlan.attributes); for (Node node : netPlan.nodes) node.netPlan = this; for (SharedRiskGroup srg : netPlan.srgs) srg.netPlan = this; for (NetworkLayer layer : netPlan.layers) { layer.netPlan = this; for (Link e : layer.links) e.netPlan = this; for (Demand e : layer.demands) e.netPlan = this; for (MulticastDemand e : layer.multicastDemands) e.netPlan = this; for (Route e : layer.routes) e.netPlan = this; for (ProtectionSegment e : layer.protectionSegments) e.netPlan = this; for (MulticastTree e : layer.multicastTrees) e.netPlan = this; } if (ErrorHandling.isDebugEnabled()) this.checkCachesConsistency(); } /** * <p>Checks that the input sequence of links belong to the same layer and follow a contiguous path. Throws an exception if the path is not contiguous or the sequence of links * is empty. </p> * @param links Sequence of links * @param layer Network layer * @param originNode Origin node * @param destinationNode Destination node * @return The input layer */ public NetworkLayer checkContiguousPath (List<Link> links , NetworkLayer layer , Node originNode , Node destinationNode) { if (links.isEmpty()) throw new Net2PlanException ("Empty sequence of links"); final Link firstLink = links.iterator().next (); if (layer == null) layer = firstLink.layer; checkInThisNetPlan(layer); if (originNode != null) checkInThisNetPlan(originNode); if (destinationNode != null) checkInThisNetPlan(destinationNode); for (Link e : links) if (!e.layer.equals (layer)) throw new Net2PlanException ("The path contains links not attached to the appropriate NetPlan object or layer"); if ((originNode != null) && (!firstLink.originNode.equals (originNode))) throw new Net2PlanException ("The initial node of the sequence of links is not correct"); Node endNodePreviousLink = firstLink.originNode; for (Link link : links) { if (!endNodePreviousLink.equals (link.originNode)) throw new Net2PlanException ("This is not a contigous sequence of links"); endNodePreviousLink = link.destinationNode; } if ((destinationNode != null) && !(endNodePreviousLink.equals (destinationNode))) throw new Net2PlanException ("The end node of the sequence of links is not correct"); return layer; } /** * <p>Checks if a demand exists in this {@code NetPlan} object. Throws an exception if nonexistent.</p> * @param id Demand id */ void checkExistsDemand (long id) { if (cache_id2DemandMap.get(id) == null) throw new Net2PlanException ("Demand of id: " + id + " does not exist"); } /** * <p>Checks if a link exists in this {@code NetPlan} object. Throws an exception if nonexistent.</p> * @param id Link id */ void checkExistsLink (long id) { if (cache_id2LinkMap.get(id) == null) throw new Net2PlanException ("Link of id: " + id + " does not exist"); } /** * <p>Checks if a multicast demand exists in this {@code NetPlan} object. Throws an exception if nonexistent.</p> * @param id Multicast demand id */ void checkExistsMulticastDemand (long id) { if (cache_id2MulticastDemandMap.get(id) == null) throw new Net2PlanException ("Multicast demand of id: " + id + " does not exist"); } /** * <p>Checks if a multicast tree exists in this {@code NetPlan} object. Throws an exception if nonexistent.</p> * @param id Multicast tree id */ void checkExistsMulticastTree (long id) { if (cache_id2MulticastTreeMap.get(id) == null) throw new Net2PlanException ("Multicast tree of id: " + id + " does not exist"); } /** * <p>Checks if a network layer exists in this {@code NetPlan} object. Throws an exception if nonexistent.</p> * @param id Network layer id */ void checkExistsNetworkLayer (long id) { if (cache_id2LayerMap.get(id) == null) throw new Net2PlanException ("Network layer of id: " + id + " does not exist"); } /** * <p>Checks if a node exists in this {@code NetPlan} object. Throws an exception if nonexistent.</p> * @param id Node id */ void checkExistsNode (long id) { if (cache_id2NodeMap.get(id) == null) throw new Net2PlanException ("Node of id: " + id + " does not exist"); } /** * <p>Checks if a protection segment exists in this {@code NetPlan} object. Throws an exception if nonexistent.</p> * @param id Protection segment id */ void checkExistsProtectionSegment (long id) { if (cache_id2ProtectionSegmentMap.get(id) == null) throw new Net2PlanException ("ProtectionSegment of id: " + id + " does not exist"); } /** * <p>Checks if a route exists in this {@code NetPlan} object. Throws an exception if nonexistent.</p> * @param id Route id */ void checkExistsRoute (long id) { if (cache_id2RouteMap.get(id) == null) throw new Net2PlanException ("Route of id: " + id + " does not exist"); } /** * <p>Checks if a shared risk group exists in this {@code NetPlan} object. Throws an exception if nonexistent.</p> * @param id the SRG identifier */ void checkExistsSRG (long id) { if (cache_id2srgMap.get(id) == null) throw new Net2PlanException ("Shared risk group of id: " + id + " does not exist"); } /** * <p>Checks if all the elements are attached to this {@code NetPlan} object. * .</p> * @param elements Collection of network elements * @see com.net2plan.interfaces.networkDesign.NetworkElement */ void checkInThisNetPlan(Collection<? extends NetworkElement> elements) { for (NetworkElement e : elements) checkInThisNetPlan(e); } /** * <p>Checks if an element is attached to this {@code NetPlan} object. It is checked also if the element belongs to the input layer.</p> * @param e Network element * @param layer Network layer (optional) */ void checkInThisNetPlanAndLayer(Collection<? extends NetworkElement> elements, NetworkLayer ... optionalLayer) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayer); for (NetworkElement e : elements) checkInThisNetPlanAndLayer(e, layer); } /** * <p>Checks if a network element exists in this {@code NetPlan} object. Throws an exception if nonexistent.</p> * @param e Network element * */ void checkInThisNetPlan(NetworkElement e) { if (e == null) throw new Net2PlanException ("Network element is null"); if (e.netPlan != this) throw new Net2PlanException ("Element " + e + " is not attached to this NetPlan object."); if (e instanceof Node) { if (e != nodes.get(e.index)) throw new Net2PlanException ("Element " + e + " is not the same object as the one in netPlan object."); } else if (e instanceof SharedRiskGroup) { if (e != srgs.get(e.index)) throw new Net2PlanException ("Element " + e + " is not the same object as the one in netPlan object."); } else if (e instanceof NetworkLayer) { if (e != layers.get(e.index)) throw new Net2PlanException ("Element " + e + " is not the same object as the one in netPlan object."); } } /** * <p>Checks if an element is attached to this {@code NetPlan} object. It is checked also if the element belongs to the input layer.</p> * @param e Network element * @param layer Network layer (optional) */ void checkInThisNetPlanAndLayer(NetworkElement e, NetworkLayer layer) { if (e == null) throw new Net2PlanException ("Network element is null"); if (e.netPlan != this) throw new Net2PlanException ("Element " + e + " is not attached to this NetPlan object."); if (e instanceof Node) { if (e != nodes.get(e.index)) throw new Net2PlanException ("Element " + e + " is not the same object as the one in netPlan object."); } else if (e instanceof SharedRiskGroup) { if (e != srgs.get(e.index)) throw new Net2PlanException ("Element " + e + " is not the same object as the one in netPlan object."); } else if (e instanceof NetworkLayer) { if (e != layers.get(e.index)) throw new Net2PlanException ("Element " + e + " is not the same object as the one in netPlan object."); } if (layer != null) { layer.checkAttachedToNetPlanObject(this); if (e instanceof Demand) { if (e != layer.demands.get(e.index)) throw new Net2PlanException ("Element " + e + " is not the same object as the one in netPlan object."); } else if (e instanceof ProtectionSegment) { if (e != layer.protectionSegments.get(e.index)) throw new Net2PlanException ("Element " + e + " is not the same object as the one in netPlan object."); } else if (e instanceof Link) { if (e != layer.links.get(e.index)) throw new Net2PlanException ("Element " + e + " is not the same object as the one in netPlan object."); } else if (e instanceof MulticastDemand) { if (e != layer.multicastDemands.get(e.index)) throw new Net2PlanException ("Element " + e + " is not the same object as the one in netPlan object."); } else if (e instanceof MulticastTree) { if (e != layer.multicastTrees.get(e.index)) throw new Net2PlanException ("Element " + e + " is not the same object as the one in netPlan object."); } else if (e instanceof Route) { if (e != layer.routes.get(e.index)) throw new Net2PlanException ("Element " + e + " is not the same object as the one in netPlan object."); } } } /** * <p>Checks if the {@code NetPlan} object is modifiable. When negative, an exception will be thrown.</p> * * @since 0.4.0 */ void checkIsModifiable() { if (!isModifiable) throw new UnsupportedOperationException(UNMODIFIABLE_EXCEPTION_STRING); } /** * <p>Checks if a set of links is valid for a given multicast demand. If it is not, an exception will be thrown. If it is valid, a map is returned with the * unique sequence of links in the tree, from the ingress node to each egress node of the multicast demand.</p> * * @param linkSet Sequence of links * @param demand Multicast demand * @return Map where the keys are nodes and the values are sequences of links (see description) * @see com.net2plan.interfaces.networkDesign.Node * @see com.net2plan.interfaces.networkDesign.Link * @see com.net2plan.interfaces.networkDesign.MulticastDemand */ Pair<Map<Node,List<Link>> , Set<Node>> checkMulticastTreeValidityForDemand(Set<Link> linkSet, MulticastDemand demand) { if (linkSet.isEmpty()) throw new Net2PlanException ("The multicast tree is empty"); checkInThisNetPlan(demand); final NetworkLayer layer = demand.layer; checkInThisNetPlanAndLayer(linkSet , demand.layer); Map<Node,List<Link>> pathToEgressNode = new HashMap<Node,List<Link>> (); Map<Link,Double> linkCost = new HashMap<Link,Double> (); for (Link link : layer.links) linkCost.put (link , (linkSet.contains (link))? 1 : Double.MAX_VALUE); Set<Link> actuallyTraversedLinks = new HashSet<Link> (); for (Node egressNode : demand.egressNodes) { final List<Link> seqLinks = GraphUtils.getShortestPath(nodes , layer.links , demand.ingressNode , egressNode , linkCost); if (seqLinks == null) throw new Net2PlanException ("No path to an end node"); pathToEgressNode.put(egressNode, seqLinks); actuallyTraversedLinks.addAll(seqLinks); } if (!linkSet.equals(actuallyTraversedLinks)) throw new Net2PlanException ("Some links in the link set provided are not traversed. The structure may not be a tree"); Set<Node> traversedNodes = new HashSet<Node> (); for (Link e : linkSet) { traversedNodes.add (e.originNode); traversedNodes.add (e.destinationNode); } if (traversedNodes.size() != linkSet.size() + 1) throw new Net2PlanException ("It is not a tree"); return Pair.of (pathToEgressNode,traversedNodes); } /** * <p>Checks if a sequence of links is valid, that is all the links follow a contiguous path from the demand ingress node to the egress node. If the sequence * is not valid, an exception is thrown.</p> * @param path Sequence of links * @param d Demand * @see com.net2plan.interfaces.networkDesign.Demand * @see com.net2plan.interfaces.networkDesign.Link */ void checkPathValidityForDemand(List<Link> path, Demand d) { checkInThisNetPlan(d); checkInThisNetPlanAndLayer(path , d.layer); checkContiguousPath (path , d.layer , d.ingressNode, d.egressNode); } /** * <p>Returns a deep copy of the current design.</p> * * @return Deep copy of the current design * @since 0.2.0 */ public NetPlan copy() { this.checkCachesConsistency(); NetPlan netPlan = new NetPlan(); netPlan.checkCachesConsistency(); netPlan.copyFrom(this); // System.out.println ("************** En el copy () *********************************************************"); this.checkCachesConsistency(); netPlan.checkCachesConsistency(); return netPlan; } /** * <p>Removes all information from the current {@code NetPlan} and copy the information from the input {@code NetPlan}.</p> * @param originNetPlan Network plan to be copied from */ public void copyFrom(NetPlan originNetPlan) { checkIsModifiable(); if (originNetPlan == this) return; if (originNetPlan == null) throw new Net2PlanException ("A NetPlan object must be provided"); this.attributes.clear(); this.attributes.putAll (originNetPlan.attributes); this.netPlan = this; this.layers = new ArrayList<NetworkLayer> (); this.nodes = new ArrayList<Node> (); this.srgs = new ArrayList<SharedRiskGroup> (); this.cache_nodesDown = new HashSet<Node> (); this.cache_id2NodeMap = new HashMap <Long,Node> (); this.cache_id2LayerMap = new HashMap <Long,NetworkLayer> (); this.cache_id2srgMap= new HashMap<Long,SharedRiskGroup> (); this.cache_id2LinkMap = new HashMap<Long,Link> (); this.cache_id2DemandMap = new HashMap<Long,Demand> (); this.cache_id2MulticastDemandMap = new HashMap<Long,MulticastDemand> (); this.cache_id2RouteMap = new HashMap<Long,Route> (); this.cache_id2MulticastTreeMap = new HashMap<Long,MulticastTree> (); this.cache_id2ProtectionSegmentMap = new HashMap<Long,ProtectionSegment> (); this.DEFAULT_ROUTING_TYPE = originNetPlan.DEFAULT_ROUTING_TYPE; this.isModifiable = true; this.networkDescription = originNetPlan.networkDescription; this.networkName = originNetPlan.networkName; this.nextElementId = originNetPlan.nextElementId; this.interLayerCoupling = new DirectedAcyclicGraph<NetworkLayer, DemandLinkMapping>(DemandLinkMapping.class); /* Create the new network elements, not all the fields filled */ for (Node originNode : originNetPlan.nodes) { Node newElement = new Node (this , originNode.id , originNode.index , originNode.nodeXYPositionMap.getX(), originNode.nodeXYPositionMap.getY(), originNode.name, originNode.attributes); cache_id2NodeMap.put(originNode.id, newElement); nodes.add (newElement); if (!originNode.isUp) cache_nodesDown.add (newElement); } for (SharedRiskGroup originSrg : originNetPlan.srgs) { SharedRiskGroup newElement = new SharedRiskGroup (this , originSrg.id , originSrg.index , null , null, originSrg.meanTimeToFailInHours , originSrg.meanTimeToRepairInHours , originSrg.attributes); cache_id2srgMap.put(originSrg.id, newElement); srgs.add (newElement); } for (NetworkLayer originLayer : originNetPlan.layers) { NetworkLayer newLayer = new NetworkLayer (this , originLayer.id , originLayer.index , originLayer.demandTrafficUnitsName , originLayer.description , originLayer.name , originLayer.linkCapacityUnitsName , originLayer.attributes); cache_id2LayerMap.put(originLayer.id, newLayer); layers.add (newLayer); if (originLayer.id == originNetPlan.defaultLayer.id) this.defaultLayer = newLayer; for (Demand originDemand : originLayer.demands) { Demand newElement = new Demand (this , originDemand.id , originDemand.index , newLayer , this.cache_id2NodeMap.get(originDemand.ingressNode.id) , this.cache_id2NodeMap.get(originDemand.egressNode.id) , originDemand.offeredTraffic , originDemand.attributes); cache_id2DemandMap.put(originDemand.id, newElement); newLayer.demands.add (newElement); } for (MulticastDemand originDemand : originLayer.multicastDemands) { Set<Node> newEgressNodes = new HashSet<Node> (); for (Node oldEgressNode : originDemand.egressNodes) newEgressNodes.add (this.cache_id2NodeMap.get(oldEgressNode.id)); MulticastDemand newElement = new MulticastDemand (this , originDemand.id , originDemand.index , newLayer , this.cache_id2NodeMap.get(originDemand.ingressNode.id) , newEgressNodes , originDemand.offeredTraffic , originDemand.attributes); cache_id2MulticastDemandMap.put(originDemand.id, newElement); newLayer.multicastDemands.add (newElement); } for (Link originLink : originLayer.links) { Link newElement = new Link (this , originLink.id , originLink.index , newLayer , this.cache_id2NodeMap.get(originLink.originNode.id) , this.cache_id2NodeMap.get(originLink.destinationNode.id) , originLink.lengthInKm , originLink.propagationSpeedInKmPerSecond , originLink.capacity , originLink.attributes); cache_id2LinkMap.put(originLink.id, newElement); newLayer.links.add (newElement); } for (Route originRoute : originLayer.routes) { List<Link> newSeqLinksRealPath = new LinkedList<Link> (); for (Link oldLink : originRoute.seqLinksRealPath) { Link newLink = this.cache_id2LinkMap.get(oldLink.id); newSeqLinksRealPath.add (newLink); } Route newElement = new Route (this , originRoute.id , originRoute.index , cache_id2DemandMap.get(originRoute.demand.id) , newSeqLinksRealPath , originRoute.attributes); newElement.carriedTraffic = originRoute.carriedTraffic; newElement.carriedTrafficIfNotFailing = originRoute.carriedTrafficIfNotFailing; newElement.occupiedLinkCapacity = originRoute.occupiedLinkCapacity; newElement.occupiedLinkCapacityIfNotFailing = originRoute.occupiedLinkCapacityIfNotFailing; cache_id2RouteMap.put(originRoute.id, newElement); newLayer.routes.add (newElement); } for (MulticastTree originTree : originLayer.multicastTrees) { Set<Link> newSetLinks = new HashSet<Link> (); for (Link oldLink : originTree.linkSet) newSetLinks.add (this.cache_id2LinkMap.get(oldLink.id)); MulticastTree newElement = new MulticastTree (this , originTree.id , originTree.index , cache_id2MulticastDemandMap.get(originTree.demand.id) , newSetLinks , originTree.attributes); cache_id2MulticastTreeMap.put(originTree.id, newElement); newLayer.multicastTrees.add (newElement); newElement.carriedTraffic = originTree.carriedTraffic; newElement.occupiedLinkCapacity = originTree.occupiedLinkCapacity; newElement.carriedTrafficIfNotFailing = originTree.carriedTrafficIfNotFailing; newElement.occupiedLinkCapacityIfNotFailing = originTree.occupiedLinkCapacityIfNotFailing; } for (ProtectionSegment originSegment : originLayer.protectionSegments) { List<Link> newSeqLinks = new LinkedList<Link> (); for (Link oldLink : originSegment.seqLinks) newSeqLinks.add (this.cache_id2LinkMap.get(oldLink.id)); ProtectionSegment newElement = new ProtectionSegment (this , originSegment.id , originSegment.index , newSeqLinks , originSegment.capacity , originSegment.attributes); cache_id2ProtectionSegmentMap.put(originSegment.id, newElement); newLayer.protectionSegments.add (newElement); } } /* Copy the rest of the fields */ for (Node newNode : this.nodes) newNode.copyFrom (originNetPlan.nodes.get(newNode.index)); for (SharedRiskGroup newSrg : this.srgs) newSrg.copyFrom (originNetPlan.srgs.get(newSrg.index)); for (NetworkLayer newLayer : this.layers) newLayer.copyFrom (originNetPlan.layers.get(newLayer.index)); this.interLayerCoupling = new DirectedAcyclicGraph<NetworkLayer, DemandLinkMapping>(DemandLinkMapping.class); for (NetworkLayer layer : originNetPlan.interLayerCoupling.vertexSet()) this.interLayerCoupling.addVertex(this.netPlan.getNetworkLayerFromId(layer.id)); for (DemandLinkMapping mapping : originNetPlan.interLayerCoupling.edgeSet()) { if (mapping.isEmpty()) throw new RuntimeException ("Bad"); DemandLinkMapping newMapping = new DemandLinkMapping(); for (Entry<Demand,Link> originEntry : mapping.getDemandMap().entrySet()) newMapping.put (this.netPlan.getDemandFromId(originEntry.getKey().id) , this.netPlan.getLinkFromId(originEntry.getValue().id)); for (Entry<MulticastDemand,Set<Link>> originEntry : mapping.getMulticastDemandMap().entrySet()) { Set<Link> newSetLink = new HashSet<Link> (); for (Link originLink : originEntry.getValue()) newSetLink.add (this.netPlan.getLinkFromId(originLink.id)); newMapping.put (this.netPlan.getMulticastDemandFromId(originEntry.getKey().id) , newSetLink); } try { this.interLayerCoupling.addDagEdge(newMapping.getDemandSideLayer () , newMapping.getLinkSideLayer (), newMapping); } catch (Exception e) { throw new RuntimeException ("Bad: " + e); } } if (ErrorHandling.isDebugEnabled()) this.checkCachesConsistency(); } /** * <p>Returns the values of a given attribute for all the provided network elements.</p> * @param collection Collection of network elements * @param attribute Attribute name * @return Map with the value of each attribute per network element (value may be {@code null} if not defined * @see com.net2plan.interfaces.networkDesign.NetworkElement */ public static Map<NetworkElement,String> getAttributes (Collection<? extends NetworkElement> collection , String attribute) { Map<NetworkElement,String> attributes = new HashMap<NetworkElement,String> (); for (NetworkElement e : collection) attributes.put (e , e.getAttribute (attribute)); return attributes; } /** * <p>Returns the values of a given attribute for all the provided network elements, as a {@code DoubleMatrix1D} vector.</p> * @param collection Collection of network elements * @param attribute Attribute name * @param defaultValue If an element has value for the attribute, or it is not a double (it fails in the {@code Double.parseDouble} conversion), then this value is set * @return array with one element per {@code NetworkElement}, in the same order as the input {@code Collection}. * @see com.net2plan.interfaces.networkDesign.NetworkElement */ public static DoubleMatrix1D getAttributeValues (Collection<? extends NetworkElement> collection , String attributeName , double defaultValue) { DoubleMatrix1D res = DoubleFactory1D.dense.make(collection.size()); int counter = 0; for (NetworkElement e : collection) { double val = defaultValue; String value = e.getAttribute(attributeName); if (value != null) try { val = Double.parseDouble(value); } catch (Exception ex) {} res.set(counter ++ , val); } return res; } /** * <p>Returns the demand with the given index.</p> * @param index Demand index * @param optionalLayerParameter Network layer (optional) * @return The demand with the given index (or {@code null} if nonexistent, index lower than 0 or greater than the number of elements minus one) * @see com.net2plan.interfaces.networkDesign.Demand */ public Demand getDemand (int index , NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter (optionalLayerParameter); if ((index < 0) || (index > layer.demands.size () -1)) return null; else return layer.demands.get(index); } /** * <p>Returns the demand with the given unique identifier.</p> * @param uid Demand unique id * @return The demand with the given unique id (or {@code null} if nonexistent) * @see com.net2plan.interfaces.networkDesign.Demand */ public Demand getDemandFromId (long uid) { return cache_id2DemandMap.get(uid); } /** * <p>Returns the array of demand unique ids for the given layer (i-th position, corresponds to index i). If no layer is provided, the default layer is used.</p> * @param optionalLayerParameter Network layer (optional) * @return ArrayList of demand ids for the given layer (or the default layer if no input was provided) * @see com.net2plan.interfaces.networkDesign.Demand */ public ArrayList<Long> getDemandIds (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); ArrayList<Long> res = new ArrayList<Long> (); for (Demand e : layer.demands) res.add (e.id); return res; } /** * <p>Returns the array of demands for the given layer (i-th position, corresponds to index i). If no layer is provided, the default layer is used.</p> * @param optionalLayerParameter Network layer (optional) * @return List of demands for the given layer (or the default layer if no input was provided) * @see com.net2plan.interfaces.networkDesign.Demand */ public List<Demand> getDemands (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); return (List<Demand>) Collections.unmodifiableList(layer.demands); } /** * <p>Returns the demands that have blocked traffic in the given layer. If no layer is provided, the default layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return List of demands with blocked traffic * @see com.net2plan.interfaces.networkDesign.Demand */ public List<Demand> getDemandsBlocked (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); List<Demand> res = new LinkedList<Demand> (); for (Demand d : layer.demands) if (d.isBlocked()) res.add (d); return res; } /** * <p>Returns the set of unicast demands that are coupled.</p> * @param optionalLayerParameter Network layer (optional) * @return {@code Set} of unicast demands that have blocked traffic for the given layer (or the defaukt layer if no input was provided) */ public Set<Demand> getDemandsCoupled (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); Set<Demand> res = new HashSet<Demand> (); for (Demand demand : layer.demands) if (demand.coupledUpperLayerLink != null) res.add (demand); return res; } /** * <p>Returns the total blocked traffic, summing up all the unicast demands, in the given layer. If no layer is provided, the default layer is assumed.</p> * * @param optionalLayerParameter Network layer (optional) * @return Total blocked trafic */ public double getDemandTotalBlockedTraffic(NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); double accum = 0; for (Demand d : layer.demands) accum += Math.max(0 , d.offeredTraffic - d.carriedTraffic); return accum; } /** * <p>Returns the total carried traffic, summing up for all the unicast demands, in the given layer. If no layer is provided, the default layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return Total carried traffic */ public double getDemandTotalCarriedTraffic(NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); double accum = 0; for (Demand d : layer.demands) accum += d.carriedTraffic; return accum; } /** * <p>Returns the total offered traffic, summing up for all the unicast demands, in the given layer. If no layer is provided, the default layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return Total offered traffic */ public double getDemandTotalOfferedTraffic(NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); double accum = 0; for (Demand d : layer.demands) accum += d.offeredTraffic; return accum; } /** * <p>Returns the name of the traffic units of the demands of the given layer. If no layer is provided, the default layer is assumed.</p> * * @param optionalLayerParameter Network layer (optional) * @return {@code String} with the traffic units name of the demands */ public String getDemandTrafficUnitsName (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); return layer.demandTrafficUnitsName; } /** * <p>Returns the traffic that is carried using a forwarding rule, in the given layer. If no layer is provided, the default layer is assumed.</p> * * <p><b>Important</b>: Routing type must be {@link com.net2plan.utils.Constants.RoutingType#HOP_BY_HOP_ROUTING HOP_BY_HOP_ROUTING}.</p> * @param demand Outgoing demand * @param link Link * @return Carried traffic by the given link from the given demand using a forwarding rule */ public double getForwardingRuleCarriedTraffic(Demand demand , Link link) { checkInThisNetPlan(demand); checkInThisNetPlanAndLayer(link , demand.layer); demand.layer.checkRoutingType(RoutingType.HOP_BY_HOP_ROUTING); return demand.layer.forwardingRules_x_de.get(demand.index,link.index); } /** * <p>Returns the forwarding rules for the given layer. If no layer is provided, the default layer is assumed.</p> * * <p><b>Important</b>: Routing type must be {@link com.net2plan.utils.Constants.RoutingType#HOP_BY_HOP_ROUTING HOP_BY_HOP_ROUTING}.</p> * @param optionalLayerParameter Network layer (optional) * @return The forwarding rules as a map of splitting factor (value) per demand and link (key) * @see com.net2plan.utils.Pair */ public Map<Pair<Demand,Link>,Double> getForwardingRules (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); layer.checkRoutingType(RoutingType.HOP_BY_HOP_ROUTING); Map<Pair<Demand,Link>,Double> res = new HashMap<Pair<Demand,Link>,Double> (); IntArrayList ds = new IntArrayList (); IntArrayList es = new IntArrayList (); DoubleArrayList vals = new DoubleArrayList (); layer.forwardingRules_f_de.getNonZeros(ds,es,vals); for (int cont = 0 ; cont < ds.size () ; cont ++) res.put (Pair.of (layer.demands.get(ds.get(cont)) , layer.links.get(es.get(cont))) , vals.get(cont)); return res; } /** * <p>Returns the splitting factor of the forwarding rule of the given demand and link. If no layer is provided, default layer is assumed.</p> * @param demand Outgoing demand * @param link Link * @param optionalLayerParameter Network layer (optional) * @return The splitting factor */ public double getForwardingRuleSplittingFactor (Demand demand , Link link , NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); checkInThisNetPlanAndLayer(demand , layer); checkInThisNetPlanAndLayer(link , layer); layer.checkRoutingType(RoutingType.HOP_BY_HOP_ROUTING); return layer.forwardingRules_f_de.get(demand.index,link.index); } /** * <p>Returns the network layer with the given unique identifier.</p> * @param index Network layer index * @return The network layer with the given index ({@code null} if it does not exist) */ public NetworkLayer getNetworkLayer (int index) { if ((index < 0) || (index > layers.size () -1)) return null; else return layers.get(index); } /** * <p>Returns the network layer with the given name.</p> * @param name Network layer name * @return The network layer with the given name ({@code null} if it does not exist) */ public NetworkLayer getNetworkLayer (String name) { for (NetworkLayer layer : layers) if (layer.name.equals(name)) return layer; return null; } /** * <p>Returns the node with the given index.</p> * @param index Node index * @return The node with the given index ({@code null} if it does not exist, index iss lesser than zero or greater than the number of elements minus one) */ public Node getNode (int index) { if ((index < 0) || (index > nodes.size () -1)) return null; else return nodes.get(index); } /** * <p>Returns the link with the given index in the given layer. If no layer is provided, default layer is assumed.</p> * @param index Link index * @param optionalLayerParameter Network layer (optional) * @return Link with the given index or {@code null} if it does not exist, index islower than 0, or greater than the number of links minus one */ public Link getLink (int index , NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); if ((index < 0) || (index > layer.links.size () -1)) return null; else return layer.links.get(index); } /** * <p>Returns the link with the given unique identifier.</p> * @param uid Link unique id * @return Link with the given id, or {@code null} if it does not exist */ public Link getLinkFromId (long uid) { checkAttachedToNetPlanObject(); return cache_id2LinkMap.get(uid); } /** * <p>Returns the name of the capacity units of the links of the given layer. If no layer is provided, the default layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return The name of capacity units */ public String getLinkCapacityUnitsName (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); return layer.linkCapacityUnitsName; } // /** // * <p>Returns a map where keys are the unique id of network elements and the values are a pair of uid representing the end nodes.</p> // * @param links Network elements // * @return A map with the end nodes unique ids (values) of each network element (key) // * @see com.net2plan.utils.Pair // */ // public Map<Long,Pair<Long,Long>> getLinkIdMap (Collection<? extends NetworkElement> links) // { // checkInThisNetPlan(links); // Map<Long,Pair<Long,Long>> map = new HashMap<Long,Pair<Long,Long>> (); // if (links.isEmpty()) return map; // if (links.iterator().next() instanceof Link) // for (Link e : (List<Link>) links) // { // map.put(e.id, Pair.of(e.originNode.id, e.destinationNode.id)); // } // else if (links.iterator().next() instanceof Demand) // for (Demand e : (List<Demand>) links) // { // map.put(e.id, Pair.of(e.ingressNode.id, e.egressNode.id)); // } // else if (links.iterator().next() instanceof Route) // for (Route e : (List<Route>) links) // { // map.put(e.id, Pair.of(e.ingressNode.id, e.egressNode.id)); // } // else throw new Net2PlanException ("Only can make id link maps for links, demands, routes and protection segments"); // return map; // } /** * <p>Returns the array of link ids for the given layer (i-th position, corresponds to index i). If no layer is provided, the default layer is assumed.</p> * @param optionalLayerParameter Network layer (optional * @return Array of link ids */ public ArrayList<Long> getLinkIds (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); ArrayList<Long> res = new ArrayList<Long> (); for (Link e : layer.links) res.add (e.id); return res; } /** * <p>Return a list of all the links in the given layer. If no layer is provided, the default layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return All the links for the given (or default) layer */ public List<Link> getLinks (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); return (List<Link>) Collections.unmodifiableList(layer.links); } /** * <p>Returns the set of links that are a bottleneck, i.e the fraction of occupied capacity respect to the total (including the capacities in the protection segments) * is highest. If no layer is provided, the default layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return The {@code Set} of bottleneck links */ public Set<Link> getLinksAreBottleneck (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); double maxRho = 0; final double PRECISION_FACTOR = Double.parseDouble(Configuration.getOption("precisionFactor")); Set<Link> res = new HashSet<Link> (); for (Link e : layer.links) if (Math.abs (e.occupiedCapacitySummingRoutesAndCarriedTrafficByProtectionSegments / e.capacity - maxRho) < PRECISION_FACTOR) res.add (e); else if (e.occupiedCapacitySummingRoutesAndCarriedTrafficByProtectionSegments / e.capacity > maxRho) { maxRho = e.occupiedCapacitySummingRoutesAndCarriedTrafficByProtectionSegments / e.capacity; res.clear (); res.add (e); } return res; } /** * <p>Returns the set of links that have zero capacity in the given layer. If no layer is provided, the default layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return The {@code Set} of links with zero capacity */ public Set<Link> getLinksWithZeroCapacity (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); final double PRECISION_FACTOR = Double.parseDouble(Configuration.getOption("precisionFactor")); Set<Link> res = new HashSet<Link> (); for (Link e : layer.links) if (e.capacity < PRECISION_FACTOR) res.add (e); return res; } /** * <p>Returns the set of links that are coupled to a multicast demand in the given layer. If no layer is provided, the default layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return The {@code Set} of links coupled to a multicast demand * @see com.net2plan.interfaces.networkDesign.MulticastDemand */ public Set<Link> getLinksCoupledToMulticastDemands (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); Set<Link> res = new HashSet<Link> (); for (Link link : layer.links) if (link.coupledLowerLayerMulticastDemand != null) res.add (link); return res; } /** * <p>Returns the set of links that are couple to a unicast demand in the given layer. If no layer is provided, the default layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return The {@code Set} of links coupled to a unicast demand * @see com.net2plan.interfaces.networkDesign.Demand */ public Set<Link> getLinksCoupledToUnicastDemands (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); Set<Link> res = new HashSet<Link> (); for (Link link : layer.links) if (link.coupledLowerLayerDemand != null) res.add (link); return res; } /** * <p>Returns the set of links that are down in the given layer. If no layer is provided, the default layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return The {@code Set} of links that are down */ public Set<Link> getLinksDown (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); return Collections.unmodifiableSet(layer.cache_linksDown); } /** * <p>Returns the set of links that are down in all layers.</p> * @return The {@code Set} of links down */ public Set<Link> getLinksDownAllLayers () { Set<Link> res = new HashSet<Link> (); for (NetworkLayer layer : layers) res.addAll (layer.cache_linksDown); return res; } /** * <p>Returns the set of links that are up in the given layer. If no layer is provided, the default layer is assumed.</p> * @param optionalLayerParameter Network layer )optional) * @return The {@code Set} of links that are up */ public Set<Link> getLinksUp (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); Set<Link> res = new HashSet<Link> (layer.links); res.removeAll (layer.cache_linksDown); return res; } /** * <p>Returns the set of links that are up in all layers.</p> * @return The {@code Set} of links that are up */ public Set<Link> getLinksUpAllLayers () { Set<Link> res = new HashSet<Link> (); for (NetworkLayer layer : layers) res.addAll (getLinksUp (layer)); return res; } /** * <p>Returns the set of links oversuscribed: the total occupied capacity (including the traffic in the protection segments) exceeds the link capacity * (including the reserved capacity by the protection segments). If no layer is provided, the default layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return The {@code Set} of oversubscribed links */ public Set<Link> getLinksOversubscribed (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); Set<Link> res = new HashSet<Link> (); for (Link e : layer.links) if (e.capacity < e.occupiedCapacitySummingRoutesAndCarriedTrafficByProtectionSegments) res.add (e); return res; } /** * <p>Returns the demand-link incidence matrix (a <i>D</i>x<i>E</i> matrix in * which an element <i>&delta;<sub>de</sub></i> is equal to the number of * times which traffic routes carrying traffic from demand <i>d</i> traverse * link <i>e</i>). If no layer is provided, the default layer is assumed.</p> * * @param optionalLayerParameter Network layer (optional) * @return The demand-link incidence matrix */ public DoubleMatrix2D getMatrixDemand2LinkAssignment(NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); DoubleMatrix2D delta_dr = getMatrixDemand2RouteAssignment(layer); DoubleMatrix2D delta_er = getMatrixLink2RouteAssignment(layer); return delta_dr.zMult(delta_er.viewDice(), null); } /** * <p>Returns the route-srg incidence matrix (an <i>R</i>x<i>S</i> matrix in which an element <i>&delta;<sub>rs</sub></i> equals 1 if route <i>r</i> * fails when SRG <i>s</i> is affected. If no layer is provided, the default layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return The route-srg incidence matrix */ public DoubleMatrix2D getMatrixRoute2SRGAffecting (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); DoubleMatrix2D A_rs = DoubleFactory2D.sparse.make (layer.routes.size () , srgs.size ()); for (Route r : layer.routes) for (Link e : r.seqLinksRealPath) for (SharedRiskGroup srg : e.cache_srgs) A_rs.set (r.index , srg.index , 1.0); return A_rs; } /** * <p>Returns the protection segment-srg incidence matrix (an <i>P</i>x<i>S</i> matrix in which an element <i>&delta;<sub>ps</sub></i> equals 1 if protection segment <i>p</i> * fails when SRG <i>s</i> is affected. If no layer is provided, the default layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return The protection segment-srg incidence matrix */ public DoubleMatrix2D getMatrixProtectionSegment2SRGAffecting (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); DoubleMatrix2D A_rs = DoubleFactory2D.sparse.make (layer.protectionSegments.size () , srgs.size ()); for (ProtectionSegment r : layer.protectionSegments) for (Link e : r.seqLinks) for (SharedRiskGroup srg : e.cache_srgs) A_rs.set (r.index , srg.index , 1.0); return A_rs; } /** * <p>Returns the multicast tree-srg incidence matrix (an <i>T</i>x<i>S</i> matrix in which an element <i>&delta;<sub>ts</sub></i> equals 1 when multicast tree <i>t</i> * fails when SRG <i>s</i> is affected. If no layer is provided, the default layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return The multicast tree-srg incidence matrix */ public DoubleMatrix2D getMatrixMulticastTree2SRGAffecting (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); DoubleMatrix2D A_rs = DoubleFactory2D.sparse.make (layer.multicastTrees.size () , srgs.size ()); for (MulticastTree r : layer.multicastTrees) for (Link e : r.linkSet) for (SharedRiskGroup srg : e.cache_srgs) A_rs.set (r.index , srg.index , 1.0); return A_rs; } /** * <p>Returns the multicast demand-link incidence matrix (a <i>D</i>x<i>E</i> matrix in * which an element <i>&delta;<sub>de</sub></i> is equal to the number of * times which multicast trees carrying traffic from demand <i>d</i> traverse * link <i>e</i>). If no layer is provided, the default layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return The multicast demand-link incidence matrix */ public DoubleMatrix2D getMatrixMulticastDemand2LinkAssignment(NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); DoubleMatrix2D delta_dr = getMatrixMulticastDemand2MulticastTreeAssignment(layer); DoubleMatrix2D delta_er = getMatrixLink2MulticastTreeAssignment(layer); return delta_dr.zMult(delta_er.viewDice(), null); } /** * <p>Returns the demand-link incidence matrix (<i>D</i>x<i>E</i> in which an element <i>&delta;<sub>de</sub></i> is equal to the amount of traffic of each demand carried in each link). Rows * and columns are in increasing order of demand and link identifiers, respectively. If no layer is provided, the default layer is assumed</p> * * <p><b>Important</b>: Routing type must be {@link com.net2plan.utils.Constants.RoutingType#HOP_BY_HOP_ROUTING HOP_BY_HOP_ROUTING}.</p> * @param optionalLayerParameter Network layer (optional) * @return Splitting ratio matrix */ public DoubleMatrix2D getMatrixDemand2LinkTrafficCarried(NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); if (layer.routingType == RoutingType.HOP_BY_HOP_ROUTING) return layer.forwardingRules_x_de.copy(); DoubleMatrix2D x_de = DoubleFactory2D.sparse.make (layer.demands.size () , layer.links.size ()); for (Route r : layer.routes) for (Link e : r.seqLinksRealPath) x_de.set (r.demand.index , e.index , x_de.get(r.demand.index , e.index) + r.carriedTraffic); return x_de; } public DoubleMatrix2D getMatrixDestination2LinkTrafficCarried(NetworkLayer ... optionalLayerParameter) { DoubleMatrix2D x_de = getMatrixDemand2LinkTrafficCarried(optionalLayerParameter); return this.getMatrixNodeDemandIncomingIncidence().zMult(x_de , null); } /** * <p>Returns the demand-route incidence matrix (a <i>D</i>x<i>R</i> matrix in * which an element <i>&delta;<sub>dr</sub></i> is equal to 1 if traffic * route <i>r</i> is able to carry traffic from demand <i>d</i>). If no layer is provided, the default layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return The demand-route incidence matrix */ public DoubleMatrix2D getMatrixDemand2RouteAssignment (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); layer.checkRoutingType(RoutingType.SOURCE_ROUTING); int D = layer.demands.size (); int R = layer.routes.size (); DoubleMatrix2D delta_dr = DoubleFactory2D.sparse.make(D, R); for (Route r : layer.routes) delta_dr.set (r.demand.index , r.index , 1); return delta_dr; } /** * <p>Returns the multicast demand-multicast tree incidence matrix (a <i>D</i>x<i>T</i> matrix in * which an element <i>&delta;<sub>dt</sub></i> is equal to 1 if multicast tree <i>t</i> is able to carry traffic from multicast demand <i>d</i>). * If no layer is provided, the default layer is * assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return The multicast demand-multicast tree incidence matrix */ public DoubleMatrix2D getMatrixMulticastDemand2MulticastTreeAssignment (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); int D = layer.multicastDemands.size (); int T = layer.multicastTrees.size (); DoubleMatrix2D delta_dt = DoubleFactory2D.sparse.make(D, T); for (MulticastTree t : layer.multicastTrees) delta_dt.set (t.demand.index , t.index , 1); return delta_dt; } /** * <p>Returns the splitting ratio matrix (fractions of traffic entering a node from * demand 'd', leaving that node through link 'e'). Rows and columns are in * increasing order of demand and link identifiers, respectively. If no layer is provided, the default layer is assumed</p> * * <p><b>Important</b>: Routing type must be {@link com.net2plan.utils.Constants.RoutingType#HOP_BY_HOP_ROUTING HOP_BY_HOP_ROUTING}.</p> * @param optionalLayerParameter Network layer (optional) * @return Splitting ratio matrix */ public DoubleMatrix2D getMatrixDemandBasedForwardingRules (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); if (layer.routingType == RoutingType.HOP_BY_HOP_ROUTING) return layer.forwardingRules_f_de.copy (); else return GraphUtils.convert_xp2xde(layer.links , layer.demands , layer.routes); } /** * <p>A destination-based routing in the form of fractions <i>f<sub>te</sub></i> (fraction of the traffic targeted to node <i>t</i> that arrives (or is generated in) node <i>a</i>(<i>e</i>) * (the initial node of link <i>e</i>), that is forwarded through link <i>e</i>). If no layer is provided, the default layer is assumed.</p> * @param optionalLayer Network layer (optional) * @return A destination-based routing from a given network design */ public DoubleMatrix2D getMatrixDestinationBasedForwardingRules (NetworkLayer ... optionalLayer) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayer); DoubleMatrix2D x_te = null; if (layer.routingType == RoutingType.HOP_BY_HOP_ROUTING) x_te = GraphUtils.convert_xde2xte(nodes ,layer.links , layer.demands , layer.forwardingRules_f_de); else x_te = GraphUtils.convert_xp2xte(nodes,layer.links,layer.demands,layer.routes); return GraphUtils.convert_xte2fte(nodes , layer.links , x_te); } /** * Returns the link-protection segment assignment matrix (an <i>E</i>x<i>R</i> matrix in * which an element <i>&delta;<sub>ep</sub></i> is equal to the number of * times which protection segment <i>r</i> traverses link <i>e</i>). * @param optionalLayerParameter Network layer (optional) * @return The link-protection segment assignment matrix */ public DoubleMatrix2D getMatrixLink2ProtectionSegmentAssignment (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); layer.checkRoutingType(RoutingType.SOURCE_ROUTING); DoubleMatrix2D delta_er = DoubleFactory2D.sparse.make(layer.links.size(), layer.protectionSegments.size()); for (ProtectionSegment r : layer.protectionSegments) for (Link e : r.seqLinks) delta_er.set (e.index , r.index , delta_er.get (e.index , r.index) + 1); return delta_er; } /** *<p>Returns the link-route incidence matrix (an <i>E</i>x<i>R</i> matrix in * which an element <i>&delta;<sub>ep</sub></i> is equal to the number of * times which traffic route <i>r</i> traverses link <i>e</i>). If no layer is provided, the default layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return The link-route incidene matrix */ public DoubleMatrix2D getMatrixLink2RouteAssignment (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); layer.checkRoutingType(RoutingType.SOURCE_ROUTING); int E = layer.links.size(); int R = layer.routes.size (); DoubleMatrix2D delta_er = DoubleFactory2D.sparse.make(E, R); for (Route r : layer.routes) for (Link e : r.seqLinksRealPath) delta_er.set (e.index , r.index , delta_er.get (e.index , r.index) + 1); return delta_er; } /** * <p>Returns the link-multicast incidence matrix (an <i>E</i>x<i>T</i> matrix in which an element <i>&delta;<sub>et</sub></i> is equal * to the number of times a multicast tree <i>t</i> traverse link <i>e</i>. If no layer is provided, the default layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return The link-multicast tree incidence matrix */ public DoubleMatrix2D getMatrixLink2MulticastTreeAssignment (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); int E = layer.links.size(); int T = layer.multicastTrees.size (); DoubleMatrix2D delta_et = DoubleFactory2D.sparse.make(E, T); for (MulticastTree t : layer.multicastTrees) for (Link e : t.linkSet) delta_et.set (e.index , t.index , delta_et.get (e.index , t.index) + 1); return delta_et; } /** * <p>Returns the link-srg assignment matrix (an <i>E</i>x<i>S</i> matrix in which an element <i>&delta;<sub>es</sub></i> equals 1 if link <i>e</i> * fails when SRG <i>s</i> is affected. If no layer is provided, the default layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return The link-srg incidence matrix */ public DoubleMatrix2D getMatrixLink2SRGAssignment (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); DoubleMatrix2D delta_es = DoubleFactory2D.sparse.make (layer.links.size() , srgs.size()); for (SharedRiskGroup s : srgs) { for (Link e : s.links) if (e.layer.equals (layer)) delta_es.set (e.index , s.index , 1); for (Node n : s.nodes) { for (Link e : n.cache_nodeIncomingLinks) if (e.layer.equals(layer)) delta_es.set (e.index , s.index , 1); for (Link e : n.cache_nodeOutgoingLinks) if (e.layer.equals(layer)) delta_es.set (e.index , s.index , 1); } } return delta_es; } /** * <p>Returns the multicast demand-link incidence matrix (<i>D</i>x<i>E</i> in which an element <i>&delta;<sub>de</sub></i> is equal to the amount of traffic of * each multicast demand carried in each link). Rows * and columns are in increasing order of demand and link identifiers, respectively. If no layer is provided, the default layer is assumed</p> * * <p><b>Important</b>: Routing type must be {@link com.net2plan.utils.Constants.RoutingType#HOP_BY_HOP_ROUTING HOP_BY_HOP_ROUTING}.</p> * @param optionalLayerParameter Network layer (optional) * @return Splitting ratio matrix */ public DoubleMatrix2D getMatrixMulticastDemand2LinkTrafficCarried(NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); DoubleMatrix2D x_de = DoubleFactory2D.sparse.make (layer.multicastDemands.size () , layer.links.size ()); for (MulticastTree t : layer.multicastTrees) for (Link e : t.linkSet) x_de.set (t.demand.index , e.index , x_de.get(t.demand.index , e.index) + t.carriedTraffic); return x_de; } /** * <p>Returns the <i>N</i>x<i>N</i> Euclidean distance matrix (derived * from node coordinates), where <i>N</i> is the number of nodes within the network.</p> * @return The Euclidean distance matrix */ public DoubleMatrix2D getMatrixNode2NodeEuclideanDistance () { int N = nodes.size(); DoubleMatrix2D out = DoubleFactory2D.dense.make(N, N); for(Node node_1 : nodes) { for (Node node_2 : nodes) { if (node_1.index >= node_2.index) continue; double physicalDistance = getNodePairEuclideanDistance(node_1, node_2); out.setQuick(node_1.index, node_2.index, physicalDistance); out.setQuick(node_2.index, node_1.index, physicalDistance); } } return out; } /** * <p>Returns the link-link bidirectionality matrix (a <i>E</i>x<i>E</i> matrix where the element <i>&delta;<sub>ee'</sub></i> equals 1 when each position <i>e</i> and <i>e'</i> represent a bidirectional * link at the given layer. If no layer is provided, default layer is assumed</p> * @param optionalLayerParameter Network layer (optional) * @return The link-link bidirectionality matrix */ public DoubleMatrix2D getMatrixLink2LinkBidirectionalityMatrix (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); final int E = layer.links.size(); DoubleMatrix2D out = DoubleFactory2D.dense.make(E, E); for(Link e_1 : layer.links) { final String idBidirPair_st = e_1.getAttribute(KEY_STRING_BIDIRECTIONALCOUPLE); if (idBidirPair_st == null) throw new Net2PlanException ("Some links are not bidirectional. Use this method for networks created using addLinkBidirectional"); final long idBidirPair = Long.parseLong (idBidirPair_st); final Link linkPair = netPlan.getLinkFromId(idBidirPair); if (linkPair == null) throw new Net2PlanException ("Some links are not bidirectional."); if ((linkPair.getOriginNode() != e_1.getDestinationNode()) ||(linkPair.getDestinationNode() != e_1.getOriginNode())) throw new Net2PlanException ("Some links are not bidirectional."); out.set(e_1.getIndex () , linkPair.getIndex () , 1.0); out.set(linkPair.getIndex () , e_1.getIndex () , 1.0); } return out; } /** * <p>Returns the <i>N</i>x<i>N</i> Haversine distance matrix (derived * from node coordinates, where 'xCoord' is equal to longitude and 'yCoord' * is equal to latitude), where <i>N</i> is the number of nodes within the network.</p> * * @return Haversine distance matrix * @see <a href="http://www.movable-type.co.uk/scripts/latlong.html">Calculate distance, bearing and more between Latitude/Longitude points</a> */ public DoubleMatrix2D getMatrixNode2NodeHaversineDistanceInKm () { int N = nodes.size(); DoubleMatrix2D out = DoubleFactory2D.dense.make(N, N); for(Node node_1 : nodes) { for (Node node_2 : nodes) { if (node_1.index >= node_2.index) continue; double physicalDistance = getNodePairHaversineDistanceInKm(node_1, node_2); out.setQuick(node_1.index, node_2.index, physicalDistance); out.setQuick(node_2.index, node_1.index, physicalDistance); } } return out; } /** * <p>Returns the traffic matrix, where rows and columns represent the ingress * node and the egress node, respectively, in increasing order of identifier. If no layer is provided, the default layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return The traffic matrix */ public DoubleMatrix2D getMatrixNode2NodeOfferedTraffic(NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); int N = nodes.size(); DoubleMatrix2D trafficMatrix = DoubleFactory2D.dense.make(N, N); for (Demand d : layer.demands) trafficMatrix.setQuick(d.ingressNode.index, d.egressNode.index, trafficMatrix.get(d.ingressNode.index, d.egressNode.index) + d.offeredTraffic); return trafficMatrix; } /** * <p>Returns a <i>N</i>x<i>N</i> matrix where each position accounts from the humber of demands that node <i>i</i> (row) as ingress node and <i>j</i> (column) as egress node. * If no layer is provided, the default layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return Adjacency matrix */ public DoubleMatrix2D getMatrixNodeDemandAdjacency (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); int N = nodes.size (); DoubleMatrix2D delta_nn = DoubleFactory2D.sparse.make(N , N); for (Demand d : layer.demands) delta_nn.set (d.ingressNode.index , d.egressNode.index , delta_nn.get (d.ingressNode.index , d.egressNode.index) + 1); return delta_nn; } /** * <p>Returns a <i>N</i>x<i>N</i> matrix where each position accounts from the humber of multicast demands that node <i>i</i> (row) as ingress node and <i>j</i> (column) as an egress node. * If no layer is provided, the default layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return Adjacency matrix */ public DoubleMatrix2D getMatrixNodeMulticastDemandAdjacency (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); int N = nodes.size (); DoubleMatrix2D delta_nn = DoubleFactory2D.sparse.make(N , N); for (MulticastDemand d : layer.multicastDemands) for (Node egressNode : d.egressNodes) delta_nn.set (d.ingressNode.index , egressNode.index , delta_nn.get (d.ingressNode.index , egressNode.index) + 1); return delta_nn; } /** * <p>Returns the node-demand incidence matrix (a <i>N</i>x<i>D</i> in which an element <i>&delta;<sub>nd</sub></i> equals 1 if <i>n</i> is the ingress node of <i>d</i>, * -1 if <i>n</i> is the egress node of <i>d</i> and 0 otherwise). * If no layer is provided, the default layer is assumed.</p> * @param optionalLayerParameter Network layer * @return The node-demand incidence matrix */ public DoubleMatrix2D getMatrixNodeDemandIncidence (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); int N = nodes.size (); int D = layer.demands.size (); DoubleMatrix2D delta_nd = DoubleFactory2D.sparse.make(N , D); for (Demand d : layer.demands) { delta_nd.set (d.ingressNode.index , d.index , 1); delta_nd.set (d.egressNode.index , d.index , -1); } return delta_nd; } /** * <p>Returns the node-multicast demand incidence matrix (a <i>N</i>x<i>D</i> in which an element <i>&delta;<sub>nd</sub></i> equals 1 if <i>n</i> is the ingress node of <i>d</i>, * -1 if <i>n</i> is an egress node of <i>d</i> and 0 otherwise). * If no layer is provided, the default layer is assumed.</p> * @param optionalLayerParameter Network layer * @return The node-multicast demand incidence matrix */ public DoubleMatrix2D getMatrixNodeMulticastDemandIncidence (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); int N = nodes.size (); int MD = layer.multicastDemands.size (); DoubleMatrix2D delta_nd = DoubleFactory2D.sparse.make(N , MD); for (MulticastDemand d : layer.multicastDemands) { delta_nd.set (d.ingressNode.index , d.index , 1); for (Node egressNode : d.egressNodes) delta_nd.set (egressNode.index , d.index , -1); } return delta_nd; } /** * <p>Returns the node-demand incoming incidence matrix (a <i>N</i>x<i>D</i> matrix in which element <i>&delta;<sub>nd</sub></i> equals 1 if demand <i>d</i> is terminated * in node <i>n</i> and 0 otherwise. If no layer is provided, the default layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return The node-demand incoming incidence matrix */ public DoubleMatrix2D getMatrixNodeDemandIncomingIncidence (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); int N = nodes.size (); int D = layer.demands.size (); DoubleMatrix2D delta_nd = DoubleFactory2D.sparse.make(N , D); for (Demand d : layer.demands) delta_nd.set (d.egressNode.index , d.index , 1); return delta_nd; } /** * <p>Returns the node-multicast demand incoming incidence matrix (a <i>N</i>x<i>D</i> matrix in which element <i>&delta;<sub>nd</sub></i> equals 1 if multicast demand <i>d</i> is terminated * in node <i>n</i> and 0 otherwise. If no layer is provided, the default layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return The node-multicast demand incoming incidence matrix */ public DoubleMatrix2D getMatrixNodeMulticastDemandIncomingIncidence (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); int N = nodes.size (); int MD = layer.multicastDemands.size (); DoubleMatrix2D delta_nd = DoubleFactory2D.sparse.make(N , MD); for (MulticastDemand d : layer.multicastDemands) for (Node egressNode : d.egressNodes) delta_nd.set (egressNode.index , d.index , 1); return delta_nd; } /** * <p>Returns the node-demand outgoing incidence matrix (a <i>N</i>x<i>D</i> matrix in which element <i>&delta;<sub>nd</sub></i> equals 1 if demand <i>d</i> is initiated * in node <i>n</i> and 0 otherwise. If no layer is provided, the default layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return The node-demand outgoing incidence matrix */ public DoubleMatrix2D getMatrixNodeDemandOutgoingIncidence (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); int N = nodes.size (); int D = layer.demands.size (); DoubleMatrix2D delta_nd = DoubleFactory2D.sparse.make(N , D); for (Demand d : layer.demands) delta_nd.set (d.ingressNode.index , d.index , 1); return delta_nd; } /** * <p>Returns the node-multicast demand outgoing incidence matrix (a <i>N</i>x<i>D</i> matrix in which element <i>&delta;<sub>nd</sub></i> equals 1 if demand <i>d</i> is initiated * in node <i>n</i> and 0 otherwise. If no layer is provided, the default layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return The node-multicast demand outgoing incidence matrix */ public DoubleMatrix2D getMatrixNodeMulticastDemandOutgoingIncidence (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); int N = nodes.size (); int MD = layer.multicastDemands.size (); DoubleMatrix2D delta_nd = DoubleFactory2D.sparse.make(N , MD); for (MulticastDemand d : layer.multicastDemands) delta_nd.set (d.ingressNode.index , d.index , 1); return delta_nd; } /** * <p>Returns the node-link adjacency matrix (a <i>N</i>x<i>N</i> matrix in which element <i>&delta;<sub>ij</sub></i> is equals to the number of links from node <i>i</i> to node <i>j</i>. * If no layer is provided, the default layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return The node-link adjacency matrix */ public DoubleMatrix2D getMatrixNodeLinkAdjacency (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); int N = nodes.size (); DoubleMatrix2D delta_nn = DoubleFactory2D.sparse.make(N , N); for (Link e : layer.links) delta_nn.set (e.originNode.index , e.destinationNode.index , delta_nn.get (e.originNode.index , e.destinationNode.index) + 1); return delta_nn; } /** * <p>Returns the node-link incidence matrix (a <i>N</i>x<i>E</i> matrix in which element <i>&delta;<sub>ne</sub></i> equals 1 if link <i>e</i> is initiated in node <i>n</i>, -1 * if link <i>e</i> ends in node <i>n</i>, and 0 otherwise. If no layer is provided, the default layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return The node-link incidence matrix */ public DoubleMatrix2D getMatrixNodeLinkIncidence (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); int N = nodes.size (); int E = layer.links.size (); DoubleMatrix2D delta_ne = DoubleFactory2D.sparse.make(N , E); for (Link e : layer.links) { delta_ne.set (e.originNode.index , e.index , 1); delta_ne.set (e.destinationNode.index , e.index , -1); } return delta_ne; } /** * <p>Returns the node-link incoming incidence matrix (a <i>N</i>x<i>E</i> matrix in which element <i>&delta;<sub>ne</sub></i> equals 1 if link <i>e</i> is terminated in node <i>n</i>, * and 0 otherwise. If no layer is provided, the default layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return The node-link incoming incidence matrix */ public DoubleMatrix2D getMatrixNodeLinkIncomingIncidence (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); int N = nodes.size (); int E = layer.links.size (); DoubleMatrix2D delta_ne = DoubleFactory2D.sparse.make(N , E); for (Link e : layer.links) delta_ne.set (e.destinationNode.index , e.index , 1); return delta_ne; } /** * <p>Returns the node-link outgoing incidence matrix (a <i>N</i>x<i>E</i> matrix in which element <i>&delta;<sub>ne</sub></i> equals 1 if link <i>e</i> is initiated in node <i>n</i>, * and 0 otherwise. If no layer is provided, the default layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return The node-link outgoing incidence matrix */ public DoubleMatrix2D getMatrixNodeLinkOutgoingIncidence (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); int N = nodes.size (); int E = layer.links.size (); DoubleMatrix2D delta_ne = DoubleFactory2D.sparse.make(N , E); for (Link e : layer.links) delta_ne.set (e.originNode.index , e.index , 1); return delta_ne; } /** * <p>Returns the multicast demand with the given index in the given layer. If no layer is provided, default layer is assumed.</p> * @param index Multicast demand index * @param optionalLayerParameter Network layer (optional) * @return The multicast demand ({@code null} if it does not exist, or index is lower than 0, or greater the number of elements minus one). */ public MulticastDemand getMulticastDemand (int index , NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); if ((index < 0) || (index > layer.multicastDemands.size () -1)) return null; else return layer.multicastDemands.get(index); } /** * <p>Returns the multicast demand with the given unique identifier.</p> * @param uid Multicast demand unique id * @return The multicast demand, or {@code null} if it does not exist */ public MulticastDemand getMulticastDemandFromId (long uid) { checkAttachedToNetPlanObject(); return cache_id2MulticastDemandMap.get(uid); } /** * <p>Returns the array of multicast demand ids for the given layer (i-th position, corresponds to index i). If no layer is provided, the default layer is assumed.</p> * @param optionalLayerParameter network layer (optional) * @return The {@code ArrayList} of multicast demand unique ids */ public ArrayList<Long> getMulticastDemandIds (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); ArrayList<Long> res = new ArrayList<Long> (); for (MulticastDemand e : layer.multicastDemands) res.add (e.id); return res; } /** * <p>Returns the list of multicast demands for the given layer (i-th position, corresponds to multicast demand with index i). If no layer is provided, the default layer is used</p> * @param optionalLayerParameter Network layer (optional) * @return The list of multicast demands */ public List<MulticastDemand> getMulticastDemands (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); return (List<MulticastDemand>) Collections.unmodifiableList(layer.multicastDemands); } /** * <p>Returns the multicast demands that have blocked traffic in the given layer. If no layer is provided, the default layer is assumed</p> * @param optionalLayerParameter Network layer (optional) * @return The multicast demands with blocked traffic */ public List<MulticastDemand> getMulticastDemandsBlocked (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); List<MulticastDemand> res = new LinkedList<MulticastDemand> (); for (MulticastDemand d : layer.multicastDemands) if (d.isBlocked()) res.add (d); return res; } /** * <p>Returns the set of multicas demands that are coupled.</p> * @param optionalLayerParameter Network layer (optional) * @return the {@code Set} of multicast demands */ public Set<MulticastDemand> getMulticastDemandsCoupled (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); Set<MulticastDemand> res = new HashSet<MulticastDemand> (); for (MulticastDemand demand : layer.multicastDemands) if (demand.coupledUpperLayerLinks != null) res.add (demand); return res; } /** * <p>Returns the total blocked traffic, summing up for all the multicast demands, in the given layer. If no layer is provided, the default layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return The total blocked traffic for all multicast demands */ public double getMulticastDemandTotalBlockedTraffic(NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); double accum = 0; for (MulticastDemand d : layer.multicastDemands) accum += Math.max(0 , d.offeredTraffic - d.carriedTraffic); return accum; } /** * <p>Returns the total carried traffic, summing up for all the multicast demands, in the given layer. If no layer is provided, the default layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return The total carried traffic for all multicast demands */ public double getMulticastDemandTotalCarriedTraffic(NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); double accum = 0; for (MulticastDemand d : layer.multicastDemands) accum += d.carriedTraffic; return accum; } /** * <p>Returns the total offered traffic, summing up for all the multicast demands, in the given layer. If no layer is provided, the default layer is assumed</p> * @param optionalLayerParameter Network layer (optional) * @return the total offered traffic for all multicast demands */ public double getMulticastDemandTotalOfferedTraffic(NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); double accum = 0; for (MulticastDemand d : layer.multicastDemands) accum += d.offeredTraffic; return accum; } /** * <p>Returns the multicast tree with the given index in the given layer. if no layer is provided, default layer is assumed.</p> * @param index Multicast tree index * @param optionalLayerParameter Network layer (optional) * @return The multicast tree ({@code null}if it does not exist, index islower than 0, or greater than the number of elements minus one) */ public MulticastTree getMulticastTree (int index , NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); if ((index < 0) || (index > layer.multicastTrees.size () -1)) return null; else return layer.multicastTrees.get(index); } /** * <p>Returns the multicast tree with the given unique identifier.</p> * @param uid Multicast tree unique id * @return The multicast tree ({@code null} if it does not exist */ public MulticastTree getMulticastTreeFromId (long uid) { checkAttachedToNetPlanObject(); return cache_id2MulticastTreeMap.get(uid); } /** * <p>Returns the array of multicast tree ids for the given layer (i-th position, corresponds to index i). If no layer is provided, the default layer is assumed.</p> * @param optionalLayerParameter network layer (optional) * @return the {@code ArrayList} of multicast trees unique ids */ public ArrayList<Long> getMulticastTreeIds (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); ArrayList<Long> res = new ArrayList<Long> (); for (MulticastTree e : layer.multicastTrees) res.add (e.id); return res; } /** * <p>Returns the array of multicast trees for the given layer (i-th position, corresponds to index i). If no layer is provided, the default layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return The {@code List} of multicast trees */ public List<MulticastTree> getMulticastTrees (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); return (List<MulticastTree>) Collections.unmodifiableList(layer.multicastTrees); } /** * <p>Returns the set of multicast trees that are down (i.e. that traverse a link or node that has failed).</p> * @param optionalLayerParameter Network layer (optional) * @return the {@code Set} of multicast trees that are down */ public Set<MulticastTree> getMulticastTreesDown (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); Set<MulticastTree> res = new HashSet<MulticastTree> (); for (MulticastTree r : layer.multicastTrees) if (r.isDown()) res.add (r); return res; } /** * <p>Returns the description associated to the {@code NetPlan} object</p> * @return The network description as a {@code String} */ public String getNetworkDescription () { return this.networkDescription; } /** * <p>Return the network element with the given unique id.</p> * @param id Unique id * @return The network element ({@code null} if it does not exist) * @see com.net2plan.interfaces.networkDesign.NetworkElement */ public NetworkElement getNetworkElement (long id) { NetworkElement e; e = cache_id2DemandMap.get(id); if (e != null) return e; e = cache_id2LayerMap.get(id); if (e != null) return e; e = cache_id2LinkMap.get(id); if (e != null) return e; e = cache_id2MulticastDemandMap.get(id); if (e != null) return e; e = cache_id2MulticastTreeMap.get(id); if (e != null) return e; e = cache_id2NodeMap.get(id); if (e != null) return e; e = cache_id2ProtectionSegmentMap.get(id); if (e != null) return e; e = cache_id2RouteMap.get(id); if (e != null) return e; e = cache_id2srgMap.get(id); if (e != null) return e; return null; } /** * <p>Returns the first network element among the ones passed as input parameters, that has the given key-value as attribute. </p> * * @param listOfElements Lit of network elements * @param attribute Attribute name * @param value Attribute value * @return First network element encountered with the given key-value ({@code null}if no network element matches or the input {@code null} or empty * @see com.net2plan.interfaces.networkDesign.NetworkElement */ public static NetworkElement getNetworkElementByAttribute(Collection<? extends NetworkElement> listOfElements , String attribute, String value) { if (listOfElements == null) return null; for (NetworkElement e : listOfElements) { String atValue = e.attributes.get (attribute); if (atValue != null) if (atValue.equals(value)) return e; } return null; } /** * Returns the next identifier for a new network element (layer, node, link, demand...) * * @return Next identifier */ public long getNetworkElementNextId() { final long elementId = nextElementId.longValue(); if (elementId < 0) throw new Net2PlanException(TEMPLATE_NO_MORE_NETWORK_ELEMENTS_ALLOWED); return elementId; } /** * <p>Returns all the network elements among the ones passed as input parameters, that have the given key-value as attribute. * Returns an empty list if no network element mathces this, the input list of elements is null or empty</p> * @param listOfElements List of network elements * @param attribute Attribute name * @param value Attribute value * @return List of all network elements with the attribute key-value */ public static Collection<? extends NetworkElement> getNetworkElementsByAttribute(Collection <? extends NetworkElement> listOfElements , String attribute, String value) { List<NetworkElement> res = new LinkedList<NetworkElement> (); if (listOfElements == null) return res; for (NetworkElement e : listOfElements) { String atValue = e.attributes.get (attribute); if (atValue != null) if (atValue.equals(value)) res.add (e); } return res; } /** * <p>Returns the network layer with the given unique identifier.</p> * @param uid Network layer unique id * @return The network layer with the given id ({@code null} if it does not exist) */ public NetworkLayer getNetworkLayerFromId (long uid) { return cache_id2LayerMap.get(uid); } /** * <p> Return the default network layer.</p> * @return The default network layer */ public NetworkLayer getNetworkLayerDefault () { return defaultLayer; } /** * <p>Returns the array of layer ids (i-th position, corresponds to index i).</p> * @return The {@code ArraList} of network layers */ public ArrayList<Long> getNetworkLayerIds () { ArrayList<Long> res = new ArrayList<Long> (); for (NetworkLayer n : layers) res.add (n.id); return res; } /** * <p>Returns network layers in bottom-up order, that is, starting from the * lower layers to the upper layers following coupling relationships. For layers * at the same hierarchical level, no order is guaranteed.</p> * * @return The {@code Set} of network layers in topological order * @since 0.3.0 */ public Set<NetworkLayer> getNetworkLayerInTopologicalOrder() { Set<NetworkLayer> layers_topologicalSort = new LinkedHashSet<NetworkLayer>(); Iterator<NetworkLayer> it = interLayerCoupling.iterator(); while(it.hasNext()) layers_topologicalSort.add(it.next()); return layers_topologicalSort; } /** * <p>Returns the array of network layers (i-th position, corresponds to index i).</p> * @return The {@code List} of network layers */ public List<NetworkLayer> getNetworkLayers () { return (List<NetworkLayer>) Collections.unmodifiableList(layers); } /** * <p>Returns the name associated to the netPlan object</p> * @return The network name */ public String getNetworkName () { return this.networkName; } /** * <p>Returns the node with the given unique identifier.</p> * @param uid Node unique id * @return The node with the given id ({@code null} if it does not exist) */ public Node getNodeFromId (long uid) { return cache_id2NodeMap.get(uid); } /** * <p>Returns the first node with the given name.</p> * @param name Node name * @return The first node with the given name ({@code null} if it does not exist) */ public Node getNodeByName(String name) { for (Node n : nodes) if (n.name.equals (name)) return n; return null; } /** * <p>Returns the array of node ids (i-th position, corresponds to index i)</p> * @return The {@code ArrayList} of nodes */ public ArrayList<Long> getNodeIds () { ArrayList<Long> res = new ArrayList<Long> (); for (Node n : nodes) res.add (n.id); return res; } /** * <p>Gets the set of demands at the given layer from the input nodes (if {@code returnDemandsInBothDirections} is {@code true}, also the reversed links are included). If no layer is provided, the default layer is assumed.</p> * @param originNode Origin node * @param destinationNode Destination node * @param returnDemandsInBothDirections Assume both directions * @param optionalLayerParameter network layer (optional) * @return the {@code Set} of demands that have the origin and destination for the given input */ public Set<Demand> getNodePairDemands (Node originNode, Node destinationNode , boolean returnDemandsInBothDirections , NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); checkInThisNetPlan(originNode); checkInThisNetPlan(destinationNode); Set<Demand> res = new HashSet<Demand> (); for (Demand e : originNode.cache_nodeOutgoingDemands) if (e.layer.equals (layer) && e.egressNode.equals (destinationNode)) res.add (e); if (returnDemandsInBothDirections) for (Demand e : originNode.cache_nodeIncomingDemands) if (e.layer.equals (layer) && e.ingressNode.equals (destinationNode)) res.add (e); return res; } /** * <p>Gets the Euclidean distance for a node pair.</p> * @param originNode Origin node * @param destinationNode Destination node * @return The Euclidean distance between a node pair */ public double getNodePairEuclideanDistance(Node originNode, Node destinationNode) { checkInThisNetPlan(originNode); checkInThisNetPlan(destinationNode); return Math.sqrt (Math.pow (originNode.nodeXYPositionMap.getX() - destinationNode.nodeXYPositionMap.getX(), 2) + Math.pow (originNode.nodeXYPositionMap.getY() - destinationNode.nodeXYPositionMap.getY() , 2)); } /** * <p>Gets the Haversine distance for a node pair.</p> * @param originNode Origin node * @param destinationNode Destination node * @return The Harvesine distance between a node pair * @see <a href="http://www.movable-type.co.uk/scripts/latlong.html">Calculate distance, bearing and more between Latitude/Longitude points</a> */ public double getNodePairHaversineDistanceInKm(Node originNode, Node destinationNode) { checkInThisNetPlan(originNode); checkInThisNetPlan(destinationNode); return GraphUtils.computeHaversineDistanceInKm(originNode.nodeXYPositionMap, destinationNode.nodeXYPositionMap); } /** * <p>Gets the set of links at the given layer from the given nodes (if {@code returnLinksInBothDirections} is {@code true}, also the reversed links are included). If no layer is provided, the default layer is assumed.</p> * @param originNode Origin node * @param destinationNode Destination node * @param returnLinksInBothDirections Include links in both direction * @param optionalLayerParameter Network layer (optional) * @return the {@code Set} of links between a pair of nodes */ public Set<Link> getNodePairLinks (Node originNode, Node destinationNode , boolean returnLinksInBothDirections , NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); checkInThisNetPlan(originNode); checkInThisNetPlan(destinationNode); Set<Link> res = new HashSet<Link> (); for (Link e : originNode.cache_nodeOutgoingLinks) if (e.layer.equals (layer) && e.destinationNode.equals (destinationNode)) res.add (e); if (returnLinksInBothDirections) for (Link e : originNode.cache_nodeIncomingLinks) if (e.layer.equals (layer) && e.originNode.equals (destinationNode)) res.add (e); return res; } /** * <p>Gets the set of routes at the given layer from the given nodes (if {@code returnRoutesInBothDirections} is {@code true}, also the reversed routes are included). * If no layer is provided, the default layer is assumed.</p> * @param originNode Origin node * @param destinationNode Destination node * @param returnRoutesInBothDirections Include routes in both directions * @param optionalLayerParameter Network layer (optional) * @return The {@code Set} of routes between a pair of nodes */ public Set<Route> getNodePairRoutes (Node originNode, Node destinationNode , boolean returnRoutesInBothDirections , NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); checkInThisNetPlan(originNode); checkInThisNetPlan(destinationNode); Set<Route> res = new HashSet<Route> (); for (Demand e : originNode.cache_nodeOutgoingDemands) if (e.layer.equals (layer) && e.egressNode.equals (destinationNode)) res.addAll (e.cache_routes); if (returnRoutesInBothDirections) for (Demand e : originNode.cache_nodeIncomingDemands) if (e.layer.equals (layer) && e.ingressNode.equals (destinationNode)) res.addAll (e.cache_routes); return res; } /** * <p>Return the set of protection segments at the given layer for the given nodes (if {@code returnSegmentsInBothDirections} is {@code true}, also the reversed protection segments are included) * If no layer is provided, default layer is assumed.</p> * @param originNode Origin node * @param destinationNode Destination node * @param returnSegmentsInBothDirections Include protection segments in both directions * @param optionalLayerParameter Network layer (optional) * @return The {@code Set} of protection segments between a pair of nodes */ public Set<ProtectionSegment> getNodePairProtectionSegments (Node originNode, Node destinationNode , boolean returnSegmentsInBothDirections , NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); checkInThisNetPlan(originNode); checkInThisNetPlan(destinationNode); Set<ProtectionSegment> res = new HashSet<ProtectionSegment> (); for (ProtectionSegment s : originNode.cache_nodeAssociatedSegments) { if ((s.originNode == originNode) && (s.destinationNode == destinationNode)) res.add (s); if (returnSegmentsInBothDirections) if ((s.originNode == destinationNode) && (s.destinationNode == originNode)) res.add (s); } return res; } /** * <p>Returns the array of nodes (i-th position, corresponds to index i).</p> * @return The {@code List} of nodes */ public List<Node> getNodes () { return (List<Node>) Collections.unmodifiableList(nodes); } // /** // * Computes the shortest path between the end nodes, using the given link costs (if null, the shortest path is in number of hops), for the // * given layer. If no layer is provided, the default layer is assumed. An infinite cost makes the link unusable. Returns null if no path exists // */ // public List<Link> computeShortestPath (Node origin , Node destination , DoubleMatrix1D linkCosts , NetworkLayer ... optionalLayerParameter) // { // checkIsModifiable(); // if (optionalLayerParameter.length >= 2) throw new Net2PlanException ("None or one layer parameter can be supplied"); // NetworkLayer layer = (optionalLayerParameter.length == 1)? optionalLayerParameter [0] : defaultLayer; // if (linkCosts == null) linkCosts = DoubleFactory1D.dense.make (layer.links.size() , 1.0); // if (linkCosts.size () != layer.links.size()) throw new Net2PlanException ("Wrong cost vector"); // final Map<Long,Pair<Long,Long>> netPlanLinkMap = getLinkIdMap (layer.links); // Map<Long,Double> linkCost = new HashMap<Long,Double> (); // for (Link link : layer.links) // linkCost.put(link.id, linkCosts.get(link.index)); // final List<Long> seqLinkIds = GraphUtils.getShortestPath(netPlanLinkMap, origin.id , destination.id , linkCost); // List<Link> seqLinks = new LinkedList<Link> (); for (long id : seqLinkIds) seqLinks.add (cache_id2LinkMap.get(id)); // return seqLinks; // } // /** * <p>Returns the set of nodes that are down (iteration order corresponds to ascending order of indexes).</p> * @return The {@code Set} of nodes that are down */ public Set<Node> getNodesDown () { return Collections.unmodifiableSet(cache_nodesDown); } /** * <p>Returns the set of nodes that are up (iteration order correspond to ascending order of indexes).</p> * @return The {@code Set} of nodes that are up */ public Set<Node> getNodesUp () { Set<Node> res = new HashSet<Node> (nodes); res.removeAll(cache_nodesDown); return res; } /** * <p>Returns the number of demands at the given layer. If no layer is provided, the default layer is assumed.</p> * @param optionalLayerParameter network layer (optional) * @return The number of demands */ public int getNumberOfDemands (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); return layer.demands.size(); } /** * <p>Returns the number of non-zero forwarding rules at the given layer. If no layer is provided, the default layer is assumed.</p> * @param optionalLayerParameter network layer (optional) * @return The number of non-zero forwarding rules */ public int getNumberOfForwardingRules (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); layer.checkRoutingType(RoutingType.HOP_BY_HOP_ROUTING); IntArrayList ds = new IntArrayList (); IntArrayList es = new IntArrayList (); DoubleArrayList vals = new DoubleArrayList (); layer.forwardingRules_f_de.getNonZeros(ds , es , vals); return ds.size (); } /** * <p>Returns the number of layers defined.</p> * @return The number of layers */ public int getNumberOfLayers () { return layers.size(); } /** * <p>Returns the number of links at the given layer. If no layer is provided, the default layer is assumed.</p> * @param optionalLayerParameter network layer * @return The number of links */ public int getNumberOfLinks (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); return layer.links.size(); } /** * <p>Returns the number of multicast demands at the given layer. If no layer is provided, the default layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return The number of multicast demands */ public int getNumberOfMulticastDemands (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); return layer.multicastDemands.size(); } /** * <p>Returns the number of multicast trees at the given layer. If no layer is provided, the default layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return The number of multicast trees */ public int getNumberOfMulticastTrees (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); return layer.multicastTrees.size(); } /** * <p>Returns the number of network nodes,</p> * @return The number of nodes */ public int getNumberOfNodes () { return nodes.size(); } /** * <p>Returns the number of node pairs.</p> * @return The number of node pairs */ public int getNumberOfNodePairs () { return nodes.size() * (nodes.size()-1); } /** * <p>Returns the number of protection segments at the given layer. If no layer is provided, the default layer is assumed.</p> * @param optionalLayerParameter network layer (optional) * @return The number of protection segments */ public int getNumberOfProtectionSegments (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); layer.checkRoutingType(RoutingType.SOURCE_ROUTING); return layer.protectionSegments.size(); } /** * <p>Returns the number of routes at the given layer. If no layer is provided, the default layer is assumed.</p> * @param optionalLayerParameter network layer (optional) * @return The number of routes */ public int getNumberOfRoutes (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); layer.checkRoutingType(RoutingType.SOURCE_ROUTING); return layer.routes.size(); } /** * <p>Returns the number of shared risk groups (SRGs) defined</p> * @return The number of defined shared risk groups */ public int getNumberOfSRGs () { return srgs.size(); } /** * <p>Returns the protection segment with the given index in the given layer. if no layer is provided, default layer is assumed.</p> * @param index Protection segment index * @param optionalLayerParameter network layer (optional) * @return The protection segment with the given index ({@code null} if it does not exist, index is lesser thatn zero or greater that the number of elements minus one) */ public ProtectionSegment getProtectionSegment (int index , NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); layer.checkRoutingType(RoutingType.SOURCE_ROUTING); if ((index < 0) || (index > layer.protectionSegments.size () -1)) return null; else return layer.protectionSegments.get(index); } /** * <p>Returns the protection segment with the given unique identifier.</p> * @param uid Protection segment unique id * @return The protection segment with the given id ({@code null} if it does not exist) */ public ProtectionSegment getProtectionSegmentFromId (long uid) { return cache_id2ProtectionSegmentMap.get(uid); } /** * <p>Returns the array of protection segment ids for the given layer (i-th position, corresponds to index i). If no layer is provided, the default layer is assumed</p> * @param optionalLayerParameter Network layer (optional) * @return The {@code ArrayList} of protection segments unique ids */ public ArrayList<Long> getProtectionSegmentIds (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); layer.checkRoutingType(RoutingType.SOURCE_ROUTING); ArrayList<Long> res = new ArrayList<Long> (); for (ProtectionSegment e : layer.protectionSegments) res.add (e.id); return res; } /** * <p>Returns the array of protection segmets for the given layer (i-th position, corresponds to index i). If no layer is provided, the default layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return The {@code List} of protection segments */ public List<ProtectionSegment> getProtectionSegments (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); layer.checkRoutingType(RoutingType.SOURCE_ROUTING); return (List<ProtectionSegment>) Collections.unmodifiableList(layer.protectionSegments); } /** * <p>Returns the set of protection segments that are down (traverse a link or node that is failed). If no layer is provided, default layer is assumed.</p> * @param optionalLayerParameter network layer (optional) * @return The {@code Set} of protection segments that are down */ public Set<ProtectionSegment> getProtectionSegmentsDown (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); layer.checkRoutingType(RoutingType.SOURCE_ROUTING); Set<ProtectionSegment> res = new HashSet<ProtectionSegment> (); for (ProtectionSegment r : layer.protectionSegments) if (r.isDown()) res.add (r); return res; } /** * <p>Returns the route with the given index in the given layer. if no layer is provided, default layer is assumed</p> * @param index Route index * @param optionalLayerParameter network layer (optional) * @return The route with the given index ({@code null} if it does not exist, index is lesser than zero or greater than the number of elements minus one) */ public Route getRoute (int index , NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); layer.checkRoutingType(RoutingType.SOURCE_ROUTING); layer.checkRoutingType(RoutingType.SOURCE_ROUTING); if ((index < 0) || (index > layer.routes.size () -1)) return null; else return layer.routes.get(index); } /** * <p>Returns the route with the given unique identifier.</p> * @param uid Rute unique id * @return The route with the given id ({@code null} if it does not exist) */ public Route getRouteFromId (long uid) { return cache_id2RouteMap.get(uid); } /** * <p>Returns the array of route ids for the given layer (i-th position, corresponds to index i). If no layer is provided, the default layer is assumed</p> * @param optionalLayerParameter Network layer (optional) * @return The {@code ArrayList} of route ides */ public ArrayList<Long> getRouteIds (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); layer.checkRoutingType(RoutingType.SOURCE_ROUTING); ArrayList<Long> res = new ArrayList<Long> (); for (Route e : layer.routes) res.add (e.id); return res; } /** * <p>Returns the array of route ids for the given layer (i-th position, corresponds to index i). If no layer is provided, the default layer is assumed</p> * @param optionalLayerParameter network layer (optional) * @return the {@code List} of routes */ public List<Route> getRoutes (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); layer.checkRoutingType(RoutingType.SOURCE_ROUTING); return (List<Route>) Collections.unmodifiableList(layer.routes); } /** * <p>Returns the set of routes that are down (traverse a link or node that is failed). If no layer is provided, default layer is assumed</p> * @param optionalLayerParameter network layer (optional) * @return The {@code Set} of routes that are down */ public Set<Route> getRoutesDown (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); layer.checkRoutingType(RoutingType.SOURCE_ROUTING); Set<Route> res = new HashSet<Route> (); for (Route r : layer.routes) if (r.isDown()) res.add (r); return res; } /** * <p>Returns the routing type of the given layer. If no layer is provided, the default layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return The routing type of the given layer * @see com.net2plan.utils.Constants.RoutingType */ public RoutingType getRoutingType(NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); return layer.routingType; } /** * <p>Returns the shared risk group with the given unique identifier.</p> * @param uid SRG unique id * @return The shared risk group with the given unique id (@code null if it does not exist) */ public SharedRiskGroup getSRGFromId (long uid) { return cache_id2srgMap.get(uid); } /** * <p>Returns the shared risk group with the given index</p> * @param index SRG index * @return The shared risk group with the given index ({@code null} if it does not exist, index is lesser than zero or greater than the number of elements minus one) */ public SharedRiskGroup getSRG (int index) { if ((index < 0) || (index > srgs.size () -1)) return null; else return srgs.get(index); } /** * <p>Returns the array of shared risk group ids (i-th position, corresponds to index i)</p> * @return The {@code ArrayList} of Shared Risk Groups unique ids */ public ArrayList<Long> getSRGIds () { ArrayList<Long> res = new ArrayList<Long> (); for (SharedRiskGroup n : srgs) res.add (n.id); return res; } /** * <p>Returns the array of shared risk groups (i-th position, corresponds to index i).</p> * @return The {@code List} of Shared Risk Groups */ public List<SharedRiskGroup> getSRGs () { return (List<SharedRiskGroup>) Collections.unmodifiableList(srgs); } /** * <p>Returns a vector with the carried traffic per demand, at the given layer. i-th vector corresponds to i-th index of the element. If no layer is provided, the defaulf layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return The vector of carried traffic per demand */ public DoubleMatrix1D getVectorDemandCarriedTraffic(NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); DoubleMatrix1D res = DoubleFactory1D.dense.make(layer.demands.size()); for (Demand e : layer.demands) res.set(e.index, e.carriedTraffic); return res; } /** * <p>Retuns a vector with the values of all given network elements for the given attribute key.</p> * <p><b>Important:</b> Each element must have the attribute set and value must be of type {@code double}</p> * @param collection Network elements * @param attributeKey Attribute name * @return The vector of values for the given attribute name for all network elements */ public DoubleMatrix1D getVectorAttributeValues (Collection<? extends NetworkElement> collection , String attributeKey) { DoubleMatrix1D res = DoubleFactory1D.dense.make (collection.size()); int counter = 0; for (NetworkElement e : collection) if (e.getAttribute(attributeKey) != null) res.set (counter ++ , Double.parseDouble(e.getAttribute(attributeKey))); else throw new Net2PlanException ("The element does not contain the attribute " + attributeKey); return res; } /** * <p>Sets the given attributes values to all the given network elements.</p> * @param collection Network elements * @param attributeKey Attribute name * @param values Attribute values (must have the same size as {@code collection} */ public void setVectorAttributeValues (Collection<? extends NetworkElement> collection , String attributeKey , DoubleMatrix1D values) { if (values.size () != collection.size()) throw new Net2PlanException ("The number of elements in the collection and the number of values to assign must be the same"); int counter = 0; for (NetworkElement e : collection) e.setAttribute(attributeKey , Double.toString(values.get (counter ++))); } /** * <p>Returns the vector with the worst propagation time (in ms) per demand at the given layer. i-th vector corresponds to i-th index of the element. If no layer is provided, default layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return The vector with the worst propagation time in ms per demand */ public DoubleMatrix1D getVectorDemandWorseCasePropagationTimeInMs (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); DoubleMatrix1D res = DoubleFactory1D.dense.make(layer.demands.size()); for (Demand e : layer.demands) res.set(e.index, e.getWorseCasePropagationTimeInMs()); return res; } /** * <p>Returns the vector with the worst propagation time (in ms) per multicast demand at the given layer. i-th vector corresponds to i-th index of the element.. If no layer is provided, default layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return The vector with the worst propagation time in ms per multicast demand */ public DoubleMatrix1D getVectorMulticastDemandWorseCasePropagationTimeInMs (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); DoubleMatrix1D res = DoubleFactory1D.dense.make(layer.demands.size()); for (MulticastDemand e : layer.multicastDemands) res.set(e.index, e.getWorseCasePropagationTimeInMs()); return res; } /** * <p>Returns a vector where each index equals the demand index and the value is 1 if said demand traverses oversubscrined links, 0 otherwise. If no layer is provided, default layer is assumed.</p> * @param optionalLayerParameter network layer (optional) * @return The vector indicating if each demand traverses oversubscribed links */ public DoubleMatrix1D getVectorDemandTraversesOversubscribedLink (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); DoubleMatrix1D res = DoubleFactory1D.dense.make(layer.demands.size()); for (Demand e : layer.demands) res.set(e.index, e.isTraversingOversubscribedLinks()? 1 : 0); return res; } /** * <p>Returns the vector indicating wheter a multicast demnd traverses (1) or not (0) oversubscribes links at the given layer. * i-th vector corresponds to i-th index of the element. If no layer is provided, the defaulf layer is assumed </p> * @param optionalLayerParameter network layer (optional) * @return The vector indicating if each multicast demand traverses oversubscribed links */ public DoubleMatrix1D getVectorMulticastDemandTraversesOversubscribedLink (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); DoubleMatrix1D res = DoubleFactory1D.dense.make(layer.multicastDemands.size()); for (MulticastDemand e : layer.multicastDemands) res.set(e.index, e.isTraversingOversubscribedLinks()? 1 : 0); return res; } /** * <p>Returns a vector with the availability per Shared Risk Group (SRG).</p> * @return The vector with the availability per Shared Risk group */ public DoubleMatrix1D getVectorSRGAvailability () { DoubleMatrix1D res = DoubleFactory1D.dense.make(srgs.size()); for (SharedRiskGroup e : srgs) res.set(e.index, e.getAvailability()); return res; } /** * <p>Returns a vector with the offered traffic per demand, at the given layer. i-th vector corresponds to i-th index of the element. If no layer is provided, the defaulf layer is assumed.</p> * @param optionalLayerParameter network layer (optional) * @return The vector with the offered traffic per demand */ public DoubleMatrix1D getVectorDemandOfferedTraffic(NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); DoubleMatrix1D res = DoubleFactory1D.dense.make(layer.demands.size()); for (Demand e : layer.demands) res.set(e.index, e.offeredTraffic); return res; } /** * <p>Returns a vector with the blocked traffic per demand, at the given layer. i-th vector corresponds to i-th index of the element. If no layer is provided, the defaulf layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return The vector with the blocked traffic per demand */ public DoubleMatrix1D getVectorDemandBlockedTraffic(NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); DoubleMatrix1D res = DoubleFactory1D.dense.make(layer.demands.size()); for (Demand e : layer.demands) res.set(e.index, Math.max (0 , e.offeredTraffic - e.carriedTraffic)); return res; } /** * <p>Returns a vector with the capacity per link, at the given layer. i-th vector corresponds to i-th index of the element. If no layer is provided, the defaulf layer is assumed.</p> * @param optionalLayerParameter network layer (optional) * @return The vector with the capacity per link */ public DoubleMatrix1D getVectorLinkCapacity(NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); DoubleMatrix1D res = DoubleFactory1D.dense.make(layer.links.size()); for (Link e : layer.links) res.set(e.index, e.capacity); return res; } /** * <p>Returns a vector with the capacity per link, at the given layer. i-th vector corresponds to i-th index of the element. If no layer is provided, the defaulf layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return The vector with the spare capacity per link */ public DoubleMatrix1D getVectorLinkSpareCapacity(NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); DoubleMatrix1D res = DoubleFactory1D.dense.make(layer.links.size()); for (Link e : layer.links) res.set(e.index, Math.max(0 , e.capacity - e.carriedTrafficSummingRoutesAndCarriedTrafficByProtectionSegments)); return res; } /** * <p>Returns a vector with the capacity per link reserved for protection, at the given layer. i-th vector corresponds to i-th index of the element. If no layer is provided, the defaulf layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return The vector with the capacity per link reserver for protection */ public DoubleMatrix1D getVectorLinkCapacityReservedForProtection (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); DoubleMatrix1D res = DoubleFactory1D.dense.make(layer.links.size()); for (Link e : layer.links) res.set(e.index, e.getReservedCapacityForProtection()); return res; } /** * <p>Returns a vector with the length in km in the links, at the given layer. i-th vector corresponds to i-th index of the element. If no layer is provided, the defaulf layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return The vector with the length un km per link */ public DoubleMatrix1D getVectorLinkLengthInKm (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); DoubleMatrix1D res = DoubleFactory1D.dense.make(layer.links.size()); for (Link e : layer.links) res.set(e.index, e.lengthInKm); return res; } /** * <p>Returns a vector with the propagation delay in milliseconds in the links, at the given layer. i-th vector corresponds to i-th index of the element. If no layer is provided, the defaulf layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return The vector with the propagation time per link */ public DoubleMatrix1D getVectorLinkPropagationDelayInMiliseconds (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); DoubleMatrix1D res = DoubleFactory1D.dense.make(layer.links.size()); for (Link e : layer.links) res.set(e.index, e.getPropagationDelayInMs()); return res; } /** * <p>Returns a vector with the propagation speed in km/s in the links, at the given layer. i-th vector corresponds to i-th index of the element. If no layer is provided, the defaulf layer is assumed.</p> * @param optionalLayerParameter network layer (optional) * @return The vector with the propagation speed in km/s per link */ public DoubleMatrix1D getVectorLinkPropagationSpeedInKmPerSecond (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); DoubleMatrix1D res = DoubleFactory1D.dense.make(layer.links.size()); for (Link e : layer.links) res.set(e.index, e.propagationSpeedInKmPerSecond); return res; } /** * <p>Returns a vector with the total carried traffic per link (counting the traffic in the traversed protection segments), at the given layer. i-th vector corresponds to i-th index of the element. * If no layer is provided, the defaulf layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return The vector with the total carried traffic per link */ public DoubleMatrix1D getVectorLinkTotalCarriedTraffic (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); DoubleMatrix1D res = DoubleFactory1D.dense.make(layer.links.size()); for (Link e : layer.links) res.set(e.index, e.carriedTrafficSummingRoutesAndCarriedTrafficByProtectionSegments); return res; } /** * <p>Returns a vector with the total occupied capacity in the links (counting the capacity occupied by the traffic in the traversed protection segments), at the given layer. * i-th vector corresponds to i-th index of the element. If no layer is provided, the defaulf layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return The vector with the tootal occupied capacity per link */ public DoubleMatrix1D getVectorLinkTotalOccupiedCapacity (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); DoubleMatrix1D res = DoubleFactory1D.dense.make(layer.links.size()); for (Link e : layer.links) res.set(e.index, e.occupiedCapacitySummingRoutesAndCarriedTrafficByProtectionSegments); return res; } /** * <p>Returns a vector with the up/down state in the links (1 up, 0 down), at the given layer. i-th vector corresponds to i-th index of the element. * If no layer is provided, the defaulf layer is assumed</p> * @param optionalLayerParameter Network layer (optional) * @return The vector with the up/down state in the links */ public DoubleMatrix1D getVectorLinkUpState (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); DoubleMatrix1D res = DoubleFactory1D.dense.make(layer.links.size()); for (Link e : layer.links) res.set(e.index, e.isUp? 1 : 0); return res; } /** * <p>Returns a vector with the utilization per link, at the given layer. Utilization is measured as the total link occupied capacity by the link traffic * including the one in the protection segments, divided by the total link capacity (accounting the reserved capacity by the protection segments). * i-th vector corresponds to i-th index of the element. If no layer is provided, the defaulf layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return The vector with the utilization per link */ public DoubleMatrix1D getVectorLinkUtilizationIncludingProtectionSegments (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); DoubleMatrix1D res = DoubleFactory1D.dense.make(layer.links.size()); for (Link e : layer.links) res.set(e.index, e.getUtilizationIncludingProtectionSegments()); return res; } /** * <p>Returns a vector with the utilization per link, at the given layer. Utilization is measured as the total link occupied capacity by the link traffic * <b>not</b> including the one in the protection segments, divided by the total link capacity, <b>not</b> including that reserved by the protection segments. * i-th vector corresponds to i-th index of the element. If no layer is provided, the defaulf layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return The link utilization vector (not including protection segments) */ public DoubleMatrix1D getVectorLinkUtilizationNotIncludingProtectionSegments (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); DoubleMatrix1D res = DoubleFactory1D.dense.make(layer.links.size()); for (Link e : layer.links) res.set(e.index, e.getUtilizationNotIncludingProtectionSegments()); return res; } /** * <p>Returns a vector with the oversubscibed traffic (oversubscribed traffic being the sum of all carried traffic, including protection segments minus the capacity, or 0 if such substraction is negative) in each link at the given layer. * i-th vector corresponds to i-th index of the element. If no layer is provided, default layer is assumed. </p> * @param optionalLayerParameter network layer (optional) * @return The vector with the oversubscribed traffic per link */ public DoubleMatrix1D getVectorLinkOversubscribedTraffic (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); DoubleMatrix1D res = DoubleFactory1D.dense.make(layer.links.size()); for (Link e : layer.links) res.set(e.index, Math.max(0 , e.occupiedCapacitySummingRoutesAndCarriedTrafficByProtectionSegments - e.capacity)); return res; } /** * <p>Returns a vector with the carried traffic per multicast demand, at the given layer. i-th vector corresponds to i-th index of the element. If no layer is provided, the defaulf layer is assumed</p> * @param optionalLayerParameter network layer (optional) * @return The vector with the carried traffic per multicast demand */ public DoubleMatrix1D getVectorMulticastDemandCarriedTraffic(NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); DoubleMatrix1D res = DoubleFactory1D.dense.make(layer.multicastDemands.size()); for (MulticastDemand e : layer.multicastDemands) res.set(e.index, e.carriedTraffic); return res; } /** * <p>Returns a vector with the offered traffic per multicast demand, at the given layer. i-th vector corresponds to i-th index of the element. If no layer is provided, the defaulf layer is assumed.</p> * @param optionalLayerParameter network layer (optional) * @return The vector with the offered traffic per multicast demand */ public DoubleMatrix1D getVectorMulticastDemandOfferedTraffic(NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); DoubleMatrix1D res = DoubleFactory1D.dense.make(layer.multicastDemands.size()); for (MulticastDemand e : layer.multicastDemands) res.set(e.index, e.offeredTraffic); return res; } /** * <p>Returns a vector with the blocked traffic per multicast demand, at the given layer. i-th vector corresponds to i-th index of the element. If no layer is provided, the defaulf layer is assumed.</p> * @param optionalLayerParameter network layer (optional) * @return The vector with the blocked traffic per multicast demand */ public DoubleMatrix1D getVectorMulticastDemandBlockedTraffic(NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); DoubleMatrix1D res = DoubleFactory1D.dense.make(layer.multicastDemands.size()); for (MulticastDemand e : layer.multicastDemands) res.set(e.index, Math.max(0 , e.offeredTraffic - e.carriedTraffic)); return res; } /** * <p>Returns a vector with the carried traffic per multicast tree, at the given layer. i-th vector corresponds to i-th index of the element. If no layer is provided, the defaulf layer is assumed.</p> * @param optionalLayerParameter network layer (optional) * @return The vector with the carried traffic per multicast tree */ public DoubleMatrix1D getVectorMulticastTreeCarriedTraffic (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); DoubleMatrix1D res = DoubleFactory1D.dense.make(layer.multicastTrees.size()); for (MulticastTree e : layer.multicastTrees) res.set(e.index, e.carriedTraffic); return res; } /** * <p>Returns a vector with the number of links per multicast tree, at the given layer. i-th vector corresponds to i-th index of the element. If no layer is provided, the defaulf layer is assumed.</p> * @param optionalLayerParameter network layer (optional) * @return The vector with the number of links per multicast tree */ public DoubleMatrix1D getVectorMulticastTreeNumberOfLinks (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); DoubleMatrix1D res = DoubleFactory1D.dense.make(layer.multicastTrees.size()); for (MulticastTree e : layer.multicastTrees) res.set(e.index, e.linkSet.size ()); return res; } /** * <p>Returns a vector with the avergage number of hops per multicast tree at the given layer. i-th vector corresponds to i-th index of the element. If no layer is provided, the defaulf layer is assumed. </p> * @param optionalLayerParameter network layer (optional) * @return The average number of hops per multicast tree */ public DoubleMatrix1D getVectorMulticastTreeAverageNumberOfHops (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); DoubleMatrix1D res = DoubleFactory1D.dense.make(layer.multicastTrees.size()); for (MulticastTree e : layer.multicastTrees) res.set(e.index, e.getTreeAveragePathLengthInHops()); return res; } /** * <p>Returns a vector with the occupied capacity traffic per multicast tree, at the given layer. i-th vector corresponds to i-th index of the element. If no layer is provided, the defaulf layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return The vector with the occupied capacity per multicast tree */ public DoubleMatrix1D getVectorMulticastTreeOccupiedCapacity (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); DoubleMatrix1D res = DoubleFactory1D.dense.make(layer.multicastTrees.size()); for (MulticastTree e : layer.multicastTrees) res.set(e.index, e.occupiedLinkCapacity); return res; } /** * <p>Returns a vector with the up/down state of the nodes (1 up, 0 down). i-th vector corresponds to i-th index of the element</p> * @return The vector with the up/down state of the nodes. */ public DoubleMatrix1D getVectorNodeUpState () { DoubleMatrix1D res = DoubleFactory1D.dense.make(nodes.size()); for (Node e : nodes) res.set(e.index, e.isUp? 1 : 0); return res; } /** * <p>Returns the vector with the total outgoing offered traffic per node at the given layer. i-th vector corresponds to i-th index of the element. if no layer is provided, default layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return The vector with the total outgoing offered traffic per node */ public DoubleMatrix1D getVectorNodeIngressUnicastTraffic (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); DoubleMatrix1D res = DoubleFactory1D.dense.make(nodes.size()); for (Node n : nodes) { double traf = 0; for (Demand d: n.cache_nodeOutgoingDemands) if (d.layer == layer) traf += d.offeredTraffic; res.set (n.index , traf); } return res; } /** * <p>Returns the vector with the total incoming offered traffic per node at the given layer. i-th vector corresponds to i-th index of the element. if no layer is provided, default layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return The vector with the total incoming offered traffic per node */ public DoubleMatrix1D getVectorNodeEgressUnicastTraffic (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); DoubleMatrix1D res = DoubleFactory1D.dense.make(nodes.size()); for (Node n : nodes) { double traf = 0; for (Demand d: n.cache_nodeIncomingDemands) if (d.layer == layer) traf += d.offeredTraffic; res.set (n.index , traf); } return res; } /** * <p>Returns a vector with the carried traffic per protection segment, at the given layer. i-th vector corresponds to i-th index of the element. If no layer is provided, the defaulf layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return The vector with the carried traffic per protection segment */ public DoubleMatrix1D getVectorProtectionSegmentCarriedTraffic (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); layer.checkRoutingType(RoutingType.SOURCE_ROUTING); DoubleMatrix1D res = DoubleFactory1D.dense.make(layer.protectionSegments.size()); for (ProtectionSegment e : layer.protectionSegments) res.set(e.index, e.carriedTrafficSummingRoutesAndCarriedTrafficByProtectionSegments); return res; } /** * <p>Returns a vector with the length in km per protection segment, at the given layer. i-th vector corresponds to i-th index of the element. If no layer is provided, the defaulf layer is assumed.</p> * @param optionalLayerParameter network layer (optional) * @return The vector with the length in km per protection segment */ public DoubleMatrix1D getVectorProtectionSegmentLengthInKm (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); layer.checkRoutingType(RoutingType.SOURCE_ROUTING); DoubleMatrix1D res = DoubleFactory1D.dense.make(layer.protectionSegments.size()); for (ProtectionSegment e : layer.protectionSegments) res.set(e.index, e.lengthInKm); return res; } /** * <p>Returns a vector with the number of links per protection segment, at the given layer. i-th vector corresponds to i-th index of the element. If no layer is provided, the defaulf layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return The vector with the number of links per protection segment */ public DoubleMatrix1D getVectorProtectionSegmentNumberOfLinks (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); layer.checkRoutingType(RoutingType.SOURCE_ROUTING); DoubleMatrix1D res = DoubleFactory1D.dense.make(layer.protectionSegments.size()); for (ProtectionSegment e : layer.protectionSegments) res.set(e.index, e.seqLinks.size()); return res; } /** * <p>Returns a vector with the occupied capacity traffic per protection segment, at the given layer. i-th vector corresponds to i-th index of the element. If no layer is provided, the defaulf layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return The vector with the occupied capacity traffic per protection segment */ public DoubleMatrix1D getVectorProtectionSegmentOccupiedCapacity (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); layer.checkRoutingType(RoutingType.SOURCE_ROUTING); DoubleMatrix1D res = DoubleFactory1D.dense.make(layer.protectionSegments.size()); for (ProtectionSegment e : layer.protectionSegments) res.set(e.index, e.occupiedCapacitySummingRoutesAndCarriedTrafficByProtectionSegments); return res; } /** * <p>Returns a vector with the carried traffic per route, at the given layer. i-th vector corresponds to i-th index of the element. If no layer is provided, the defaulf layer is assumed</p> * @param optionalLayerParameter Network layer (optional) * @return The vector with the carried traffic per route */ public DoubleMatrix1D getVectorRouteCarriedTraffic (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); layer.checkRoutingType(RoutingType.SOURCE_ROUTING); DoubleMatrix1D res = DoubleFactory1D.dense.make(layer.routes.size()); for (Route e : layer.routes) res.set(e.index, e.carriedTraffic); return res; } /** * <p>Returns a vector with the offered traffic (from its associated demand) per route at the given layer. i-th vector corresponds to i-th index of the element. If no layer is provided, the defaulf layer is assumed. </p> * @param optionalLayerParameter Network layer (optional) * @return The vector with the offered traffic per route (from is associated demand) */ public DoubleMatrix1D getVectorRouteOfferedTrafficOfAssociatedDemand (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); layer.checkRoutingType(RoutingType.SOURCE_ROUTING); DoubleMatrix1D res = DoubleFactory1D.dense.make(layer.routes.size()); for (Route e : layer.routes) res.set(e.index, e.demand.offeredTraffic); return res; } /** * <p>Returns a vector with the offered traffic per multicast tree from its associated multicast demand, at the given layer. i-th vector corresponds to i-th index of the element. If no layer is provided, the defaulf layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return The vector with the offered traffic per multicast tree from its associated multicast demand */ public DoubleMatrix1D getVectorMulticastTreeOfferedTrafficOfAssociatedMulticastDemand (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); DoubleMatrix1D res = DoubleFactory1D.dense.make(layer.multicastTrees.size()); for (MulticastTree e : layer.multicastTrees) res.set(e.index, e.demand.offeredTraffic); return res; } /** * <p>Returns a vector with the length in km per route, at the given layer. i-th vector corresponds to i-th index of the element. If no layer is provided, the defaulf layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return The vector with the length in km per route */ public DoubleMatrix1D getVectorRouteLengthInKm (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); layer.checkRoutingType(RoutingType.SOURCE_ROUTING); DoubleMatrix1D res = DoubleFactory1D.dense.make(layer.routes.size()); for (Route e : layer.routes) res.set(e.index, e.getLengthInKm()); return res; } /** * <p>Returns a vector with the propagation delay in seconds per route, at the given layer. i-th vector corresponds to i-th index of the element. If no layer is provided, the defaulf layer is assumed.</p> * @param optionalLayerParameter network layer (optional) * @return The vector with the propagation delay in seconds per route */ public DoubleMatrix1D getVectorRoutePropagationDelayInMiliseconds (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); layer.checkRoutingType(RoutingType.SOURCE_ROUTING); DoubleMatrix1D res = DoubleFactory1D.dense.make(layer.routes.size()); for (Route e : layer.routes) res.set(e.index, e.getPropagationDelayInMiliseconds()); return res; } /** * <p>Returns a vector with the number of links per route (including the links in the traversed protection segments if any), at the given layer. i-th vector corresponds to i-th index of the element. * If no layer is provided, the defaulf layer is assumed.</p> * @param optionalLayerParameter network layer (optional) * @return The vector with the number of links per route */ public DoubleMatrix1D getVectorRouteNumberOfLinks (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); layer.checkRoutingType(RoutingType.SOURCE_ROUTING); DoubleMatrix1D res = DoubleFactory1D.dense.make(layer.routes.size()); for (Route e : layer.routes) res.set(e.index, e.seqLinksRealPath.size()); return res; } /** * <p>Returns an array with the cost of each route in the layer. The cost of a route is given by the sum * of the costs of its links, given by the provided cost vector. If the route traverses protection segments, the cost * of its links is included. If the cost vector provided is {@code null}, * all links have cost one.</p> * @param costs Costs array * @param optionalLayerParameter Network layer (optional) * @return The cost of each route in the network * @see com.net2plan.interfaces.networkDesign.Route */ public DoubleMatrix1D computeRouteCostVector (double [] costs , NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); layer.checkRoutingType(RoutingType.SOURCE_ROUTING); if (costs == null) costs = DoubleUtils.ones(layer.links.size ()); else if (costs.length != layer.links.size()) throw new Net2PlanException ("The array of costs must have the same length as the number of links in the layer"); DoubleMatrix1D res = DoubleFactory1D.dense.make (layer.routes.size()); for (Route r : layer.routes) for (Link link : r.seqLinksRealPath) res.set (r.index , res.get(r.index) + costs [link.index]); return res; } /** * <p>Returns an array with the cost of each multicast tree in the layer. The cost of a multicast tree is given by the sum * of the costs in its links, given by the provided cost vector. If the cost vector provided is {@code null}, * all links have cost one. </p> * @param costs Costs array * @param optionalLayerParameter Network layer (optional) * @return The cost of each multicast tree * @see com.net2plan.interfaces.networkDesign.MulticastTree */ public DoubleMatrix1D computeMulticastTreeCostVector (double [] costs , NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); if (costs.length != layer.links.size()) throw new Net2PlanException ("The array of costs must have the same length as the number of links in the layer"); DoubleMatrix1D res = DoubleFactory1D.dense.make (layer.routes.size()); for (MulticastTree t : layer.multicastTrees) for (Link link : t.linkSet) res.set (t.index , res.get(t.index) + costs [link.index]); return res; } /** * <p>Returns a vector with the occupied capacity traffic per route, at the given layer. i-th vector corresponds to i-th index of the element. If no layer is provided, the defaulf layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return The vector with the occupied traffic per route */ public DoubleMatrix1D getVectorRouteOccupiedCapacity (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); layer.checkRoutingType(RoutingType.SOURCE_ROUTING); DoubleMatrix1D res = DoubleFactory1D.dense.make(layer.routes.size()); for (Route e : layer.routes) res.set(e.index, e.occupiedLinkCapacity); return res; } /** * <p>Returns {@code true} if the network has one or more demands at the given layer. If no layer is provided, the default layer is assumed.</p> * @param optionalLayerParameter network layer (optional) * @return {@code True} if the network has demands at the given layer, {@code false} otherwise */ public boolean hasDemands (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); return layer.demands.size() > 0; } /** * <p>Returns {@code true} if the network has at least one non-zero forwarding rule splitting ratio in any demand-link pair, in the given layer. If no layer is provided, the default layer is assumed.</p> * @param optionalLayerParameter network layer (optional) * @return {@code True} if the network has at least one forwarding rule, {@code false} otherwise */ public boolean hasForwardingRules (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); layer.checkRoutingType(RoutingType.HOP_BY_HOP_ROUTING); IntArrayList rows = new IntArrayList (); IntArrayList cols = new IntArrayList (); DoubleArrayList vals = new DoubleArrayList (); layer.forwardingRules_f_de.getNonZeros(rows,cols,vals); return (rows.size () != 0); } /** * <p>Returns {@code true} if the network has one or more links at the given layer. If no layer is provided, the default layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return {@code True} if the network has one or more links, {@code false} otherwise */ public boolean hasLinks (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); return layer.links.size() > 0; } /** * <p>Returns {@code true} if the network has one or more multicast demands at the given layer. If no layer is provided, the default layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return {@code True} if the network has one or more multicast demand, {@code false} otherwise */ public boolean hasMulticastDemands (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); return layer.multicastDemands.size() > 0; } /** * <p>Returns {@code true} if the network has one or more multicast trees at the given layer. If no layer is provided, the default layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return {@code True} if the network has one or more multicast trees, {@code false} otherwise */ public boolean hasMulticastTrees (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); return layer.multicastTrees.size() > 0; } /** * <p>Returns {@code true} if the network has nodes.</p> * @return {@code True} if the network has nodes, {@code false} otherwise */ public boolean hasNodes () { return nodes.size() > 0; } /** * <p>Returns {@code true} if the network has one or more protection segments at the given layer. If no layer is provided, the default layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return {@code True} if the network has one or more protection segments, {@code false} otherwise */ public boolean hasProtectionSegments (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); layer.checkRoutingType(RoutingType.SOURCE_ROUTING); return layer.protectionSegments.size() > 0; } /** * <p>Returns {@code true} if the network has one or moreroutes at the given layer. If no layer is provided, the default layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return {@code True} if the network has one or more routes, {@code false} otherwise */ public boolean hasRoutes (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); layer.checkRoutingType(RoutingType.SOURCE_ROUTING); return layer.routes.size() > 0; } /** * <p>Returns {@code true} if the network has one or more shared risk groups (SRGs) defined.</p> * @return {@code True} if the network has SRGs defined, {@code false} otherwise */ public boolean hasSRGs () { return srgs.size() > 0; } /** * <p>Returns {@code true} if the network has at least one routing cycle at the given layer. If no layer is provided, default layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return {@code True} if there is at least one routing cycle, {@code false} otherwise */ public boolean hasUnicastRoutingLoops (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); for (Demand d : layer.demands) if (d.getRoutingCycleType() != RoutingCycleType.LOOPLESS) return true; return false; } /** * <p>Indicates whether or not a further coupling between two layers would be valid. * This can be used to check if a new coupling would create cycles in the topology * of layers, that is, if layer hierarchy is not broken.</p> * @param lowerLayer Network lower layer * @param upperLayer Network upper layer * @return {@code True} if coupling between both input layers is valid, {@code false} otherwise */ public boolean isLayerCouplingValid(NetworkLayer lowerLayer , NetworkLayer upperLayer) { checkInThisNetPlan(lowerLayer); checkInThisNetPlan(upperLayer); if (lowerLayer.equals (upperLayer)) return false; DemandLinkMapping coupling_thisLayerPair = interLayerCoupling.getEdge(lowerLayer, upperLayer); if (coupling_thisLayerPair == null) { coupling_thisLayerPair = new DemandLinkMapping(); boolean valid; try { valid = interLayerCoupling.addDagEdge(lowerLayer, upperLayer, coupling_thisLayerPair); } catch (DirectedAcyclicGraph.CycleFoundException ex) { valid = false; } if (valid) interLayerCoupling.removeEdge(lowerLayer, upperLayer); else return false; } return true; } /** * <p>Returns {@code true} if in the given layer, the traffic of any multicast demand is carried by more than one multicast tree. If no layer is provided, the default layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return {@code True} if traffic from at least one multicast demand is carried trhough two or more multicast trees, {@code false} otherwise */ public boolean isMulticastRoutingBifurcated (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); for (MulticastDemand d : layer.multicastDemands) if (d.isBifurcated ()) return true; return false; } /** * <p>Returns {@code true} if the network has more than one layer.</p> * @return {@code True} if the network has two or more layers, {@code false} otherwise */ public boolean isMultilayer () { return layers.size() > 1; } /** * <p>Returns {@code true} if the network has just one layer</p> * @return {@code True} if network has only one layer, {@code false} otherwise */ public boolean isSingleLayer () { return layers.size() == 1; } /** * <p>Returns {@code true} if in the given layer, the traffic of any demand is carried by more than one route (in {@link com.net2plan.utils.Constants.RoutingType#SOURCE_ROUTING SOURCE_ROUTING}), * or a node sends traffic of a demand to more than * one link (in {@link com.net2plan.utils.Constants.RoutingType#HOP_BY_HOP_ROUTING HOP_BY_HOP_ROUTING}). If no layer is provided, the default layer is assumed</p> * @param optionalLayerParameter Network layer (optional) * @return {@code True} if unicast traffic is bifurcated (see description), {@code false} otherwise */ public boolean isUnicastRoutingBifurcated (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); for (Demand d : layer.demands) if (d.isBifurcated ()) return true; return false; } /** * <p>Indicates whether or not a path, multicast tree or arbitrary collection of links (and/or protection segments) is up. * This means that all links are up, and all end nodes of the links are also up</p> * @param linksAndOrProtectionSegments Sequence of links * @return {@code True} if all links in the sequence are up, {@code false} otherwise */ public boolean isUp (Collection<Link> linksAndOrProtectionSegments) { checkInThisNetPlan(linksAndOrProtectionSegments); for (Link e : linksAndOrProtectionSegments) { e.checkAttachedToNetPlanObject(this); if (!e.isUp ()) return false; if (!e.originNode.isUp) return false; if (!e.destinationNode.isUp) return false; } return true; } /** * <p>Removes a layer, and any associated link, demand, route, protection segment or forwarding rule. If this layer is the default, the new default layer is the one with index 0 (the smallest identifier) </p> * @param optionalLayerParameter Network layer (optional) */ public void removeNetworkLayer (NetworkLayer ... optionalLayerParameter) { checkIsModifiable(); NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); checkAttachedToNetPlanObject(); netPlan.checkIsModifiable(); if (netPlan.layers.size () == 1) throw new Net2PlanException("At least one layer must exist"); for (ProtectionSegment segment : new LinkedList<ProtectionSegment> (layer.protectionSegments)) segment.remove (); for (Route route : new LinkedList<Route> (layer.routes)) route.remove (); for (MulticastTree tree : new LinkedList<MulticastTree> (layer.multicastTrees)) tree.remove (); for (Link link : new LinkedList<Link> (layer.links)) link.remove (); for (Demand demand : new LinkedList<Demand> (layer.demands)) demand.remove (); for (MulticastDemand demand : new LinkedList<MulticastDemand> (layer.multicastDemands)) demand.remove (); netPlan.interLayerCoupling.removeVertex(layer); netPlan.cache_id2LayerMap.remove(layer.id); NetPlan.removeNetworkElementAndShiftIndexes(netPlan.layers , layer.index); if (netPlan.defaultLayer.equals(layer)) netPlan.defaultLayer = netPlan.layers.get (0); if (ErrorHandling.isDebugEnabled()) netPlan.checkCachesConsistency(); removeId (); } /** * <p>Removes all the demands defined in the given layer. If no layer is provided, default layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) */ public void removeAllDemands(NetworkLayer ... optionalLayerParameter) { checkIsModifiable(); NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); for (Demand d : new ArrayList<Demand> (layer.demands)) d.remove (); if (ErrorHandling.isDebugEnabled()) this.checkCachesConsistency(); } /** * <p>Removes all the forwarding rules in the given layer. If no layer is provided, default layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) */ public void removeAllForwardingRules(NetworkLayer ... optionalLayerParameter) { checkIsModifiable(); NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); layer.checkRoutingType(RoutingType.HOP_BY_HOP_ROUTING); layer.forwardingRules_f_de = DoubleFactory2D.sparse.make (layer.demands.size() , layer.links.size()); layer.forwardingRules_x_de = DoubleFactory2D.sparse.make (layer.demands.size() , layer.links.size()); for (Demand d : layer.demands) { d.routingCycleType = RoutingCycleType.LOOPLESS; d.carriedTraffic = 0; if (d.coupledUpperLayerLink != null) d.coupledUpperLayerLink.capacity = d.carriedTraffic; } for (Link e : layer.links) { e.carriedTrafficSummingRoutesAndCarriedTrafficByProtectionSegments = e.getMulticastCarriedTraffic(); e.occupiedCapacitySummingRoutesAndCarriedTrafficByProtectionSegments = e.getMulticastOccupiedLinkCapacity(); } if (ErrorHandling.isDebugEnabled()) this.checkCachesConsistency(); } /** * <p>Removes all the links defined in the given layer. If no layer is provided, default layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) */ public void removeAllLinks(NetworkLayer ... optionalLayerParameter) { checkIsModifiable(); NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); for (Link e : new ArrayList<Link> (layer.links)) e.remove (); if (ErrorHandling.isDebugEnabled()) this.checkCachesConsistency(); } /** * <p>Removes all the multicast demands defined in the given layer. If no layer is provided, default layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) */ public void removeAllMulticastDemands(NetworkLayer ... optionalLayerParameter) { checkIsModifiable(); NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); for (MulticastDemand d : new ArrayList<MulticastDemand> (layer.multicastDemands)) d.remove (); if (ErrorHandling.isDebugEnabled()) this.checkCachesConsistency(); } /** * <p>Removes all the multicast trees defined in the given layer. If no layer is provided, default layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) */ public void removeAllMulticastTrees (NetworkLayer ... optionalLayerParameter) { checkIsModifiable(); NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); for (MulticastTree t : new ArrayList<MulticastTree> (layer.multicastTrees)) t.remove (); if (ErrorHandling.isDebugEnabled()) this.checkCachesConsistency(); } /** * <p>Removes all the multicast trees carrying no traffic and occupying no link capacity defined in the given layer. If no layer is provided, default layer is used.</p> * * @param toleranceTrafficAndCapacityValueToConsiderUnusedTree Tolerance capacity to consider a link unsused * @param optionalLayerParameter Network layer (optional) */ public void removeAllMulticastTreesUnused (double toleranceTrafficAndCapacityValueToConsiderUnusedTree , NetworkLayer ... optionalLayerParameter) { checkIsModifiable(); NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); for (MulticastTree t : new ArrayList<MulticastTree> (layer.multicastTrees)) if ((t.carriedTraffic < toleranceTrafficAndCapacityValueToConsiderUnusedTree) && (t.occupiedLinkCapacity < toleranceTrafficAndCapacityValueToConsiderUnusedTree)) t.remove (); if (ErrorHandling.isDebugEnabled()) this.checkCachesConsistency(); } /** * <p>Removes all the network layers (everything but the nodes and the SRGs). Removes all the links, demands and multicast demands of the defualt layer, it does not remove it </p> */ public void removeAllNetworkLayers () { checkIsModifiable(); for (NetworkLayer layer : new ArrayList<NetworkLayer> (layers)) { if (layer != defaultLayer) { removeNetworkLayer (layer); continue; } removeAllLinks(layer); removeAllDemands(layer); removeAllMulticastDemands(layer); } if (ErrorHandling.isDebugEnabled()) this.checkCachesConsistency(); } /** * <p>Removes all the network nodes.</p> */ public void removeAllNodes () { checkIsModifiable(); for (NetworkLayer layer : layers) if (layer.routingType == RoutingType.HOP_BY_HOP_ROUTING) removeAllForwardingRules(layer); // to speed up things for (Node n : new ArrayList<Node> (nodes)) n.remove (); if (ErrorHandling.isDebugEnabled()) this.checkCachesConsistency(); } /** * <p>Removes all the protection segments defined in the given layer. If no layer is provided, default layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) */ public void removeAllProtectionSegments(NetworkLayer ... optionalLayerParameter) { checkIsModifiable(); NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); layer.checkRoutingType(RoutingType.SOURCE_ROUTING); for (ProtectionSegment s : new ArrayList<ProtectionSegment> (layer.protectionSegments)) s.remove (); if (ErrorHandling.isDebugEnabled()) this.checkCachesConsistency(); } /** * <p>Removes all the routes defined in the given layer. If no layer is provided, default layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) */ public void removeAllRoutes(NetworkLayer ... optionalLayerParameter) { checkIsModifiable(); NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); layer.checkRoutingType(RoutingType.SOURCE_ROUTING); for (Route r : new ArrayList<Route> (layer.routes)) r.remove (); if (ErrorHandling.isDebugEnabled()) this.checkCachesConsistency(); } /** * <p>Removes all the routes defined in the given layer that do not carry traffic nor occupy link capacity in the given layer. If no layer is provided, default layer is assumed.</p> * @param toleranceTrafficAndCapacityValueToConsiderUnusedRoute Tolerance traffic to consider a route unused * @param optionalLayerParameter Network layer (optional) */ public void removeAllRoutesUnused (double toleranceTrafficAndCapacityValueToConsiderUnusedRoute , NetworkLayer ... optionalLayerParameter) { checkIsModifiable(); NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); layer.checkRoutingType(RoutingType.SOURCE_ROUTING); for (Route r : new ArrayList<Route> (layer.routes)) if ((r.carriedTraffic < toleranceTrafficAndCapacityValueToConsiderUnusedRoute) && (r.occupiedLinkCapacity < toleranceTrafficAndCapacityValueToConsiderUnusedRoute)) r.remove (); if (ErrorHandling.isDebugEnabled()) this.checkCachesConsistency(); } /** * <p>Removes all the unsused links (those whith lesser capacity than {@code toleranceCapacityValueToConsiderUnusedLink}) defined in the given layer. If no layer is provided, default layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @param toleranceCapacityValueToConsiderUnusedLink Tolerance capacity to consider a link unsused */ public void removeAllLinksUnused (double toleranceCapacityValueToConsiderUnusedLink , NetworkLayer ... optionalLayerParameter) { checkIsModifiable(); NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); for (Link e : new ArrayList<Link> (layer.links)) if (e.capacity < toleranceCapacityValueToConsiderUnusedLink) e.remove (); if (ErrorHandling.isDebugEnabled()) this.checkCachesConsistency(); } /** * <p>Removes all the routing information (unicast and multicast) for the given layer, irrespective of the routing type * setting. For source routing, all routes and protection segments are removed. * For hop-by-hop routing, all forwarding rules are removed. If no layer is provided, the default layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) */ public void removeAllUnicastRoutingInformation(NetworkLayer ... optionalLayerParameter) { checkIsModifiable(); NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); switch(layer.routingType) { case SOURCE_ROUTING: removeAllRoutes(layer); removeAllProtectionSegments(layer); break; case HOP_BY_HOP_ROUTING: removeAllForwardingRules(layer); break; default: throw new RuntimeException("Bad"); } if (ErrorHandling.isDebugEnabled()) this.checkCachesConsistency(); } /** * <p>Removes all the shared risk groups.</p> */ public void removeAllSRGs () { checkIsModifiable(); for (SharedRiskGroup s : new ArrayList<SharedRiskGroup> (srgs)) s.remove (); if (ErrorHandling.isDebugEnabled()) this.checkCachesConsistency(); } /** * <p>Resets the state of the network to an empty {@code NetPlan}.</p> */ public void reset() { checkIsModifiable(); assignFrom(new NetPlan()); if (ErrorHandling.isDebugEnabled()) this.checkCachesConsistency(); } /** * <p>Saves the current network plan to a given file. If extension {@code .n2p} * is not in the file name, it will be added automatically.</p> * @param file Output file */ public void saveToFile(File file) { String filePath = file.getPath(); if (!filePath.toLowerCase(Locale.getDefault()).endsWith(".n2p")) file = new File(filePath + ".n2p"); FileOutputStream fos = null; try { fos = new FileOutputStream(file); saveToOutputStream(fos); } catch (FileNotFoundException e) { if (fos != null) { try { fos.close(); } catch (IOException ex) { } } throw new Net2PlanException(e.getMessage()); } } /** * <p>Saves the current network plan to a given output stream.</p> * @param outputStream Output stream */ public void saveToOutputStream(OutputStream outputStream) { try { XMLOutputFactory2 output = (XMLOutputFactory2) XMLOutputFactory2.newFactory(); XMLStreamWriter2 writer = (XMLStreamWriter2) output.createXMLStreamWriter(outputStream); writer.writeStartDocument("UTF-8", "1.0"); XMLUtils.indent(writer, 0); writer.writeStartElement("network"); writer.writeAttribute("description", getNetworkDescription()); writer.writeAttribute("name", getNetworkName()); writer.writeAttribute("version", Version.getFileFormatVersion()); //Set<Long> nodeIds_thisNetPlan = new HashSet<Long> (getNodeIds()); for (Node node : nodes) { boolean emptyNode = node.attributes.isEmpty(); XMLUtils.indent(writer, 1); if (emptyNode) writer.writeEmptyElement("node"); else writer.writeStartElement("node"); Point2D position = node.nodeXYPositionMap; writer.writeAttribute("id", Long.toString(node.id)); writer.writeAttribute("xCoord", Double.toString(position.getX())); writer.writeAttribute("yCoord", Double.toString(position.getY())); writer.writeAttribute("name", node.name); writer.writeAttribute("isUp", Boolean.toString (node.isUp)); for (Entry<String, String> entry : node.attributes.entrySet()) { XMLUtils.indent(writer, 2); writer.writeEmptyElement("attribute"); writer.writeAttribute("key", entry.getKey()); writer.writeAttribute("value", entry.getValue()); } if (!emptyNode) { XMLUtils.indent(writer, 1); writer.writeEndElement(); } } for(NetworkLayer layer : layers) { XMLUtils.indent(writer, 1); writer.writeStartElement("layer"); writer.writeAttribute("id", Long.toString(layer.id)); writer.writeAttribute("name", layer.name); writer.writeAttribute("description", layer.description); writer.writeAttribute("linkCapacityUnitsName", layer.linkCapacityUnitsName); writer.writeAttribute("demandTrafficUnitsName", layer.demandTrafficUnitsName); for(Link link : layer.links) { boolean emptyLink = link.attributes.isEmpty(); XMLUtils.indent(writer, 2); if (emptyLink) writer.writeEmptyElement("link"); else writer.writeStartElement("link"); writer.writeAttribute("id", Long.toString(link.id)); writer.writeAttribute("originNodeId", Long.toString(link.originNode.id)); writer.writeAttribute("destinationNodeId", Long.toString(link.destinationNode.id)); writer.writeAttribute("capacity", Double.toString(link.capacity)); writer.writeAttribute("lengthInKm", Double.toString(link.lengthInKm)); writer.writeAttribute("propagationSpeedInKmPerSecond", Double.toString(link.propagationSpeedInKmPerSecond)); writer.writeAttribute("isUp", Boolean.toString(link.isUp)); for (Entry<String, String> entry : link.attributes.entrySet()) { XMLUtils.indent(writer, 3); writer.writeEmptyElement("attribute"); writer.writeAttribute("key", entry.getKey()); writer.writeAttribute("value", entry.getValue()); } if (!emptyLink) { XMLUtils.indent(writer, 2); writer.writeEndElement(); } } for(Demand demand : layer.demands) { boolean emptyDemand = demand.attributes.isEmpty(); XMLUtils.indent(writer, 2); if (emptyDemand) writer.writeEmptyElement("demand"); else writer.writeStartElement("demand"); writer.writeAttribute("id", Long.toString(demand.id)); writer.writeAttribute("ingressNodeId", Long.toString(demand.ingressNode.id)); writer.writeAttribute("egressNodeId", Long.toString(demand.egressNode.id)); writer.writeAttribute("offeredTraffic", Double.toString(demand.offeredTraffic)); for (Entry<String, String> entry : demand.attributes.entrySet()) { XMLUtils.indent(writer, 3); writer.writeEmptyElement("attribute"); writer.writeAttribute("key", entry.getKey()); writer.writeAttribute("value", entry.getValue()); } if (!emptyDemand) { XMLUtils.indent(writer, 2); writer.writeEndElement(); } } for(MulticastDemand demand : layer.multicastDemands) { boolean emptyDemand = demand.attributes.isEmpty(); XMLUtils.indent(writer, 2); if (emptyDemand) writer.writeEmptyElement("multicastDemand"); else writer.writeStartElement("multicastDemand"); writer.writeAttribute("id", Long.toString(demand.id)); writer.writeAttribute("ingressNodeId", Long.toString(demand.ingressNode.id)); List<Long> egressNodeIds = new LinkedList<Long> (); for (Node n : demand.egressNodes) egressNodeIds.add (n.id); writer.writeAttribute("egressNodeIds", CollectionUtils.join(egressNodeIds, " ")); writer.writeAttribute("offeredTraffic", Double.toString(demand.offeredTraffic)); for (Entry<String, String> entry : demand.attributes.entrySet()) { XMLUtils.indent(writer, 3); writer.writeEmptyElement("attribute"); writer.writeAttribute("key", entry.getKey()); writer.writeAttribute("value", entry.getValue()); } if (!emptyDemand) { XMLUtils.indent(writer, 2); writer.writeEndElement(); } } for(MulticastTree tree : layer.multicastTrees) { boolean emptyTree = tree.attributes.isEmpty(); XMLUtils.indent(writer, 3); if (emptyTree) writer.writeEmptyElement("multicastTree"); else writer.writeStartElement("multicastTree"); writer.writeAttribute("id", Long.toString(tree.id)); writer.writeAttribute("demandId", Long.toString(tree.demand.id)); writer.writeAttribute("carriedTraffic", Double.toString(tree.carriedTraffic)); writer.writeAttribute("occupiedCapacity", Double.toString(tree.occupiedLinkCapacity)); writer.writeAttribute("carriedTrafficIfNotFailing", Double.toString(tree.carriedTrafficIfNotFailing)); writer.writeAttribute("occupiedLinkCapacityIfNotFailing", Double.toString(tree.occupiedLinkCapacityIfNotFailing)); List<Long> linkIds = new LinkedList<Long> (); for (Link e : tree.linkSet) linkIds.add (e.id); writer.writeAttribute("currentSetLinks", CollectionUtils.join(linkIds , " ")); linkIds = new LinkedList<Long> (); for (Link e : tree.initialSetLinksWhenWasCreated) linkIds.add (e.id); writer.writeAttribute("linkIds", CollectionUtils.join(linkIds , " ")); for (Entry<String, String> entry : tree.attributes.entrySet()) { XMLUtils.indent(writer, 4); writer.writeEmptyElement("attribute"); writer.writeAttribute("key", entry.getKey()); writer.writeAttribute("value", entry.getValue()); } if (!emptyTree) { XMLUtils.indent(writer, 3); writer.writeEndElement(); } } if (layer.routingType == RoutingType.SOURCE_ROUTING) { boolean emptySourceRouting = !hasProtectionSegments(layer) && !hasRoutes(layer); XMLUtils.indent(writer, 2); if (emptySourceRouting) writer.writeEmptyElement("sourceRouting"); else writer.writeStartElement("sourceRouting"); for(ProtectionSegment segment : layer.protectionSegments) { boolean emptySegment = segment.attributes.isEmpty(); XMLUtils.indent(writer, 3); if (emptySegment) writer.writeEmptyElement("protectionSegment"); else writer.writeStartElement("protectionSegment"); writer.writeAttribute("id", Long.toString(segment.id)); writer.writeAttribute("reservedCapacity", Double.toString(segment.capacity)); List<Long> seqLinks = new LinkedList<Long> (); for (Link e : segment.seqLinks) seqLinks.add (e.id); writer.writeAttribute("seqLinks", CollectionUtils.join(seqLinks, " ")); for (Entry<String, String> entry : segment.attributes.entrySet()) { XMLUtils.indent(writer, 4); writer.writeEmptyElement("attribute"); writer.writeAttribute("key", entry.getKey()); writer.writeAttribute("value", entry.getValue()); } if (!emptySegment) { XMLUtils.indent(writer, 3); writer.writeEndElement(); } } for(Route route : layer.routes) { boolean emptyRoute = route.attributes.isEmpty(); XMLUtils.indent(writer, 3); if (emptyRoute) writer.writeEmptyElement("route"); else writer.writeStartElement("route"); writer.writeAttribute("id", Long.toString(route.id)); writer.writeAttribute("demandId", Long.toString(route.demand.id)); writer.writeAttribute("carriedTraffic", Double.toString(route.carriedTraffic)); writer.writeAttribute("occupiedCapacity", Double.toString(route.occupiedLinkCapacity)); writer.writeAttribute("carriedTrafficIfNotFailing", Double.toString(route.carriedTrafficIfNotFailing)); writer.writeAttribute("occupiedLinkCapacityIfNotFailing", Double.toString(route.occupiedLinkCapacityIfNotFailing)); List<Long> initialSeqLinksWhenCreated = new LinkedList<Long> (); for (Link e : route.initialSeqLinksWhenCreated) initialSeqLinksWhenCreated.add (e.id); List<Long> seqLinksAndProtectionSegments = new LinkedList<Long> (); for (Link e : route.seqLinksAndProtectionSegments) seqLinksAndProtectionSegments.add (e.id); List<Long> backupSegmentList = new LinkedList<Long> (); for (ProtectionSegment e : route.potentialBackupSegments) backupSegmentList.add (e.id); writer.writeAttribute("seqLinks", CollectionUtils.join(initialSeqLinksWhenCreated, " ")); writer.writeAttribute("currentSeqLinksAndProtectionSegments", CollectionUtils.join(seqLinksAndProtectionSegments, " ")); writer.writeAttribute("backupSegmentList", CollectionUtils.join(backupSegmentList, " ")); for (Entry<String, String> entry : route.attributes.entrySet()) { XMLUtils.indent(writer, 4); writer.writeEmptyElement("attribute"); writer.writeAttribute("key", entry.getKey()); writer.writeAttribute("value", entry.getValue()); } if (!emptyRoute) { XMLUtils.indent(writer, 3); writer.writeEndElement(); } } if (!emptySourceRouting) { XMLUtils.indent(writer, 2); writer.writeEndElement(); } } else { boolean emptyHopByHopRouting = !hasForwardingRules(layer); XMLUtils.indent(writer, 2); if (emptyHopByHopRouting) writer.writeEmptyElement("hopByHopRouting"); else writer.writeStartElement("hopByHopRouting"); IntArrayList rows = new IntArrayList (); IntArrayList cols = new IntArrayList (); DoubleArrayList vals = new DoubleArrayList (); layer.forwardingRules_f_de.getNonZeros(rows,cols,vals); for(int cont = 0 ; cont < rows.size () ; cont ++) { final int indexDemand = rows.get (cont); final int indexLink = cols.get (cont); final double splittingRatio = vals.get (cont); XMLUtils.indent(writer, 3); writer.writeEmptyElement("forwardingRule"); writer.writeAttribute("demandId", Long.toString(layer.demands.get(indexDemand).id)); writer.writeAttribute("linkId", Long.toString(layer.links.get(indexLink).id)); writer.writeAttribute("splittingRatio", Double.toString(splittingRatio)); } if (!emptyHopByHopRouting) { XMLUtils.indent(writer, 2); writer.writeEndElement(); } } for (Entry<String, String> entry : layer.attributes.entrySet()) { XMLUtils.indent(writer, 2); writer.writeEmptyElement("attribute"); writer.writeAttribute("key", entry.getKey()); writer.writeAttribute("value", entry.getValue()); } XMLUtils.indent(writer, 1); writer.writeEndElement(); } for (SharedRiskGroup srg : srgs) { boolean emptySRG = srg.attributes.isEmpty() && srg.nodes.isEmpty() && srg.links.isEmpty(); XMLUtils.indent(writer, 1); if (emptySRG) writer.writeEmptyElement("srg"); else writer.writeStartElement("srg"); writer.writeAttribute("id", Long.toString(srg.id)); writer.writeAttribute("meanTimeToFailInHours", Double.toString(srg.meanTimeToFailInHours)); writer.writeAttribute("meanTimeToRepairInHours", Double.toString(srg.meanTimeToRepairInHours)); for (Node node : srg.nodes) { XMLUtils.indent(writer, 2); writer.writeEmptyElement("node"); writer.writeAttribute("id", Long.toString(node.id)); } for (Link link : srg.links) { XMLUtils.indent(writer, 2); writer.writeEmptyElement("link"); writer.writeAttribute("linkId", Long.toString(link.id)); } for (Entry<String, String> entry : srg.attributes.entrySet()) { XMLUtils.indent(writer, 2); writer.writeEmptyElement("attribute"); writer.writeAttribute("key", entry.getKey()); writer.writeAttribute("value", entry.getValue()); } if (!emptySRG) { XMLUtils.indent(writer, 1); writer.writeEndElement(); } } for (DemandLinkMapping d_e : interLayerCoupling.edgeSet()) { for (Entry<Demand,Link> coupling : d_e.demandLinkMapping.entrySet()) { XMLUtils.indent(writer, 1); writer.writeEmptyElement("layerCouplingDemand"); writer.writeAttribute("lowerLayerDemandId", "" + coupling.getKey().id); writer.writeAttribute("upperLayerLinkId", "" + coupling.getValue().id); } for (Entry<MulticastDemand,Set<Link>> coupling : d_e.multicastDemandLinkMapping.entrySet()) { XMLUtils.indent(writer, 1); writer.writeEmptyElement("layerCouplingMulticastDemand"); List<Long> linkIds = new LinkedList<Long> (); for (Link e : coupling.getValue()) linkIds.add (e.id); writer.writeAttribute("lowerLayerDemandId", "" + coupling.getKey().id); writer.writeAttribute("upperLayerLinkIds", CollectionUtils.join(linkIds , " ")); } } for (Entry<String, String> entry : this.attributes.entrySet()) { XMLUtils.indent(writer, 1); writer.writeEmptyElement("attribute"); writer.writeAttribute("key", entry.getKey()); writer.writeAttribute("value", entry.getValue()); } XMLUtils.indent(writer, 0); writer.writeEndElement(); writer.writeEndDocument(); writer.flush(); writer.close(); } catch (XMLStreamException e) { throw new RuntimeException(e); } } /** * <p>Sets the failure state (up or down) for all the links in the given layer. If no layer is provided, the default layer is assumed.</p> * @param setAsUp {@code true} up, {@code false} down * @param optionalLayerParameter Network layer (optional) */ public void setAllLinksFailureState (boolean setAsUp , NetworkLayer ... optionalLayerParameter) { checkIsModifiable(); NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); if (setAsUp) setLinksAndNodesFailureState (layer.links , null , null , null); else setLinksAndNodesFailureState (null , layer.links , null , null); } /** * <p>Sets the failure state (up or down) for all the nodes.</p> * @param setAsUp {@code true} up, {@code false} down */ public void setAllNodesFailureState (boolean setAsUp) { checkIsModifiable(); if (setAsUp) setLinksAndNodesFailureState (null , null , nodes , null); else setLinksAndNodesFailureState (null , null , null , nodes); } /** * <p>Changes the failure state of the links and updates the routes/trees/segments (they do not carry traffic nor occupy capacity), and hop-by-hop routing * (no traffic is forwarded in links down)</p> * @param linksToSetAsUp Links to set as up * @param linksToSetAsDown Links to set as down * @param nodesToSetAsUp Nodes to set as up * @param nodesToSetAsDown Nodes to set as down */ public void setLinksAndNodesFailureState (Collection<Link> linksToSetAsUp , Collection<Link> linksToSetAsDown , Collection<Node> nodesToSetAsUp , Collection<Node> nodesToSetAsDown) { checkIsModifiable(); if (linksToSetAsUp != null) checkInThisNetPlan(linksToSetAsUp); if (linksToSetAsDown != null) checkInThisNetPlan(linksToSetAsDown); if (nodesToSetAsUp != null) checkInThisNetPlan(nodesToSetAsUp); if (nodesToSetAsDown != null) checkInThisNetPlan(nodesToSetAsDown); Set<Link> affectedLinks = new HashSet<Link> (); // System.out.println ("setLinksAndNodesFailureState : links to up: " + linksToSetAsUp + ", links to down: " + linksToSetAsDown + ", nodes up: " + nodesToSetAsUp + ", nodes down: " + nodesToSetAsDown); /* Take all the affected links, including the in/out links of nodes. Update their state up/down and the cache of links and nodes up down, but not the routes, trees etc. */ if (linksToSetAsUp != null) for (Link e : linksToSetAsUp) if (!e.isUp) { e.isUp = true; e.layer.cache_linksDown.remove (e); affectedLinks.add (e); } if (linksToSetAsDown != null) for (Link e : linksToSetAsDown) if (e.isUp) { e.isUp = false; e.layer.cache_linksDown.add (e); affectedLinks.add (e); } if (nodesToSetAsUp != null) for (Node node : nodesToSetAsUp) if (!node.isUp) { node.isUp = true; cache_nodesDown.remove (node); affectedLinks.addAll (node.cache_nodeOutgoingLinks); affectedLinks.addAll (node.cache_nodeIncomingLinks); } if (nodesToSetAsDown != null) for (Node node : nodesToSetAsDown) if (node.isUp) { node.isUp = false; cache_nodesDown.add (node); affectedLinks.addAll (node.cache_nodeOutgoingLinks); affectedLinks.addAll (node.cache_nodeIncomingLinks); } Set<NetworkLayer> affectedLayersHopByHopRouting = new HashSet<NetworkLayer> (); Set<Route> affectedRoutesSourceRouting = new HashSet<Route> (); Set<ProtectionSegment> affectedSegmentsSourceRouting = new HashSet<ProtectionSegment> (); Set<MulticastTree> affectedTrees = new HashSet<MulticastTree> (); for (Link link : affectedLinks) { if (link.layer.routingType == RoutingType.HOP_BY_HOP_ROUTING) { if (affectedLayersHopByHopRouting.contains(link.layer)) continue; affectedLayersHopByHopRouting.add (link.layer); } else { affectedRoutesSourceRouting.addAll (link.cache_traversingRoutes.keySet()); affectedSegmentsSourceRouting.addAll (link.cache_traversingSegments); } affectedTrees.addAll (link.cache_traversingTrees); } // System.out.println ("affected routes: " + affectedRoutesSourceRouting); for (NetworkLayer affectedLayer : affectedLayersHopByHopRouting) for (Demand d : affectedLayer.demands) d.layer.updateHopByHopRoutingDemand(d); netPlan.updateFailureStateRoutesTreesSegments(affectedRoutesSourceRouting); netPlan.updateFailureStateRoutesTreesSegments(affectedSegmentsSourceRouting); netPlan.updateFailureStateRoutesTreesSegments(affectedTrees); if (ErrorHandling.isDebugEnabled()) this.checkCachesConsistency(); } /** * <p>Sets the name of the units in which the offered traffic is measured (e.g. "Gbps") at the given layer. If no layer is provided, default layer is assumed.</p> * @param demandTrafficUnitsName Traffic units name * @param optionalLayerParameter Network layer (optional) */ public void setDemandTrafficUnitsName(String demandTrafficUnitsName , NetworkLayer ... optionalLayerParameter) { checkIsModifiable(); NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); try{ for(Demand d : layer.demands) if (d.coupledUpperLayerLink != null) if (!demandTrafficUnitsName.equals(layer.demandTrafficUnitsName)) throw new Net2PlanException("Demand traffic units name cannot be modified since there is some coupling with other layers"); } catch (Exception e) { e.printStackTrace(); throw e; } layer.demandTrafficUnitsName = demandTrafficUnitsName; } /** * <p>Sets the layer description. If no layer is provided, default layer is used.</p> * @param description Layer description * @param optionalLayerParameter Network layer (optional) */ public void setDescription (String description , NetworkLayer ... optionalLayerParameter) { checkIsModifiable(); NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); layer.description = description; } /** * <p>Adds a new forwarding rule (or override an existing one), to the layer of the demand and link (must be in the same layer).</p> * * <p><b>Important</b>: Routing type must be {@link com.net2plan.utils.Constants.RoutingType#HOP_BY_HOP_ROUTING HOP_BY_HOP_ROUTING}.</p> * @param demand Demand * @param link Link * @param splittingRatio Splitting ratio (fraction of traffic from demand 'd' entering to the origin node of link 'e', going through link 'e'). * Must be equal or greater than 0 and equal or lesser than 1. * @return The previous value of the forwarding rule */ public double setForwardingRule(Demand demand , Link link , double splittingRatio) { checkIsModifiable(); checkInThisNetPlan(demand); final NetworkLayer layer = demand.layer; final double PRECISION_FACTOR = Double.parseDouble(Configuration.getOption("precisionFactor")); checkInThisNetPlanAndLayer(link , demand.layer); layer.checkRoutingType(RoutingType.HOP_BY_HOP_ROUTING); if (splittingRatio < 0) throw new Net2PlanException("Splitting ratio must be greater or equal than zero"); if (splittingRatio > 1) throw new Net2PlanException("Splitting ratio must be lower or equal than one"); double sumOutFde = 0; for (Link e : link.originNode.getOutgoingLinks(layer)) sumOutFde += layer.forwardingRules_f_de.get(demand.index, e.index); final double previousValueFr = layer.forwardingRules_f_de.get(demand.index , link.index); if (sumOutFde + splittingRatio - previousValueFr > 1 + PRECISION_FACTOR) throw new Net2PlanException("The sum of splitting factors for outgoing links cannot exceed one"); layer.forwardingRules_f_de.set(demand.index , link.index , splittingRatio); layer.updateHopByHopRoutingDemand (demand); if (ErrorHandling.isDebugEnabled()) this.checkCachesConsistency(); return previousValueFr; } /** * <p>Adds a set of forwarding rules (or override existing ones). Demands, links and ratio are processed sequentially. All the elements must be in the same layer.</p> * * <p><b>Important</b>: Routing type must be {@link com.net2plan.utils.Constants.RoutingType#HOP_BY_HOP_ROUTING HOP_BY_HOP_ROUTING}.</p> * @param demands Demands * @param links Links * @param splittingFactors Splitting ratios (fraction of traffic from demand 'd' entering to the origin node of link 'e', going through link 'e'). * Each value must be equal or greater than 0 and equal or lesser than 1. * @param includeUnusedRules Inclue {@code true} or not {@code false} unused rules */ public void setForwardingRules(Collection<Demand> demands , Collection<Link> links , Collection<Double> splittingFactors , boolean includeUnusedRules) { checkIsModifiable(); if ((demands.size () != links.size ()) || (demands.size () != splittingFactors.size ())) throw new Net2PlanException ("The number of demands, links and aplitting factors must be the same"); if (demands.isEmpty()) return; NetworkLayer layer = demands.iterator().next().layer; checkInThisNetPlanAndLayer(demands , layer); checkInThisNetPlanAndLayer(links , layer); for (double sf : splittingFactors) if ((sf < 0) || (sf > 1)) throw new Net2PlanException("Splitting ratio must be greater or equal than zero and lower or equal than one"); layer.checkRoutingType(RoutingType.HOP_BY_HOP_ROUTING); final double PRECISION_FACTOR = Double.parseDouble(Configuration.getOption("precisionFactor")); DoubleMatrix2D original_fde = layer.forwardingRules_f_de.copy(); Iterator<Demand> it_d = demands.iterator(); Iterator<Link> it_e = links.iterator(); Iterator<Double> it_sf = splittingFactors.iterator(); Set<Demand> modifiedDemands = new HashSet<Demand> (); while (it_d.hasNext()) { final Demand demand = it_d.next (); final Link link = it_e.next (); final double splittingFactor = it_sf.next(); if (includeUnusedRules || (splittingFactor > 1E-5)) { if (splittingFactor != layer.forwardingRules_f_de.get(demand.index , link.index)) { layer.forwardingRules_f_de.set(demand.index , link.index , splittingFactor); modifiedDemands.add (demand); } } } DoubleMatrix2D A_dn = layer.forwardingRules_f_de.zMult(layer.forwardingRules_Aout_ne , null , 1 , 0 , false , true); // traffic of demand d that leaves node n if (A_dn.size() > 0) if (A_dn.getMaxLocation() [0] > 1 + PRECISION_FACTOR) { layer.forwardingRules_f_de = original_fde; throw new Net2PlanException ("The sum of the splitting factors of the output links of a node cannot exceed one"); } for (Demand demand : modifiedDemands) layer.updateHopByHopRoutingDemand (demand); if (ErrorHandling.isDebugEnabled()) this.checkCachesConsistency(); } /** * <p>Sets the forwarding rules for the given design. Any previous routing * information (either source routing or hop-by-hop routing) will be removed.</p> * @param f_de For each demand <i>d</i> (<i>d = 0</i> refers to the first demand in {@code demandIds}, <i>d = 1</i> * refers to the second one, and so on), and each link <i>e</i> (<i>e = 0</i> refers to the first link in {@code NetPlan} object, <i>e = 1</i> * refers to the second one, and so on), {@code f_de[d][e]} sets the fraction of the traffic from demand <i>d</i> that arrives (or is generated in) node <i>a(e)</i> (the origin node of link <i>e</i>), that is forwarded through link <i>e</i>. It must hold that for every node <i>n</i> different of <i>b(d)</i>, the sum of the fractions <i>f<sub>te</sub></i> along its outgoing links must be lower or equal than 1 * @param optionalLayerParameter Network layer (optional) */ public void setForwardingRules(DoubleMatrix2D f_de , NetworkLayer ... optionalLayerParameter) { checkIsModifiable(); NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); layer.checkRoutingType(RoutingType.HOP_BY_HOP_ROUTING); int D = layer.demands.size (); int E = layer.links.size (); if (f_de.rows() != D || f_de.columns() != E) throw new Net2PlanException("'f_de' should be a " + D + " x" + E + " matrix (demands x links)"); if ((D == 0) || (E == 0)) { layer.forwardingRules_f_de = f_de; return; } if ((D > 0) && (E > 0)) if ((f_de.getMinLocation() [0] < -1e-3) || (f_de.getMaxLocation() [0] > 1 + 1e-3)) throw new Net2PlanException("Splitting ratios must be greater or equal than zero and lower or equal than one"); final double PRECISION_FACTOR = Double.parseDouble(Configuration.getOption("precisionFactor")); DoubleMatrix2D A_dn = layer.forwardingRules_f_de.zMult(layer.forwardingRules_Aout_ne , null , 1 , 0 , false , true); // traffic of demand d that leaves node n if (A_dn.size () > 0) if (A_dn.getMaxLocation() [0] > 1 + PRECISION_FACTOR) throw new Net2PlanException ("The sum of the splitting factors of the output links of a node cannot exceed one"); layer.forwardingRules_f_de = f_de; for (Demand d : layer.demands) layer.updateHopByHopRoutingDemand(d); if (ErrorHandling.isDebugEnabled()) this.checkCachesConsistency(); } /** * <p>Sets the name of the units in which the link capacity is measured (e.g. "Gbps") at the given layer. If no ayer is provided, the default layer is assumed.</p> * @param name Capacity units name * @param optionalLayerParameter Network layer (optional) */ public void setLinkCapacityUnitsName(String name , NetworkLayer ... optionalLayerParameter) { checkIsModifiable(); NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); try{ for(Link e : layer.links) if ((e.coupledLowerLayerDemand != null) || (e.coupledLowerLayerMulticastDemand != null)) if (!name.equals(layer.linkCapacityUnitsName)) { throw new Net2PlanException("Link capacity units name cannot be modified since there is some coupling with other layers"); } } catch (Exception e) { e.printStackTrace(); throw e; } layer.linkCapacityUnitsName = name; } /** * <p>Sets the network description.</p> * * @param description Description (when {@code null}, it will be set to empty) * @since 0.2.3 */ public void setNetworkDescription(String description) { checkIsModifiable(); networkDescription = description == null ? "" : description; } /** * <p>Sets the default network layer.</p> * @param layer The default network layer */ public void setNetworkLayerDefault (NetworkLayer layer) { checkInThisNetPlan(layer); this.defaultLayer = layer; } /** * <p>Sets the network name.</p> * * @param name Name * @since 0.2.3 */ public void setNetworkName(String name) { checkIsModifiable(); networkName = name == null ? "" : name; } /** * <p>Checks the flow conservation constraints, and returns the traffic carried per demand.</p> * @param x_de Amount of traffic from demand {@code d} (i-th row) transmitted through link e (j-th column) in traffic units * @param xdeValueAsFractionsRespectToDemandOfferedTraffic If {@code true}, {@code x_de} values are measured as fractions [0,1] instead of traffic units * @param optionalLayerParameter Network layer (optional) * @return Carried traffic per demand (i-th position is the demand index and the value is the carried traffic) */ public DoubleMatrix1D checkMatrixDemandLinkCarriedTrafficFlowConservationConstraints (DoubleMatrix2D x_de , boolean xdeValueAsFractionsRespectToDemandOfferedTraffic , NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); final double PRECISION_FACTOR = Double.parseDouble(Configuration.getOption("precisionFactor")); if ((x_de.rows() != layer.demands.size()) || (x_de.columns() != layer.links.size ())) throw new Net2PlanException ("Wrong size of x_de matrix"); if (x_de.size () > 0) if (x_de.getMinLocation() [0] < -PRECISION_FACTOR) throw new Net2PlanException ("Carried traffics cannot be negative"); final DoubleMatrix2D trafficBased_xde = xdeValueAsFractionsRespectToDemandOfferedTraffic? DoubleFactory2D.sparse.diagonal(getVectorDemandOfferedTraffic(layer)).zMult (x_de , null) : x_de; final DoubleMatrix2D A_ne = netPlan.getMatrixNodeLinkIncidence(layer); final DoubleMatrix2D Div_dn = trafficBased_xde.zMult (A_ne.viewDice () , null); // out traffic minus in traffic of demand d in node n DoubleMatrix1D r_d = DoubleFactory1D.dense.make (layer.demands.size ()); for (Demand d : layer.demands) { final double outTrafficOfIngress = Div_dn.get(d.index , d.ingressNode.index); final double outTrafficOfEgress = Div_dn.get(d.index , d.egressNode.index); if (outTrafficOfIngress < -PRECISION_FACTOR) throw new Net2PlanException ("Flow conservation constraints are not met for this matrix (demand index " + d.index + ")"); if (outTrafficOfEgress > PRECISION_FACTOR) throw new Net2PlanException ("Flow conservation constraints are not met for this matrix (demand index " + d.index + ")"); if (Math.abs(outTrafficOfIngress + outTrafficOfEgress) > PRECISION_FACTOR) throw new Net2PlanException ("Flow conservation constraints are not met for this matrix (demand index " + d.index + ")"); IntArrayList ns = new IntArrayList (); DoubleArrayList vals = new DoubleArrayList (); Div_dn.viewRow (d.index).getNonZeros(ns , vals); for (int cont = 0; cont < ns.size () ; cont ++) { final double divergence = vals.get(cont); final int n = ns.get (cont); if ((divergence > PRECISION_FACTOR) && (n != d.ingressNode.index)) throw new Net2PlanException ("Flow conservation constraints are not met for this matrix (demand index " + d.index + ")"); if ((divergence < -PRECISION_FACTOR) && (n != d.egressNode.index)) throw new Net2PlanException ("Flow conservation constraints are not met for this matrix (demand index " + d.index + ")"); } r_d.set(d.index , outTrafficOfIngress); } return r_d; } /** * <p>Checks the flow conservation constraints, and returns the traffic carried per input output node pair.</p> * @param x_te Amount of traffic targeted to node {@code t} (i-th row) transmitted through link e (j-th column) in traffi units * @param optionalLayerParameter Network layer (optional) * @return Carried traffic per input (i-th row) output (j-th column) node pair */ public DoubleMatrix2D checkMatrixDestinationLinkCarriedTrafficFlowConservationConstraints (DoubleMatrix2D x_te , NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); final double PRECISION_FACTOR = Double.parseDouble(Configuration.getOption("precisionFactor")); if ((x_te.rows() != nodes.size()) || (x_te.columns() != layer.links.size ())) throw new Net2PlanException ("Wrong size of x_te matrix"); if (x_te.size () > 0) if (x_te.getMinLocation() [0] < -PRECISION_FACTOR) throw new Net2PlanException ("Carried traffics cannot be negative"); final DoubleMatrix2D A_ne = netPlan.getMatrixNodeLinkIncidence(layer); DoubleMatrix2D h_st = DoubleFactory2D.dense.make (nodes.size () , nodes.size ()); final DoubleMatrix2D Div_tn = x_te.zMult (A_ne.viewDice () , null); // out traffic minus in traffic of demand d in node n for (Node t : nodes) for (Node n : nodes) { final double h_nt = Div_tn.get(t.index,n.index); if ((t == n) && (h_nt > PRECISION_FACTOR)) throw new Net2PlanException ("Flow conservation constraints are not met for this matrix (destination index " + t.index + ", node index " + n.index + ")"); else if ((t != n) && (h_nt < -PRECISION_FACTOR)) throw new Net2PlanException ("Flow conservation constraints are not met for this matrix (destination index " + t.index + ", node index " + n.index + ")"); h_st.set (n.index , t.index , h_nt); } return h_st; } /** * <p>Adds traffic routes (or forwarding rules, depending on the routing type) from demand-link routing at the given layer. * If no layer is provided, default layer is assumed. If the routing is SOURCE-ROUTING, the new routing will have no closed nor open loops. If the routing is * HOP-BY-HOP routing, the new routing can have open loops. However, if the routing has closed loops (which were not removed), a {@code ClosedCycleRoutingException} * will be thrown.</p> * @param x_de Matrix containing the amount of traffic from demand <i>d</i> (rows) which traverses link <i>e</i> (columns) * @param xdeValueAsFractionsRespectToDemandOfferedTraffic If {@code true}, {code x_de} contains the fraction of the carried traffic (between 0 and 1) * @param removeCycles If true, the open and closed loops are eliminated from the routing before any processing is done. The form in which this is done guarantees that the resulting * routing uses the same or less traffic in the links for each destination than the original routing. For removing the cycles, * the method calls to {@code removeCyclesFrom_xte} using the default ILP solver defined in Net2Plan, and no limit in the maximum solver running time. * @param optionalLayerParameter Network layer (optional) */ public void setRoutingFromDemandLinkCarriedTraffic(DoubleMatrix2D x_de , boolean xdeValueAsFractionsRespectToDemandOfferedTraffic , boolean removeCycles , NetworkLayer ... optionalLayerParameter) { checkIsModifiable(); NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); final DoubleMatrix2D trafficBased_xde = xdeValueAsFractionsRespectToDemandOfferedTraffic? DoubleFactory2D.sparse.diagonal(getVectorDemandOfferedTraffic(layer)).zMult (x_de , null) : x_de; checkMatrixDemandLinkCarriedTrafficFlowConservationConstraints (trafficBased_xde , false , layer); if (removeCycles) x_de = GraphUtils.removeCyclesFrom_xde(nodes, layer.links, layer.demands, x_de, xdeValueAsFractionsRespectToDemandOfferedTraffic , Configuration.getOption("defaultILPSolver") , null, -1); if (layer.routingType == RoutingType.SOURCE_ROUTING) { removeAllRoutes(layer); removeAllProtectionSegments(layer); /* Convert the x_de variables into a set of routes for each demand */ List<Demand> demands = new LinkedList<Demand>(); List<Double> x_p = new LinkedList<Double>(); List<List<Link>> seqLinks = new LinkedList<List<Link>>(); GraphUtils.convert_xde2xp(nodes , layer.links , layer.demands , trafficBased_xde , demands, x_p, seqLinks); /* Update netPlan object adding the calculated routes */ Iterator<Demand> demands_it = demands.iterator(); Iterator<List<Link>> seqLinks_it = seqLinks.iterator(); Iterator<Double> x_p_it = x_p.iterator(); while(x_p_it.hasNext()) { Demand demand = demands_it.next(); List<Link> seqLinks_thisPath = seqLinks_it.next(); double x_p_thisPath = x_p_it.next(); addRoute(demand , x_p_thisPath , x_p_thisPath , seqLinks_thisPath, null); } } else if (layer.routingType == RoutingType.HOP_BY_HOP_ROUTING) { DoubleMatrix2D f_de = GraphUtils.convert_xde2fde(nodes , layer.links , layer.demands , trafficBased_xde); setForwardingRules(f_de, layer); } else throw new RuntimeException ("Bad"); if (ErrorHandling.isDebugEnabled()) this.checkCachesConsistency(); } /** * <p>Adds traffic routes (or forwarding rules, depending on the routing type) from destination-link routing at the given layer. * If no layer is provided, default layer is assumed. If the routing is SOURCE-ROUTING, the new routing will have no closed nor open loops. If the routing is * HOP-BY-HOP routing, the new routing can have open loops. However, if the routing has closed loops (which were not removed), a {@code ClosedCycleRoutingException} * will be thrown </p> * @param x_te For each destination node <i>t</i> (rows), and each link <i>e</i> (columns), {@code f_te[t][e]} represents the traffic targeted to node <i>t</i> that arrives (or is generated * in) node a(e) (the origin node of link e), that is forwarded through link e * @param removeCycles If true, the open and closed loops are eliminated from the routing before any processing is done. The form in which this is done guarantees that the resulting * routing uses the same or less traffic in the links for each destination than the original routing. For removing the cycles, * the method calls to {@code removeCyclesFrom_xte} using the default ILP solver defined in Net2Plan, and no limit in the maximum solver running time. * @param optionalLayerParameter Network layer (optional) */ public void setRoutingFromDestinationLinkCarriedTraffic(DoubleMatrix2D x_te , boolean removeCycles , NetworkLayer ... optionalLayerParameter) { checkIsModifiable(); NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); checkMatrixDestinationLinkCarriedTrafficFlowConservationConstraints(x_te , layer); if (removeCycles) x_te = GraphUtils.removeCyclesFrom_xte(nodes, layer.links, getMatrixNode2NodeOfferedTraffic(layer), x_te, Configuration.getOption("defaultILPSolver") , null, -1); if (layer.routingType == RoutingType.SOURCE_ROUTING) { removeAllRoutes(layer); removeAllProtectionSegments(layer); /* Convert the x_te variables into a set of routes for each demand */ DoubleMatrix2D f_te = GraphUtils.convert_xte2fte(nodes , layer.links , x_te); List<Demand> demands_p = new LinkedList<Demand>(); List<Double> x_p = new LinkedList<Double>(); List<List<Link>> seqLinks_p = new LinkedList<List<Link>>(); GraphUtils.convert_fte2xp(nodes , layer.links , layer.demands , getVectorDemandOfferedTraffic(layer) , f_te, demands_p, x_p, seqLinks_p); /* Update netPlan object adding the calculated routes */ Iterator<Demand> demands_it = demands_p.iterator(); Iterator<Double> x_p_it = x_p.iterator(); Iterator<List<Link>> seqLinks_it = seqLinks_p.iterator(); while(x_p_it.hasNext()) { Demand demand = demands_it.next(); List<Link> seqLinks_thisPath = seqLinks_it.next(); double x_p_thisPath = x_p_it.next(); addRoute(demand , x_p_thisPath , x_p_thisPath , seqLinks_thisPath, null); } } else if (layer.routingType == RoutingType.HOP_BY_HOP_ROUTING) { DoubleMatrix2D f_te = GraphUtils.convert_xte2fte(nodes , layer.links , x_te); DoubleMatrix2D f_de = GraphUtils.convert_fte2fde(layer.demands , f_te); setForwardingRules(f_de, layer); } else throw new RuntimeException ("Bad"); if (ErrorHandling.isDebugEnabled()) this.checkCachesConsistency(); } /** * <p>Sets the routing type at the given layer. If there is some previous routing information, it * will be converted to the new type. If no layer is provided, default layer is assumed. In the conversion from * HOP-BY-HOP to SOURCE-ROUTING: (i) the demands with open loops are routed so these loops are removed, and the resulting * routing consumes the same or less bandwidth in the demand traversed links, (ii) the demands with closed loops are * routed so that the traffic that enters the closed loops is not carried. These modifications are done since open or close * loops would require routes with an infinite number of links to be fairly represented.</p> * * @param optionalLayerParameter Network layer (optional) * @param newRoutingType {@link com.net2plan.utils.Constants.RoutingType RoutingType} */ public void setRoutingType(RoutingType newRoutingType , NetworkLayer ... optionalLayerParameter) { checkIsModifiable(); NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); if (layer.routingType == newRoutingType) return; switch(newRoutingType) { case HOP_BY_HOP_ROUTING: { layer.forwardingRules_x_de = GraphUtils.convert_xp2xde(layer.links, layer.demands, layer.routes); layer.forwardingRules_Aout_ne = this.getMatrixNodeLinkOutgoingIncidence(layer); layer.forwardingRules_Ain_ne = this.getMatrixNodeLinkIncomingIncidence(layer); layer.forwardingRules_f_de = DoubleFactory2D.sparse.make (layer.demands.size(),layer.links.size ()); DoubleMatrix2D A_dn = layer.forwardingRules_x_de.zMult(layer.forwardingRules_Aout_ne , null , 1 , 0 , false , true); // traffic of demand d that leaves node n removeAllProtectionSegments(layer); removeAllRoutes(layer); layer.routingType = RoutingType.HOP_BY_HOP_ROUTING; IntArrayList ds = new IntArrayList(); IntArrayList es = new IntArrayList(); DoubleArrayList trafs = new DoubleArrayList(); layer.forwardingRules_x_de.getNonZeros(ds , es , trafs); for (int cont = 0 ; cont < ds.size() ; cont ++) { final int d = ds.get(cont); final int e = es.get(cont); double outTraf = A_dn.get (d , layer.links.get(e).originNode.index); layer.forwardingRules_f_de.set (d , e , outTraf == 0? 0 : trafs.get(cont) / outTraf ); } /* update link and demand carried traffics, and demand routing cycle type */ layer.forwardingRules_x_de.assign(0); // this is recomputed inside next call for (Demand d : layer.demands) layer.updateHopByHopRoutingDemand(d); break; } case SOURCE_ROUTING: { layer.routingType = RoutingType.SOURCE_ROUTING; removeAllRoutes(layer); removeAllProtectionSegments(layer); for (Link e : layer.links) { e.carriedTrafficSummingRoutesAndCarriedTrafficByProtectionSegments = e.getMulticastCarriedTraffic(); e.occupiedCapacitySummingRoutesAndCarriedTrafficByProtectionSegments = e.getMulticastOccupiedLinkCapacity(); } for (Demand d : layer.demands) d.carriedTraffic = 0; List<Demand> d_p = new LinkedList<Demand> (); List<Double> x_p = new LinkedList<Double> (); List<List<Link>> pathList = new LinkedList<List<Link>> (); GraphUtils.convert_xde2xp(nodes, layer.links , layer.demands , layer.forwardingRules_x_de , d_p, x_p, pathList); Iterator<Demand> it_demand = d_p.iterator(); Iterator<Double> it_xp = x_p.iterator(); Iterator<List<Link>> it_pathList = pathList.iterator(); while (it_demand.hasNext()) { final Demand d = it_demand.next(); final double trafficInPath = it_xp.next(); final List<Link> seqLinks = it_pathList.next(); addRoute(d, trafficInPath , trafficInPath , seqLinks , null); } // final double PRECISION_FACTOR = Double.parseDouble(Configuration.getOption("precisionFactor")); // final int E = layer.links.size (); // Graph<Node, Link> graph = JUNGUtils.getGraphFromLinkMap(nodes , layer.links); // Transformer<Link, Double> nev = JUNGUtils.getEdgeWeightTransformer(null); // for (Demand demand : layer.demands) // { // Node ingressNode = demand.getIngressNode(); // Node egressNode = demand.getEgressNode(); // DoubleMatrix1D x_e = layer.forwardingRules_x_de.viewRow(demand.getIndex()).copy(); // // Collection<Link> incomingLinksToIngressNode = graph.getInEdges(ingressNode); // Collection<Link> outgoingLinksFromIngressNode = graph.getOutEdges(ingressNode); // if (incomingLinksToIngressNode == null) incomingLinksToIngressNode = new LinkedHashSet<Link>(); // if (outgoingLinksFromIngressNode == null) outgoingLinksFromIngressNode = new LinkedHashSet<Link>(); // // double divAtIngressNode = 0; // for(Link link : outgoingLinksFromIngressNode) // divAtIngressNode += x_e.get(link.getIndex()); // // for(Link link : incomingLinksToIngressNode) // divAtIngressNode -= x_e.get(link.getIndex()); // // while (divAtIngressNode > PRECISION_FACTOR) // { // List<Link> candidateLinks = new LinkedList<Link>(); for (int e = 0; e < E ; e ++) if (x_e.get(e) > 0)candidateLinks.add(layer.links.get(e)); // if (candidateLinks.isEmpty()) break; // // Graph<Node, Link> auxGraph = JUNGUtils.filterGraph(graph, null, null, candidateLinks, null); // List<Link> seqLinks = JUNGUtils.getShortestPath(auxGraph, nev, ingressNode, egressNode); // if (seqLinks.isEmpty()) break; // // double trafficInPath = Double.MAX_VALUE; // for(Link link : seqLinks) trafficInPath = Math.min(trafficInPath, x_e.get(link.getIndex())); // // trafficInPath = Math.min(trafficInPath, divAtIngressNode); // divAtIngressNode -= trafficInPath; // // addRoute(demand, trafficInPath , trafficInPath , seqLinks , null); // // for (Link link : seqLinks) // { // double newTrafficValue_thisLink = x_e.get(link.getIndex()) - trafficInPath; // if (newTrafficValue_thisLink < PRECISION_FACTOR) x_e.set(link.getIndex() , 0); // else x_e.set(link.getIndex(), newTrafficValue_thisLink); // } // // if (divAtIngressNode <= PRECISION_FACTOR) break; // } // } /* Remove previous 'hop-by-hop' routing information */ layer.forwardingRules_f_de = null; layer.forwardingRules_x_de = null; layer.forwardingRules_Ain_ne = null; layer.forwardingRules_Aout_ne = null; break; } default: throw new RuntimeException("Bad - Unknown routing type " + newRoutingType); } if (ErrorHandling.isDebugEnabled()) this.checkCachesConsistency(); } /** * <p>Sets the traffic demands at the given layer from a given traffic matrix, removing any previous * demand. If no layer is provided, default layer is assumed.</p> * * <p><b>Important</b>: Matrix values must be strictly non-negative and matrix size have to be <i>N</i>x<i>N</i> (where <i>N</i> is the number of nodes) * * @param optionalLayerParameter Network layer (optional * @param trafficMatrix Traffic matrix * @since 0.3.1 */ public void setTrafficMatrix(DoubleMatrix2D trafficMatrix, NetworkLayer ... optionalLayerParameter) { trafficMatrix = NetPlan.adjustToTolerance(trafficMatrix); checkIsModifiable(); NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); removeAllDemands(layer); int N = nodes.size (); if ((trafficMatrix.rows () != N) || (trafficMatrix.columns() != N)) throw new Net2PlanException ("Bad number of rows-columns in the traffic matrix"); if (trafficMatrix.size () > 0) if (trafficMatrix.getMinLocation() [0] < 0) throw new Net2PlanException ("Offered traffic must be a non-negative"); for (int n1 = 0 ; n1 < N ; n1 ++) for (int n2 = 0 ; n2 < N ; n2 ++) { if (n1 == n2) continue; addDemand(nodes.get(n1) , nodes.get(n2) , trafficMatrix.getQuick(n1, n2), null , layer); } if (ErrorHandling.isDebugEnabled()) this.checkCachesConsistency(); } /** * <p>Sets the vector of the offered traffic per demand, at the given layer. i-th vector corresponds to i-th index of the element. If no layer is provided, * the defaulf layer is assumed.</p> * @param offeredTrafficVector Offered traffic vector * @param optionalLayerParameter Network layer (optional) */ public void setVectorDemandOfferedTraffic(DoubleMatrix1D offeredTrafficVector , NetworkLayer ... optionalLayerParameter) { offeredTrafficVector = NetPlan.adjustToTolerance(offeredTrafficVector); checkIsModifiable(); NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); if (offeredTrafficVector.size() != layer.demands.size()) throw new Net2PlanException ("Wrong veector size"); if (offeredTrafficVector.size () > 0) if (offeredTrafficVector.getMinLocation() [0] < 0) throw new Net2PlanException("Offered traffic must be greater or equal than zero"); for (Demand d : layer.demands) { d.offeredTraffic = offeredTrafficVector.get (d.index); if (layer.routingType == RoutingType.HOP_BY_HOP_ROUTING) layer.updateHopByHopRoutingDemand(d); } if (ErrorHandling.isDebugEnabled()) this.checkCachesConsistency(); } /** * <p>Sets the vector of the link capacities, at the given layer. i-th vector corresponds to i-th index of the element. If no layer is provided, the defaulf layer is assumed.</p> * @param linkCapacities Link capacities * @param optionalLayerParameter Network layer (optional) */ public void setVectorLinkCapacity (DoubleMatrix1D linkCapacities , NetworkLayer ... optionalLayerParameter) { linkCapacities = NetPlan.adjustToTolerance(linkCapacities); checkIsModifiable(); NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); if (linkCapacities.size() != layer.links.size()) throw new Net2PlanException ("Wrong veector size"); if (linkCapacities.size () > 0) if (linkCapacities.getMinLocation() [0] < 0) throw new Net2PlanException("Link capacities must be greater or equal than zero"); for (Link e : layer.links) if ((e.coupledLowerLayerDemand != null) || (e.coupledLowerLayerMulticastDemand != null)) throw new Net2PlanException ("Coupled links cannot change its capacity"); for (Link e : layer.links) e.capacity = linkCapacities.get (e.index); if (ErrorHandling.isDebugEnabled()) this.checkCachesConsistency(); } /** * <p>Sets the vector of the offered traffic per multicast demand, at the given layer. i-th vector corresponds to i-th index of the element. If no layer is provided, the defaulf layer is * assumed.</p> * @param offeredTrafficVector Offered traffic vector * @param optionalLayerParameter Network layer (optional) */ public void setVectorMulticastDemandOfferedTraffic(DoubleMatrix1D offeredTrafficVector , NetworkLayer ... optionalLayerParameter) { offeredTrafficVector = NetPlan.adjustToTolerance(offeredTrafficVector); checkIsModifiable(); NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); if (offeredTrafficVector.size() != layer.multicastDemands.size()) throw new Net2PlanException ("Wrong veector size"); if (offeredTrafficVector.size () > 0) if (offeredTrafficVector.getMinLocation() [0] < 0) throw new Net2PlanException("Offered traffic must be greater or equal than zero"); for (MulticastDemand d : layer.multicastDemands) d.offeredTraffic = offeredTrafficVector.get (d.index); if (ErrorHandling.isDebugEnabled()) this.checkCachesConsistency(); } /** * <p>Sets the vector of the multicast trees carried traffics and occupied link capacities, at the given layer. i-th vector corresponds to i-th index of the element. * If occupied link capacities are {@code null}, the same amount as the carried traffic is assumed. If no layer is provided, the defaulf layer is assumed.</p> * @param carriedTraffic Carried traffic vector * @param occupiedLinkCapacity Occupied link capacity vector * @param optionalLayerParameter Network layer (optional) */ public void setVectorMulticastTreeCarriedTrafficAndOccupiedLinkCapacities (DoubleMatrix1D carriedTraffic , DoubleMatrix1D occupiedLinkCapacity , NetworkLayer ... optionalLayerParameter) { carriedTraffic = NetPlan.adjustToTolerance(carriedTraffic); occupiedLinkCapacity = NetPlan.adjustToTolerance(occupiedLinkCapacity); checkIsModifiable(); NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); if (occupiedLinkCapacity == null) occupiedLinkCapacity = carriedTraffic; if (carriedTraffic.size() != layer.multicastTrees.size()) throw new Net2PlanException ("Wrong veector size"); if (carriedTraffic.size() != occupiedLinkCapacity.size()) throw new Net2PlanException ("Wrong veector size"); if (carriedTraffic.size () > 0) if (carriedTraffic.getMinLocation() [0] < 0) throw new Net2PlanException("Carried traffics must be greater or equal than zero"); if (occupiedLinkCapacity.size () > 0) if (occupiedLinkCapacity.getMinLocation() [0] < 0) throw new Net2PlanException("Occupied link capacities must be greater or equal than zero"); for (MulticastTree t : layer.multicastTrees) t.setCarriedTraffic(carriedTraffic.get (t.index) , occupiedLinkCapacity.get(t.index)); if (ErrorHandling.isDebugEnabled()) this.checkCachesConsistency(); } /** * <p>Sets the vector of the reserved capacity for protection segments, at the given layer. i-th vector corresponds to i-th index of the element. If no layer is provided, the defaulf layer is * assumed.</p> * @param segmentCapacities Protection segment reserved capacities vector * @param optionalLayerParameter Network layer (optional) */ public void setVectorProtectionSegmentReservedCapacity (DoubleMatrix1D segmentCapacities , NetworkLayer ... optionalLayerParameter) { segmentCapacities = NetPlan.adjustToTolerance(segmentCapacities); checkIsModifiable(); NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); if (segmentCapacities.size() != layer.protectionSegments.size()) throw new Net2PlanException ("Wrong veector size"); if (segmentCapacities.size () > 0) if (segmentCapacities.getMinLocation() [0] < 0) throw new Net2PlanException("Protection segment reserved capacities must be greater or equal than zero"); layer.checkRoutingType(RoutingType.SOURCE_ROUTING); for (ProtectionSegment s : layer.protectionSegments) s.capacity = segmentCapacities.get (s.index); if (ErrorHandling.isDebugEnabled()) this.checkCachesConsistency(); } /** * <p>Sets the vector of the route carried traffics and occupied link capacities, at the given layer. i-th vector corresponds to i-th index of the element. * If occupied link capacities are {@code null}, the same amount as the carried traffic is assumed. If no layer is provided, the defaulf layer is assumed,</p> * @param carriedTraffic Carried traffic vector * @param occupiedLinkCapacity Occupied link capacity vector * @param optionalLayerParameter Network layer (optional) */ public void setVectorRouteCarriedTrafficAndOccupiedLinkCapacities (DoubleMatrix1D carriedTraffic , DoubleMatrix1D occupiedLinkCapacity , NetworkLayer ... optionalLayerParameter) { carriedTraffic = NetPlan.adjustToTolerance(carriedTraffic); occupiedLinkCapacity = NetPlan.adjustToTolerance(occupiedLinkCapacity); checkIsModifiable(); NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); if (occupiedLinkCapacity == null) occupiedLinkCapacity = carriedTraffic; if (carriedTraffic.size() != layer.routes.size()) throw new Net2PlanException ("Wrong veector size"); if (carriedTraffic.size() != occupiedLinkCapacity.size()) throw new Net2PlanException ("Wrong veector size"); if (carriedTraffic.size () > 0) if (carriedTraffic.getMinLocation() [0] < 0) throw new Net2PlanException("Carried traffics must be greater or equal than zero"); if (occupiedLinkCapacity.size () > 0) if (occupiedLinkCapacity.getMinLocation() [0] < 0) throw new Net2PlanException("Occupied link capacities must be greater or equal than zero"); layer.checkRoutingType(RoutingType.SOURCE_ROUTING); for (Route r : layer.routes) r.setCarriedTraffic(carriedTraffic.get (r.index) , occupiedLinkCapacity.get(r.index)); if (ErrorHandling.isDebugEnabled()) this.checkCachesConsistency(); } /** * Returns a {@code String} representation of the network design. * * @return String representation of the network design * @since 0.2.0 */ @Override public String toString() { return toString(layers); } /** * Returns a {@code String} representation of the network design only for the * given layers. * * @param layers Network layers * @return String representation of the network design */ public String toString(Collection<NetworkLayer> layers) { StringBuilder netPlanInformation = new StringBuilder(); String NEWLINE = StringUtils.getLineSeparator(); int N = nodes.size (); if (N == 0) { netPlanInformation.append("Empty network"); // return netPlanInformation.toString(); } int L = getNumberOfLayers(); int numSRGs = getNumberOfSRGs(); netPlanInformation.append("Network information"); netPlanInformation.append(NEWLINE); netPlanInformation.append("--------------------------------"); netPlanInformation.append(NEWLINE).append(NEWLINE); netPlanInformation.append("Name: ").append(this.networkName).append(NEWLINE); netPlanInformation.append("Description: ").append(networkDescription).append(NEWLINE); Map<String, String> networkAttributes_thisNetPlan = this.attributes; netPlanInformation.append("Attributes: "); netPlanInformation.append(networkAttributes_thisNetPlan.isEmpty() ? "none" : StringUtils.mapToString(networkAttributes_thisNetPlan, "=", ", ")); netPlanInformation.append(NEWLINE); netPlanInformation.append("Number of layers: ").append(L).append(NEWLINE); netPlanInformation.append("Default layer: ").append(defaultLayer.id).append(NEWLINE); netPlanInformation.append("Number of nodes: ").append(N).append(NEWLINE); netPlanInformation.append("Number of SRGs: ").append(numSRGs).append(NEWLINE); netPlanInformation.append(NEWLINE); netPlanInformation.append("Node information"); netPlanInformation.append(NEWLINE); netPlanInformation.append("--------------------------------"); netPlanInformation.append(NEWLINE).append(NEWLINE); for (Node node : nodes) { String nodeInformation = String.format("n%d (id %d), state: %s, position: (%.3g, %.3g), name: %s, attributes: %s", node.index , node.id , !node.isUp ? "down" : "up", node.nodeXYPositionMap.getX(), node.nodeXYPositionMap.getY(), node.name , node.attributes.isEmpty() ? "none" : node.attributes); netPlanInformation.append(nodeInformation); netPlanInformation.append(NEWLINE); } for (NetworkLayer layer : layers) { netPlanInformation.append(NEWLINE); netPlanInformation.append("Layer ").append(layer.index + " (id: " + layer.id + ")").append(" information"); netPlanInformation.append(NEWLINE); netPlanInformation.append("--------------------------------"); netPlanInformation.append(NEWLINE).append(NEWLINE); netPlanInformation.append("Name: ").append(layer.name).append(NEWLINE); netPlanInformation.append("Description: ").append(layer.description).append(NEWLINE); netPlanInformation.append("Link capacity units: ").append(layer.linkCapacityUnitsName).append(NEWLINE); netPlanInformation.append("Demand traffic units: ").append(layer.demandTrafficUnitsName).append(NEWLINE); netPlanInformation.append("Routing type: ").append(layer.routingType).append(NEWLINE); if (!layer.attributes.isEmpty()) { netPlanInformation.append("Attributes: "); netPlanInformation.append(StringUtils.mapToString(layer.attributes , "=", ", ")); netPlanInformation.append(NEWLINE); } netPlanInformation.append("Number of links: ").append(layer.links.size ()).append(NEWLINE); netPlanInformation.append("Number of demands: ").append(layer.demands.size ()).append(NEWLINE); netPlanInformation.append("Number of multicast demands: ").append(layer.multicastDemands.size ()).append(NEWLINE); netPlanInformation.append("Number of multicast trees: ").append(layer.multicastTrees.size ()).append(NEWLINE); if (layer.routingType == RoutingType.SOURCE_ROUTING) { netPlanInformation.append("Number of routes: ").append(layer.routes.size ()).append(NEWLINE); netPlanInformation.append("Number of protection segments: ").append(layer.protectionSegments.size ()).append(NEWLINE); } if (!layer.links.isEmpty()) { netPlanInformation.append(NEWLINE); netPlanInformation.append("Link information"); netPlanInformation.append(NEWLINE); netPlanInformation.append("--------------------------------"); netPlanInformation.append(NEWLINE).append(NEWLINE); for (Link link : layer.links) { String linkInformation = String.format("e%d (id %d), n%d (%s) -> n%d (%s), state: %s, capacity: %.3g, length: %.3g km, propagation speed: %.3g km/s, carried traffic (incl. segments): %.3g , occupied capacity (incl. traffic in segments): %.3g, attributes: %s", link.index, link.id , link.originNode.id, link.originNode.name, link.destinationNode.id, link.destinationNode.name , !link.isUp? "down" : "up", link.capacity , link.lengthInKm , link.propagationSpeedInKmPerSecond, link.carriedTrafficSummingRoutesAndCarriedTrafficByProtectionSegments , link.occupiedCapacitySummingRoutesAndCarriedTrafficByProtectionSegments , link.attributes.isEmpty() ? "none" : link.attributes); netPlanInformation.append(linkInformation); if (link.coupledLowerLayerDemand != null) netPlanInformation.append(String.format(", associated to demand %d (id %d) at layer %d (id %d)", link.coupledLowerLayerDemand.index , link.coupledLowerLayerDemand.id , link.coupledLowerLayerDemand.layer.index , link.coupledLowerLayerDemand.layer.id)); if (link.coupledLowerLayerMulticastDemand != null) netPlanInformation.append(String.format(", associated to multicast demand %d (id %d) at layer %d (id %d)", link.coupledLowerLayerMulticastDemand.index , link.coupledLowerLayerMulticastDemand.id , link.coupledLowerLayerMulticastDemand.layer.index , link.coupledLowerLayerMulticastDemand.layer.id)); netPlanInformation.append(NEWLINE); } } if (!layer.demands.isEmpty()) { netPlanInformation.append(NEWLINE); netPlanInformation.append("Demand information"); netPlanInformation.append(NEWLINE); netPlanInformation.append("--------------------------------"); netPlanInformation.append(NEWLINE).append(NEWLINE); for (Demand demand : layer.demands) { String demandInformation = String.format("d%d (id %d), n%d (%s) -> n%d (%s), offered traffic: %.3g, carried: %.3g, attributes: %s", demand.index , demand.id, demand.ingressNode.id, demand.ingressNode.name , demand.egressNode.id, demand.egressNode.name , demand.offeredTraffic , demand.carriedTraffic , demand.attributes.isEmpty() ? "none" : demand.attributes); netPlanInformation.append(demandInformation); if (demand.coupledUpperLayerLink != null) netPlanInformation.append(String.format(", associated to link %d (id %d) in layer %d (id %d)", demand.coupledUpperLayerLink.index, demand.coupledUpperLayerLink.id , demand.coupledUpperLayerLink.layer.index , demand.coupledUpperLayerLink.layer.id)); netPlanInformation.append(NEWLINE); } } if (!layer.multicastDemands.isEmpty()) { netPlanInformation.append(NEWLINE); netPlanInformation.append("Multicast demand information"); netPlanInformation.append(NEWLINE); netPlanInformation.append("--------------------------------"); netPlanInformation.append(NEWLINE).append(NEWLINE); for (MulticastDemand demand : layer.multicastDemands) { String demandInformation = String.format("d%d (id %d, n%d (%s) -> " , demand.index , demand.id , demand.ingressNode.id, demand.ingressNode.name); for (Node n : demand.egressNodes) demandInformation += " " + n + " (" + n.name + ")"; demandInformation += String.format (", offered traffic: %.3g, carried: %.3g, attributes: %s", demand.offeredTraffic, demand.carriedTraffic , demand.attributes.isEmpty() ? "none" : demand.attributes); netPlanInformation.append(demandInformation); if (demand.coupledUpperLayerLinks != null) { netPlanInformation.append(", associated to links "); for (Link e : demand.coupledUpperLayerLinks.values ()) netPlanInformation.append (" " + e.index + " (id " + e.id + "), "); netPlanInformation.append(" of layer: " + demand.coupledUpperLayerLinks.values ().iterator().next().index + " (id " + demand.coupledUpperLayerLinks.values ().iterator().next().id + ")"); } netPlanInformation.append(NEWLINE); } } if (layer.routingType == RoutingType.SOURCE_ROUTING) { if (!layer.routes.isEmpty()) { netPlanInformation.append(NEWLINE); netPlanInformation.append("Routing information"); netPlanInformation.append(NEWLINE); netPlanInformation.append("--------------------------------"); netPlanInformation.append(NEWLINE).append(NEWLINE); for (Route route : layer.routes) { String str_seqNodes = CollectionUtils.join(route.seqNodesRealPath , " => "); String str_seqLinks = CollectionUtils.join(route.seqLinksRealPath , " => "); String backupSegments = route.potentialBackupSegments.isEmpty() ? "none" : CollectionUtils.join(route.potentialBackupSegments, ", "); String routeInformation = String.format("r%d (id %d), demand: d%d (id %d), carried traffic: %.3g, occupied capacity: %.3g, seq. links: %s, seq. nodes: %s, backup segments: %s, attributes: %s", route.index , route.id , route.demand.index , route.demand.id, route.carriedTraffic, route.occupiedLinkCapacity, str_seqLinks, str_seqNodes, backupSegments, route.attributes.isEmpty() ? "none" : route.attributes); netPlanInformation.append(routeInformation); netPlanInformation.append(NEWLINE); } } if (!layer.protectionSegments.isEmpty()) { netPlanInformation.append(NEWLINE); netPlanInformation.append("Protection segment information"); netPlanInformation.append(NEWLINE); netPlanInformation.append("--------------------------------"); netPlanInformation.append(NEWLINE).append(NEWLINE); for (ProtectionSegment segment : layer.protectionSegments) { String str_seqLinks = CollectionUtils.join(segment.seqLinks, " => "); String str_seqNodes = CollectionUtils.join(segment.seqNodes, " => "); String segmentInformation = String.format("s%d (id %d), reserved bandwidth: %.3g, seq. links: %s, seq. nodes: %s, attributes: %s", segment.index , segment.id , segment.capacity , str_seqLinks, str_seqNodes, segment.attributes.isEmpty() ? "none" : segment.attributes); netPlanInformation.append(segmentInformation); netPlanInformation.append(NEWLINE); } } if (!layer.multicastTrees.isEmpty()) { netPlanInformation.append(NEWLINE); netPlanInformation.append("Multicast trees information"); netPlanInformation.append(NEWLINE); netPlanInformation.append("--------------------------------"); netPlanInformation.append(NEWLINE).append(NEWLINE); for (MulticastTree tree : layer.multicastTrees) { String str_seqNodes = CollectionUtils.join(tree.cache_traversedNodes , " , "); String str_seqLinks = CollectionUtils.join(tree.linkSet , " , "); String treeInformation = String.format("mt%d (id %d), multicast demand: md%d (id %d), carried traffic: %.3g, occupied capacity: %.3g, links: %s, nodes: %s, attributes: %s", tree.index , tree.id , tree.demand.index , tree.demand.id , tree.carriedTraffic, tree.occupiedLinkCapacity, str_seqLinks, str_seqNodes, tree.attributes.isEmpty() ? "none" : tree.attributes); netPlanInformation.append(treeInformation); netPlanInformation.append(NEWLINE); } } } else { netPlanInformation.append(NEWLINE); netPlanInformation.append("Forwarding information"); netPlanInformation.append(NEWLINE); netPlanInformation.append("--------------------------------"); netPlanInformation.append(NEWLINE).append(NEWLINE); netPlanInformation.append("f_de: ").append(NEWLINE); netPlanInformation.append(DoubleFactory2D.dense.make (layer.forwardingRules_f_de.toArray())).append(NEWLINE); netPlanInformation.append("x_de: ").append(NEWLINE); netPlanInformation.append(layer.forwardingRules_x_de).append(NEWLINE); } } if (!srgs.isEmpty()) { netPlanInformation.append(NEWLINE); netPlanInformation.append("Shared-risk group information"); netPlanInformation.append(NEWLINE); netPlanInformation.append("--------------------------------"); netPlanInformation.append(NEWLINE).append(NEWLINE); for (SharedRiskGroup srg : srgs) { String aux_nodes = srg.nodes.isEmpty() ? "none" : CollectionUtils.join(srg.nodes, " "); String aux_links = srg.links.isEmpty() ? "none" : CollectionUtils.join(srg.links, " "); String aux_mttf = StringUtils.secondsToYearsDaysHoursMinutesSeconds(srg.meanTimeToFailInHours * 3600); String aux_mttr = StringUtils.secondsToYearsDaysHoursMinutesSeconds(srg.meanTimeToRepairInHours * 3600); String srgInformation = String.format("srg%d (id %d), nodes: %s, links: %s, mttf: %s, mttr: %s, attributes: %s", srg.index , srg.id , aux_nodes, aux_links.toString(), aux_mttf, aux_mttr, srg.attributes.isEmpty() ? "none" : srg.attributes); netPlanInformation.append(srgInformation); netPlanInformation.append(NEWLINE); } } return netPlanInformation.toString(); } // /** // * Returns an unmodifiable view of the network. // * // * @return An unmodifiable view of the network // * @since 0.2.3 // */ // public NetPlan unmodifiableView() // { // NetPlan netPlan = new NetPlan(); // netPlan.assignFrom(this); // netPlan.isModifiable = false; // return netPlan; // } /** * <p>Sets the {@code NetPlan} so it cannot be modified</p> * @param isModifiable }If {@code true}, the object can be modified, {@code false} otherwise * @return The previous modifiable state */ public boolean setModifiableState (boolean isModifiable) { final boolean oldState = this.isModifiable; this.isModifiable = isModifiable; return oldState; } /** * <p>Checks if the given layer is valid and belongs to this {@code NetPlan} design. Throws and exception if the input is invalid.</p> * @param optionalLayer Network layer (optional) * @return The given layer (or the defaukt layer if no input was given) */ public NetworkLayer checkInThisNetPlanOptionalLayerParameter (NetworkLayer ... optionalLayer) { if (optionalLayer.length >= 2) throw new Net2PlanException ("None or one layer parameter can be supplied"); if (optionalLayer.length == 1) { checkInThisNetPlan(optionalLayer [0]); return optionalLayer [0]; } return defaultLayer; } NetworkElement getPeerElementInThisNetPlan (NetworkElement e) { NetworkElement res; if (e instanceof NetPlan) throw new RuntimeException ("Bad"); if (e.netPlan == null) throw new RuntimeException ("Bad"); if (e.netPlan == this) throw new RuntimeException ("Bad"); if (e instanceof Node) res = this.cache_id2NodeMap.get (e.id); else if (e instanceof Demand) res = this.cache_id2DemandMap.get (e.id); else if (e instanceof ProtectionSegment) res = this.cache_id2ProtectionSegmentMap.get (e.id); else if (e instanceof Link) res = this.cache_id2LinkMap.get (e.id); else if (e instanceof MulticastDemand) res = this.cache_id2MulticastDemandMap.get (e.id); else if (e instanceof MulticastTree) res = this.cache_id2MulticastTreeMap.get (e.id); else if (e instanceof Node) res = this.cache_id2NodeMap.get (e.id); else if (e instanceof Route) res = this.cache_id2RouteMap.get (e.id); else if (e instanceof SharedRiskGroup) res = this.cache_id2srgMap.get (e.id); else throw new RuntimeException ("Bad"); if (res.index != e.index) throw new RuntimeException ("Bad"); return res; } /* Receives a collection of routes, segments or multicast trees, and updates its failure state according to the traversing links and nodes */ void updateFailureStateRoutesTreesSegments (Collection<? extends NetworkElement> set) { for (NetworkElement thisElement : set) updateFailureStateRoutesTreesSegments (thisElement); } /* Receives a route, segment or multicast tree, and updates its failure state according to the traversing links and nodes */ void updateFailureStateRoutesTreesSegments (NetworkElement thisElement) { if (thisElement instanceof Route) { Route route = (Route) thisElement; boolean previouslyUp = !route.layer.cache_routesDown.contains (route); boolean isUp = true; for (Link e : route.seqLinksRealPath) if (!e.isUp) { isUp = false; break; } if (isUp) for (Node e : route.seqNodesRealPath) if (!e.isUp) { isUp = false; break; } // System.out.println ("Route :" + route + ", previously up:" + previouslyUp + ", isUp: " + isUp); // for (Link e : route.seqLinksRealPath) // System.out.println ("Link " + e + ", isUp: " + e.isUp); // for (Node n : route.seqNodesRealPath) // System.out.println ("Node " + n + ", isUp: " + n.isUp); if (isUp == previouslyUp) return; if (isUp) // from down to up { if (route.occupiedLinkCapacity != 0) throw new RuntimeException ("Bad"); if (route.carriedTraffic != 0) throw new RuntimeException ("Bad"); route.layer.cache_routesDown.remove (route); // System.out.println ("down to up: route.layer.cache_routesDown: " + route.layer.cache_routesDown); } else { if (route.occupiedLinkCapacity != route.occupiedLinkCapacityIfNotFailing) throw new RuntimeException ("Bad"); if (route.carriedTraffic != route.carriedTrafficIfNotFailing) throw new RuntimeException ("Bad"); route.layer.cache_routesDown.add (route); // System.out.println ("up to down : route.layer.cache_routesDown: " + route.layer.cache_routesDown); } final boolean previousDebug = ErrorHandling.isDebugEnabled(); ErrorHandling.setDebug(false); route.setCarriedTraffic(route.carriedTrafficIfNotFailing , route.occupiedLinkCapacityIfNotFailing); ErrorHandling.setDebug(previousDebug); } else if (thisElement instanceof MulticastTree) { MulticastTree tree = (MulticastTree) thisElement; boolean previouslyUp = !tree.layer.cache_multicastTreesDown.contains (tree); boolean isUp = true; for (Link e : tree.linkSet) if (!e.isUp) { isUp = false; break; } for (Node e : tree.cache_traversedNodes) if (!e.isUp) { isUp = false; break; } if (isUp == previouslyUp) return; if (isUp) // from down to up { if (tree.occupiedLinkCapacity != 0) throw new RuntimeException ("Bad"); if (tree.carriedTraffic != 0) throw new RuntimeException ("Bad"); tree.layer.cache_multicastTreesDown.remove (tree); } else { if (tree.occupiedLinkCapacity != tree.occupiedLinkCapacityIfNotFailing) throw new RuntimeException ("Bad"); if (tree.carriedTraffic != tree.carriedTrafficIfNotFailing) throw new RuntimeException ("Bad"); tree.layer.cache_multicastTreesDown.add (tree); } final boolean previousDebug = ErrorHandling.isDebugEnabled(); ErrorHandling.setDebug(false); tree.setCarriedTraffic(tree.carriedTrafficIfNotFailing , tree.occupiedLinkCapacityIfNotFailing); // updates links since all are up ErrorHandling.setDebug(previousDebug); } else if (thisElement instanceof ProtectionSegment) { ProtectionSegment segment = (ProtectionSegment) thisElement; boolean previouslyUp = !segment.layer.cache_segmentsDown.contains (segment); boolean isUp = true; for (Link e : segment.seqLinks) if (!e.isUp) { isUp = false; break; } for (Node e : segment.seqNodes) if (!e.isUp) { isUp = false; break; } if (isUp == previouslyUp) return; if (isUp) // from down to up { segment.layer.cache_segmentsDown.remove (segment); } else { segment.layer.cache_segmentsDown.add (segment); } } else throw new RuntimeException ("Bad"); } // // private Map<String,String> copyAttributeMap (Map<String,String> map) // { // Map<String,String> m = new HashMap<String,String> (); // for (Entry<String,String> e : map.entrySet ()) m.put(e.getKey(),e.getValue()); // return m; // } void checkCachesConsistency (List<? extends NetworkElement> list , Map<Long,? extends NetworkElement> cache , boolean mustBeSameSize) { if (mustBeSameSize) if (cache.size () != list.size ()) throw new RuntimeException ("Bad: cache: " + cache+ ", list: " + list); for (int cont = 0 ; cont < list.size () ; cont ++) { NetworkElement e = list.get(cont); if (e.index != cont) throw new RuntimeException ("Bad"); if (cache.get(e.id) == null) throw new RuntimeException ("Bad"); if (!e.equals (cache.get(e.id))) throw new RuntimeException ("Bad: list: " + list + ", cache: " + cache + ", e: " + e + ", cache.get(e.id): " + cache.get(e.id)); if (e != cache.get(e.id)) throw new RuntimeException ("Bad"); } } /** * <p>For debug purposes: Checks the consistency of the internal cache (nodes, srgs, layers, links, demands, multicast demands, multicast trees, routes, protection segments). If any * inconsistency is found an exception is thrown.</p> */ public void checkCachesConsistency () { // System.out.println ("Check caches consistency of object: " + hashCode()); checkCachesConsistency (nodes , cache_id2NodeMap , true); checkCachesConsistency (srgs , cache_id2srgMap , true); checkCachesConsistency (layers , cache_id2LayerMap , true); for (NetworkLayer layer : layers) { checkCachesConsistency (layer.links , cache_id2LinkMap , false); checkCachesConsistency (layer.demands , cache_id2DemandMap , false); checkCachesConsistency (layer.multicastDemands , cache_id2MulticastDemandMap , false); checkCachesConsistency (layer.multicastTrees , cache_id2MulticastTreeMap , false); checkCachesConsistency (layer.protectionSegments , cache_id2ProtectionSegmentMap, false); checkCachesConsistency (layer.routes , cache_id2RouteMap , false); } this.checkInThisNetPlan (nodes); this.checkInThisNetPlan (srgs); this.checkInThisNetPlan (layers); this.checkInThisNetPlan (defaultLayer); for (Node node : nodes) node.checkCachesConsistency(); for (SharedRiskGroup srg : srgs) srg.checkCachesConsistency(); for (NetworkLayer layer : layers) { this.checkInThisNetPlanAndLayer (layer.links , layer); this.checkInThisNetPlanAndLayer (layer.demands , layer); this.checkInThisNetPlanAndLayer (layer.multicastDemands , layer); this.checkInThisNetPlanAndLayer (layer.multicastTrees , layer); this.checkInThisNetPlanAndLayer (layer.routes , layer); this.checkInThisNetPlanAndLayer (layer.protectionSegments , layer); layer.checkCachesConsistency(); for (Link link : layer.links) link.checkCachesConsistency(); for (Demand demand : layer.demands) demand.checkCachesConsistency(); for (MulticastDemand demand : layer.multicastDemands) demand.checkCachesConsistency(); for (Route route : layer.routes) route.checkCachesConsistency(); for (MulticastTree tree : layer.multicastTrees) tree.checkCachesConsistency(); for (ProtectionSegment segment : layer.protectionSegments) segment.checkCachesConsistency(); if (layer.routingType == RoutingType.HOP_BY_HOP_ROUTING) { for (int d = 0 ; d < layer.demands.size() ; d ++) { final Demand demand = layer.demands.get (d); for (int e = 0 ; e < layer.links.size () ; e ++) { final Link link = layer.links.get(e); final double f_de = layer.forwardingRules_f_de.get(d, e); final double x_de = layer.forwardingRules_x_de.get(d, e); if (f_de < 0) throw new RuntimeException ("Bad"); if (f_de > 1) throw new RuntimeException ("Bad"); final Node a_e = layer.links.get(e).originNode; double linkInitialNodeOutTraffic = 0; double linkInitialNodeOutRules = 0; for (Link outLink : a_e.getOutgoingLinks(layer)) { final int out_a_e = outLink.index; linkInitialNodeOutTraffic += layer.forwardingRules_x_de.get(d, out_a_e); linkInitialNodeOutRules += layer.forwardingRules_f_de.get(d, out_a_e); } final boolean linkUp = link.isUp && link.originNode.isUp && link.destinationNode.isUp; double linkInitialNodeInTraffic = (link.originNode == demand.ingressNode)? demand.offeredTraffic : 0; for (Link inLink : a_e.getIncomingLinks(layer)) linkInitialNodeInTraffic += layer.forwardingRules_x_de.get(d, inLink.index); if (linkInitialNodeOutRules > 1 + 1E-3) throw new RuntimeException ("Bad"); if (!linkUp && (x_de > 1E-3))throw new RuntimeException ("Bad. outTraffic: " + linkInitialNodeOutTraffic + " and link " + link + " is down. NetPlan: " + this); if (linkUp && (linkInitialNodeInTraffic > 1e-3)) if (Math.abs(f_de - x_de/linkInitialNodeInTraffic) > 1e-4) throw new RuntimeException ("Bad. demand index: " + d + ", link : " + link + " (isUp? )" + link.isUp + ", nodeInTraffic: " + linkInitialNodeInTraffic + ", x_de: " + x_de + ", f_de: " + f_de + ", f_de - x_de/nodeInTraffic: " + (f_de - x_de/linkInitialNodeInTraffic)); if (linkInitialNodeOutTraffic < 1e-3) if (x_de > 1e-3) throw new RuntimeException ("Bad"); } } } } /* Check the interlayer object */ Set<NetworkLayer> layersAccordingToInterLayer = interLayerCoupling.vertexSet(); if (!layersAccordingToInterLayer.containsAll(layers)) throw new RuntimeException ("Bad"); if (layersAccordingToInterLayer.size () != layers.size()) throw new RuntimeException ("Bad"); for (DemandLinkMapping mapping : interLayerCoupling.edgeSet()) { NetworkLayer linkLayer = mapping.getLinkSideLayer(); NetworkLayer demandLayer = mapping.getDemandSideLayer(); linkLayer.checkAttachedToNetPlanObject(this); demandLayer.checkAttachedToNetPlanObject(this); for (Entry<Demand,Link> e : mapping.getDemandMap().entrySet()) { e.getKey().checkAttachedToNetPlanObject(this); e.getValue().checkAttachedToNetPlanObject(this); } } if (layers.get (defaultLayer.index) != defaultLayer) throw new RuntimeException ("Bad"); } static double adjustToTolerance (double val) { final double PRECISION_FACTOR = Double.parseDouble(Configuration.getOption("precisionFactor")); return (Math.abs(val) < PRECISION_FACTOR)? 0 : val; } static DoubleMatrix1D adjustToTolerance (DoubleMatrix1D vals) { final double PRECISION_FACTOR = Double.parseDouble(Configuration.getOption("precisionFactor")); return vals.copy ().assign (new DoubleFunction () { public double apply (double x) { return Math.abs(x) < PRECISION_FACTOR ? 0 : x; } }); } static DoubleMatrix2D adjustToTolerance (DoubleMatrix2D vals) { final double PRECISION_FACTOR = Double.parseDouble(Configuration.getOption("precisionFactor")); return vals.copy ().assign (new DoubleFunction () { public double apply (double x) { return Math.abs(x) < PRECISION_FACTOR ? 0 : x; } }); } }
src/main/java/com/net2plan/interfaces/networkDesign/NetPlan.java
/******************************************************************************* * Copyright (c) 2016 Pablo Pavon-Marino. * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v2.1 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl.html * * Contributors: * Pablo Pavon-Marino - Jose-Luis Izquierdo-Zaragoza, up to version 0.3.1 * Pablo Pavon-Marino - from version 0.4.0 onwards ******************************************************************************/ package com.net2plan.interfaces.networkDesign; import java.awt.geom.Point2D; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import javax.xml.stream.FactoryConfigurationError; import javax.xml.stream.XMLStreamException; import javax.xml.stream.events.XMLEvent; import org.apache.commons.lang3.mutable.MutableLong; import org.codehaus.stax2.XMLInputFactory2; import org.codehaus.stax2.XMLOutputFactory2; import org.codehaus.stax2.XMLStreamReader2; import org.codehaus.stax2.XMLStreamWriter2; import org.jgrapht.experimental.dag.DirectedAcyclicGraph; import com.net2plan.internal.AttributeMap; import com.net2plan.internal.ErrorHandling; import com.net2plan.internal.Version; import com.net2plan.internal.XMLUtils; import com.net2plan.libraries.GraphUtils; import com.net2plan.libraries.GraphUtils.ClosedCycleRoutingException; import com.net2plan.libraries.SRGUtils; import com.net2plan.utils.CollectionUtils; import com.net2plan.utils.Constants.RoutingCycleType; import com.net2plan.utils.Constants.RoutingType; import com.net2plan.utils.DoubleUtils; import com.net2plan.utils.Pair; import com.net2plan.utils.StringUtils; import cern.colt.function.tdouble.DoubleFunction; import cern.colt.list.tdouble.DoubleArrayList; import cern.colt.list.tint.IntArrayList; import cern.colt.matrix.tdouble.DoubleFactory1D; import cern.colt.matrix.tdouble.DoubleFactory2D; import cern.colt.matrix.tdouble.DoubleMatrix1D; import cern.colt.matrix.tdouble.DoubleMatrix2D; /** * <p>Class defining a complete multi-layer network structure. Layers may * contain links, demands, routes and protection segments or forwarding rules, * while nodes and SRGs are defined with a network-wide scope, that is, they * appear in all layers. To simplify handling of single-layer designs, methods that may refer to * layer-specific elements have an optiona input parameter of type {@link com.net2plan.interfaces.networkDesign.NetworkLayer NetworkLayer}. * In case of not using this optional parameter, the action * will be applied to the default layer (by default it is first defined layer), * which can be modified using the {@link #setNetworkLayerDefault(NetworkLayer)} setNetworkLayerDefault())} * method.</p> * * <p>Internal representation of the {@code NetPlan} object is based on:</p> * <ul> * <li>{@link com.net2plan.interfaces.networkDesign.NetworkLayer NetworkLayer} objects.</li> * <li>{@link com.net2plan.interfaces.networkDesign.Node Node} objects.</li> * <li>{@link com.net2plan.interfaces.networkDesign.Link Link} objects.</li> * <li>{@link com.net2plan.interfaces.networkDesign.Route Route} objects (depending on the selected {@link com.net2plan.utils.Constants.RoutingCycleType Routing Type}.</li> * <li>{@link com.net2plan.interfaces.networkDesign.Demand Unicast} or {@link com.net2plan.interfaces.networkDesign.MulticastDemand Multicast} demand objects. </li> * <li>{@link com.net2plan.interfaces.networkDesign.ProtectionSegment Protection Segment} objects.</li> * <li>{@link com.net2plan.interfaces.networkDesign.SharedRiskGroup Shared Risk Group} objects</li> * </ul> * * <p>Each element has a unique identifier (represented as {@code long}) assigned the moment they are created, and two elements * (irregardless of their type) cannot share this identifier. This id is incremental (but not necessarily consecutive) and perpetual (i.e after removing an element identifiers are no renumbered).</p> * <p>Also, elements have an index number that identify them among their own type (nodes, links, etc.). Indexes are renumbered when an element is removed and are zero base, that is the first * element of its type is always 0 and the last is N-1 (where N is the total number of elements of the same type).</p> * * <p>An instance of a NetPlan object can be set as unmodifiable through the * {@link NetPlan#setModifiableState(boolean)} setModifiableState())} method. The instance will work * transparently as {@code NetPlan} object unless you try to change it. Calling * any method that can potentially change the network (e.g. add/set/remove methods) * throws an {@code UnsupportedOperationException}.</p> * * @author Pablo Pavon-Marino, Jose-Luis Izquierdo-Zaragoza * @since 0.2.0 */ public class NetPlan extends NetworkElement { final static String TEMPLATE_CROSS_LAYER_UNITS_NOT_MATCHING = "Link capacity units at layer %d (%s) do not match demand traffic units at layer %d (%s)"; final static String TEMPLATE_NO_MORE_NETWORK_ELEMENTS_ALLOWED = "Maximum number of identifiers in the design reached"; final static String TEMPLATE_NO_MORE_NODES_ALLOWED = "Maximum node identifier reached"; final static String TEMPLATE_NO_MORE_LINKS_ALLOWED = "Maximum link identifier for layer %d reached"; final static String TEMPLATE_NO_MORE_DEMANDS_ALLOWED = "Maximum demand identifier for layer %d reached"; final static String TEMPLATE_NO_MORE_MULTICASTDEMANDS_ALLOWED = "Maximum multicast demand identifier for layer %d reached"; final static String TEMPLATE_NO_MORE_ROUTES_ALLOWED = "Maximum route identifier for layer %d reached"; final static String TEMPLATE_NO_MORE_MULTICASTTREES_ALLOWED = "Maximum multicast tree identifier for layer %d reached"; final static String TEMPLATE_NO_MORE_SEGMENTS_ALLOWED = "Maximum protection segment identifier for layer %d reached"; final static String TEMPLATE_NO_MORE_SRGS_ALLOWED = "Maximum SRG identifier reached"; final static String TEMPLATE_NOT_ACTIVE_LAYER = "Layer %d is not in the network"; final static String TEMPLATE_NOT_ACTIVE_NODE = "Node %d is not in the network"; final static String TEMPLATE_NOT_ACTIVE_LINK = "Link %d is not in the network"; final static String TEMPLATE_NOT_ACTIVE_DEMAND = "Demand %d is not in the network"; final static String TEMPLATE_NOT_ACTIVE_MULTICASTDEMAND = "Multicast demand %d is not in the network"; final static String TEMPLATE_NOT_ACTIVE_ROUTE = "Route %d is not in the network"; final static String TEMPLATE_NOT_ACTIVE_MULTICASTTREE = "Multicast tree %d is not in the network"; final static String TEMPLATE_NOT_ACTIVE_FORWARDING_RULE = "Forwarding rule (%d, %d) is not in the network"; final static String TEMPLATE_NOT_ACTIVE_SEGMENT = "Protection segment %d is not in the network"; final static String TEMPLATE_NOT_ACTIVE_SRG = "SRG %d is not in the network"; final static String TEMPLATE_DEMAND_NOT_ACTIVE_IN_LAYER = "Demand %d is not in layer %d"; final static String TEMPLATE_LINK_NOT_ACTIVE_IN_LAYER = "Link %d is not in layer %d"; final static String TEMPLATE_ROUTE_NOT_ACTIVE_IN_LAYER = "Route %d is not in layer %d"; final static String TEMPLATE_MULTICASTDEMAND_NOT_ACTIVE_IN_LAYER = "Multicast demand %d is not in layer %d"; final static String TEMPLATE_MULTICASTTREE_NOT_ACTIVE_IN_LAYER = "Multicast tree %d is not in layer %d"; final static String TEMPLATE_PROTECTIONSEGMENT_NOT_ACTIVE_IN_LAYER = "Protection segment %d is not in layer %d"; final static String TEMPLATE_FORWARDINGRULE_NOT_ACTIVE_IN_LAYER = "Forwarding rule %d is not in layer %d"; final static String TEMPLATE_ROUTE_NOT_ALL_LINKS_SAME_LAYER = "Not all of the links of the route belong to the same layer"; final static String TEMPLATE_SEGMENT_NOT_ALL_LINKS_SAME_LAYER = "Not all of the links of the protection segment belong to the same layer"; final static String TEMPLATE_MULTICASTTREE_NOT_ALL_LINKS_SAME_LAYER = "Not all of the links of the multicast tree belong to the same layer"; final static String TEMPLATE_NOT_OF_THE_SAME_LAYER_ROUTE_AND_SEGMENT = "The route %d and the segment %d are of different layers (%d, %d)"; final static String UNMODIFIABLE_EXCEPTION_STRING = "Unmodifiable NetState object - can't be changed"; final static String KEY_STRING_BIDIRECTIONALCOUPLE = "bidirectionalCouple"; RoutingType DEFAULT_ROUTING_TYPE = RoutingType.SOURCE_ROUTING; boolean isModifiable; String networkDescription; String networkName; NetworkLayer defaultLayer; MutableLong nextElementId; ArrayList<NetworkLayer> layers; ArrayList<Node> nodes; ArrayList<SharedRiskGroup> srgs; HashSet<Node> cache_nodesDown; Map<Long,Node> cache_id2NodeMap; Map<Long,NetworkLayer> cache_id2LayerMap; Map<Long,Link> cache_id2LinkMap; Map<Long,Demand> cache_id2DemandMap; Map<Long,MulticastDemand> cache_id2MulticastDemandMap; Map<Long,Route> cache_id2RouteMap; Map<Long,MulticastTree> cache_id2MulticastTreeMap; Map<Long,ProtectionSegment> cache_id2ProtectionSegmentMap; Map<Long,SharedRiskGroup> cache_id2srgMap; DirectedAcyclicGraph<NetworkLayer, DemandLinkMapping> interLayerCoupling; /** * <p>Default constructor. Creates an empty design</p> * * @since 0.4.0 */ public NetPlan() { super (null , 0 , 0 , new AttributeMap()); this.netPlan = this; DEFAULT_ROUTING_TYPE = RoutingType.SOURCE_ROUTING; isModifiable = true; networkDescription = ""; networkName = ""; nextElementId = new MutableLong(1); layers = new ArrayList<NetworkLayer> (); nodes = new ArrayList<Node> (); srgs= new ArrayList<SharedRiskGroup> (); cache_nodesDown = new HashSet<Node> (); this.cache_id2NodeMap = new HashMap <Long,Node> (); this.cache_id2LayerMap = new HashMap <Long,NetworkLayer> (); this.cache_id2srgMap= new HashMap<Long,SharedRiskGroup> (); this.cache_id2LinkMap = new HashMap<Long,Link> (); this.cache_id2DemandMap = new HashMap<Long,Demand> (); this.cache_id2MulticastDemandMap = new HashMap<Long,MulticastDemand> (); this.cache_id2RouteMap = new HashMap<Long,Route> (); this.cache_id2MulticastTreeMap = new HashMap<Long,MulticastTree> (); this.cache_id2ProtectionSegmentMap = new HashMap<Long,ProtectionSegment> (); interLayerCoupling = new DirectedAcyclicGraph<NetworkLayer, DemandLinkMapping>(DemandLinkMapping.class); defaultLayer = addLayer("Layer 0", null, null, null, null); } /********************************************************************************************************/ /********************************************************************************************************/ /********************************* INIT BLOCK ***********************************************************************/ /********************************************************************************************************/ /********************************************************************************************************/ /********************************************************************************************************/ /********************************************************************************************************/ /** * <p>Generates a new network design from a given {@code .n2p} file.</p> * * @param file {@code .n2p} file * @since 0.2.0 */ public NetPlan(File file) { this(); NetPlan np = loadFromFile(file); if (ErrorHandling.isDebugEnabled()) np.checkCachesConsistency(); assignFrom(np); if (ErrorHandling.isDebugEnabled()) this.checkCachesConsistency(); // System.out.println ("End NetPlan(File file): " + netPlan + " ----------- "); } /** * <p>Generates a new network design from an input stream.</p> * * @param inputStream Input stream * @since 0.3.1 */ public NetPlan(InputStream inputStream) { this(); try { XMLInputFactory2 xmlInputFactory = (XMLInputFactory2) XMLInputFactory2.newInstance(); XMLStreamReader2 xmlStreamReader = (XMLStreamReader2) xmlInputFactory.createXMLStreamReader(inputStream); while(xmlStreamReader.hasNext()) { int eventType = xmlStreamReader.next(); switch (eventType) { case XMLEvent.START_ELEMENT: String elementName = xmlStreamReader.getName().toString(); if (!elementName.equals("network")) throw new RuntimeException("Root element must be 'network'"); IReaderNetPlan netPlanFormat; int index = xmlStreamReader.getAttributeIndex(null, "version"); if (index == -1) { System.out.println ("Version 1"); netPlanFormat = new ReaderNetPlan_v1(); } else { int version = xmlStreamReader.getAttributeAsInt(index); switch(version) { case 2: System.out.println ("Version 2"); netPlanFormat = new ReaderNetPlan_v2(); break; case 3: System.out.println ("Version 3"); netPlanFormat = new ReaderNetPlan_v3(); break; case 4: System.out.println ("Version 4"); netPlanFormat = new ReaderNetPlan_v4 (); break; default: throw new Net2PlanException("Wrong version number"); } } netPlanFormat.create(this, xmlStreamReader); if (ErrorHandling.isDebugEnabled()) this.checkCachesConsistency(); return; default: break; } } } catch (Net2PlanException e) { if (ErrorHandling.isDebugEnabled()) ErrorHandling.printStackTrace(e); throw(e); } catch (FactoryConfigurationError | Exception e) { if (ErrorHandling.isDebugEnabled()) ErrorHandling.printStackTrace(e); throw new RuntimeException(e); } throw new Net2PlanException("Not a valid .n2p file"); } /** * <p>Returns the unique ids of the provided network elements.</p> * @param collection Network elements * @return Unique ids of the provided network elements. If the input {@code Collection} is a {@code Set}, the returned collection is a {@code HashSet}. If the input * {@code Collection} is a {@code List}, an {@code ArrayList} is returned}. */ public static Collection<Long> getIds (Collection<? extends NetworkElement> collection) { Collection<Long> res = (collection instanceof Set)? new HashSet<Long> () : new ArrayList<Long> (collection.size ()); for (NetworkElement e : collection) res.add (e.id); return res; } /** * <p>Returns the indexes of the provided network elements. </p> * @param collection Network elements * @return Indexes of the provided network elements. If the input {@code Collection} is a {@code Set}, the returned collection is a {@code HashSet}. If the input * {@code Collection} is a {@code List}, an {@code ArrayList} is returned}. */ public static Collection<Integer> getIndexes (Collection<? extends NetworkElement> collection) { Collection<Integer> res = (collection instanceof Set)? new HashSet<Integer> () : new ArrayList<Integer> (collection.size ()); for (NetworkElement e : collection) res.add (e.index); return res; } /** * <p>Static factory method to get a {@link com.net2plan.interfaces.networkDesign.NetPlan NetPlan} object from a {@code .n2p} file.</p> * @param file Input file * @return A network design */ public static NetPlan loadFromFile(File file) { try { InputStream inputStream = new FileInputStream(file); NetPlan np = new NetPlan(inputStream); if (ErrorHandling.isDebugEnabled()) np.checkCachesConsistency(); return np; } catch(FileNotFoundException e) { throw new Net2PlanException(e.getMessage()); } } /** * <p>Removes the network element contained in the list which has the given index, and shifts the indexes of the rest of the elements accordingly.</p> * @param x Network elements * @param indexToRemove Index to remove */ static void removeNetworkElementAndShiftIndexes (ArrayList<? extends NetworkElement> x , int indexToRemove) { x.remove(indexToRemove); for (int newIndex = indexToRemove ; newIndex < x.size () ; newIndex ++) { x.get(newIndex).index = newIndex; } } /** * <p>Adds new traffic demands froma traffic matrix given as a {@code DoubleMatrix2D} object.</p> * * <p><b>Important: </b>Previous demands will be removed.</p> * <p><b>Important</b>: Self-demands are not allowed.</p> * * @param trafficMatrix Traffix matrix where i-th row is the ingress node, the j-th column the egress node and each entry the offered traffic * @param optionalLayerParameter Network layer to which to add the demands (optional) * @return A list with the newly created demands * @see com.net2plan.interfaces.networkDesign.Demand */ public List<Demand> addDemandsFromTrafficMatrix (DoubleMatrix2D trafficMatrix , NetworkLayer ... optionalLayerParameter) { trafficMatrix = NetPlan.adjustToTolerance(trafficMatrix); checkIsModifiable(); NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); List<Demand> demands = new LinkedList<Demand> (); if ((trafficMatrix.rows () != nodes.size ()) || (trafficMatrix.columns () != nodes.size ())) throw new Net2PlanException ("Wrong matrix size"); for (int n1 = 0 ; n1 < nodes.size () ; n1 ++) for (int n2 = 0 ; n2 < nodes.size () ; n2 ++) if (n1 != n2) demands.add (addDemand (nodes.get(n1) , nodes.get(n2) , trafficMatrix.get(n1,n2) , null , layer)); if (ErrorHandling.isDebugEnabled()) this.checkCachesConsistency(); return demands; } /** * <p>Adds a new traffic demand.</p> * * <p><b>Important</b>: Self-demands are not allowed.</p> * * @param optionalLayerParameter Network layer to which add the demand (optional) * @param ingressNode Ingress node * @param egressNode Egress node * @param offeredTraffic Offered traffic by this demand. It must be greater or equal than zero * @param attributes Map for user-defined attributes ({@code null} means 'no attribute'). Each key represents the attribute name, whereas value represents the attribute value * @return The newly added demand object * @see com.net2plan.interfaces.networkDesign.Demand */ public Demand addDemand(Node ingressNode, Node egressNode, double offeredTraffic, Map<String, String> attributes , NetworkLayer ... optionalLayerParameter) { offeredTraffic = NetPlan.adjustToTolerance(offeredTraffic); checkIsModifiable(); NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); checkInThisNetPlan(ingressNode); checkInThisNetPlan(egressNode); if (ingressNode.equals (egressNode)) throw new Net2PlanException("Self-demands are not allowed"); if (offeredTraffic < 0) throw new Net2PlanException ("Offered traffic must be non-negative"); final long demandId = nextElementId.longValue(); nextElementId.increment(); Demand demand = new Demand (this , demandId , layer.demands.size () , layer , ingressNode , egressNode , offeredTraffic , new AttributeMap (attributes)); cache_id2DemandMap.put (demandId , demand); layer.demands.add (demand); egressNode.cache_nodeIncomingDemands.add (demand); ingressNode.cache_nodeOutgoingDemands.add (demand); if (layer.routingType == RoutingType.HOP_BY_HOP_ROUTING) { layer.forwardingRules_f_de = DoubleFactory2D.sparse.appendRow(layer.forwardingRules_f_de , DoubleFactory1D.sparse.make (layer.links.size ())); layer.forwardingRules_x_de = DoubleFactory2D.sparse.appendRow(layer.forwardingRules_x_de , DoubleFactory1D.sparse.make (layer.links.size ())); } if (ErrorHandling.isDebugEnabled()) this.checkCachesConsistency(); return demand; } /** * <p>Adds two demands, one in each direction,.</p> * * <p><b>Important</b>: Self-demands are not allowed.</p> * * @param ingressNode Identifier of the ingress node * @param egressNode Identifier of the egress node * @param offeredTraffic Offered traffic by this demand. It must be greater or equal than zero * @param attributes Map for user-defined attributes ({@code null} means 'no attribute'). Each key represents the attribute name, whereas value represents the attribute value * @param optionalLayerParameter Network layer to which add the demand (optional) * @see com.net2plan.interfaces.networkDesign.Demand * @see com.net2plan.utils.Pair * @return A pair object with the two newly created demands */ public Pair<Demand, Demand> addDemandBidirectional(Node ingressNode, Node egressNode, double offeredTraffic, Map<String, String> attributes , NetworkLayer ... optionalLayerParameter) { offeredTraffic = NetPlan.adjustToTolerance(offeredTraffic); checkIsModifiable(); NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); checkInThisNetPlan(ingressNode); checkInThisNetPlan(egressNode); if (ingressNode.equals (egressNode)) throw new Net2PlanException("Self-demands are not allowed"); if (offeredTraffic < 0) throw new Net2PlanException ("Offered traffic must be non-negative"); Demand d1 = addDemand (ingressNode, egressNode, offeredTraffic , attributes , layer); Demand d2 = addDemand (egressNode, ingressNode, offeredTraffic , attributes , layer); d1.setAttribute(KEY_STRING_BIDIRECTIONALCOUPLE , "" + d2.id); d2.setAttribute(KEY_STRING_BIDIRECTIONALCOUPLE , "" + d1.id); if (ErrorHandling.isDebugEnabled()) this.checkCachesConsistency(); return Pair.of (d1,d2); } /** * <p>Adds a new layer.</p> * * @param name Layer name ({@code null} means empty) * @param description Layer description ({@code null} means empty) * @param linkCapacityUnitsName Textual description of link capacity units ({@code null} means empty) * @param demandTrafficUnitsName Textual description of demand traffic units ({@code null} means empty) * @param attributes Map for user-defined attributes ({@code null} means 'no attribute'). Each key represents the attribute name, whereas value represents the attribute value * @return The newly created layer object * @see com.net2plan.interfaces.networkDesign.NetworkLayer */ public NetworkLayer addLayer(String name, String description, String linkCapacityUnitsName, String demandTrafficUnitsName, Map<String, String> attributes) { checkIsModifiable(); if (name == null) name = ""; if (description == null) description = ""; if (linkCapacityUnitsName == null) linkCapacityUnitsName = ""; if (demandTrafficUnitsName == null) demandTrafficUnitsName = ""; final long id = nextElementId.longValue(); nextElementId.increment(); NetworkLayer layer = new NetworkLayer (this , id, layers.size() , demandTrafficUnitsName, description, name, linkCapacityUnitsName, new AttributeMap (attributes)); interLayerCoupling.addVertex(layer); cache_id2LayerMap.put (id , layer); layers.add (layer); if (layers.size () == 1) defaultLayer = layer; if (ErrorHandling.isDebugEnabled()) this.checkCachesConsistency(); return layer; } /** * <p>Creates a new layer and adds the links, routes etc. from the input layer. The number of nodes in the two designs must be the same (the unique ids may differ). * Any coupling information in the origin layer is omitted. Links, demands, multicast demands, routes, multicast trees and protecion segments * will have the same index within the layer in the origin and in the copied layers, but may have different unique ids.</p> * @param origin Layer to be copied * @return The newly created layer object * @see com.net2plan.interfaces.networkDesign.NetworkLayer * @see com.net2plan.interfaces.networkDesign.Node */ public NetworkLayer addLayerFrom (NetworkLayer origin) { checkIsModifiable(); checkInThisNetPlan(origin); ArrayList<Node> originNodes = origin.netPlan.nodes; if (originNodes.size () != nodes.size ()) throw new Net2PlanException ("The number of nodes in the origin design and this design must be the same"); NetworkLayer newLayer = addLayer(origin.name, origin.description, origin.linkCapacityUnitsName, origin.demandTrafficUnitsName, origin.getAttributes()); for (Link originLink : origin.links) this.addLink(nodes.get(originLink.originNode.index) , nodes.get(originLink.destinationNode.index) , originLink.capacity , originLink.lengthInKm , originLink.propagationSpeedInKmPerSecond , originLink.attributes , newLayer); for (Demand originDemand : origin.demands) this.addDemand(nodes.get(originDemand.ingressNode.index) , nodes.get(originDemand.egressNode.index) , originDemand.offeredTraffic , originDemand.attributes , newLayer); for (MulticastDemand originDemand : origin.multicastDemands) { Set<Node> newEgressNodes = new HashSet<Node> (); for (Node originEgress : originDemand.egressNodes) newEgressNodes.add (nodes.get(originEgress.index)); this.addMulticastDemand(nodes.get(originDemand.ingressNode.index) , newEgressNodes , originDemand.offeredTraffic , originDemand.attributes , newLayer); } for (ProtectionSegment originSegment: origin.protectionSegments) { List<Link> newSeqLinks = new LinkedList<Link> (); for (Link originLink : originSegment.seqLinks) newSeqLinks.add (newLayer.links.get (originLink.index)); this.addProtectionSegment(newSeqLinks , originSegment.capacity , originSegment.attributes); } for (Route originRoute : origin.routes) { List<Link> newSeqLinksRealPath = new LinkedList<Link> (); for (Link originLink : originRoute.seqLinksRealPath) newSeqLinksRealPath.add (newLayer.links.get (originLink.index)); Route newRoute = this.addRoute(newLayer.demands.get(originRoute.demand.index) , originRoute.carriedTraffic , originRoute.occupiedLinkCapacity , newSeqLinksRealPath , originRoute.attributes); List<Link> newSeqLinksAndProtectionSegment = new LinkedList<Link> (); for (Link originLink : originRoute.seqLinksAndProtectionSegments) if (originLink instanceof ProtectionSegment) newSeqLinksAndProtectionSegment.add (newLayer.protectionSegments.get (originLink.index)); else newSeqLinksAndProtectionSegment.add (newLayer.links.get (originLink.index)); newRoute.setSeqLinksAndProtectionSegments(newSeqLinksAndProtectionSegment); } for (MulticastTree originTree: origin.multicastTrees) { Set<Link> newSetLinks = new HashSet<Link> (); for (Link originLink : originTree.linkSet) newSetLinks.add (newLayer.links.get (originLink.index)); this.addMulticastTree(newLayer.multicastDemands.get(originTree.demand.index) , originTree.carriedTraffic , originTree.occupiedLinkCapacity , newSetLinks , originTree.attributes); } if (ErrorHandling.isDebugEnabled()) this.checkCachesConsistency(); return newLayer; } /** * <p>Adds a new link.</p> * * <p><b>Important</b>: Self-links are not allowed.</p> * * @param originNode Link origin node * @param destinationNode Link destination node * @param capacity Link capacity. It must be greather or equal to zero * @param lengthInKm Link length. It must be greater or equal than zero. Physical distance between node pais can be otainer through the {@link #getNodePairEuclideanDistance(Node, Node) getNodePairEuclideanDistance} * (for Euclidean distance) or {@link #getNodePairHaversineDistanceInKm(Node, Node) getNodePairHaversineDistanceInKm} (for airlinea distance) methods. * @param propagationSpeedInKmPerSecond Link propagation speed in km/s. It must be greater than zero ({@code Double.MAX_VALUE} means no propagation delay, a non-positive value is changed into * 200000 km/seg, a typical speed of light in the wires) * @param attributes Map for user-defined attributes ({@code null} means 'no attribute'). Each key represents the attribute name, whereas value represents the attribute value * @param optionalLayerParameter Network layer to which add the link (optional) * @return The newly created link object * @see com.net2plan.interfaces.networkDesign.Link * @see com.net2plan.interfaces.networkDesign.Node */ public Link addLink(Node originNode, Node destinationNode , double capacity, double lengthInKm, double propagationSpeedInKmPerSecond, Map<String, String> attributes , NetworkLayer ... optionalLayerParameter) { capacity = NetPlan.adjustToTolerance(capacity); checkIsModifiable(); NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); checkInThisNetPlan(originNode); checkInThisNetPlan(destinationNode); if (originNode.equals (destinationNode)) throw new Net2PlanException("Self-links are not allowed"); if (capacity < 0) throw new Net2PlanException ("Link capacity must be non-negative"); if (lengthInKm < 0) throw new Net2PlanException ("Link length must be non-negative"); if (propagationSpeedInKmPerSecond <= 0) throw new Net2PlanException ("Propagation speed must be positive"); final long linkId = nextElementId.longValue(); nextElementId.increment(); Link link = new Link (this, linkId , layer.links.size (), layer , originNode, destinationNode , lengthInKm , propagationSpeedInKmPerSecond , capacity , new AttributeMap (attributes)); cache_id2LinkMap.put (linkId , link); layer.links.add (link); originNode.cache_nodeOutgoingLinks.add (link); destinationNode.cache_nodeIncomingLinks.add (link); if (layer.routingType == RoutingType.HOP_BY_HOP_ROUTING) { layer.forwardingRules_f_de = DoubleFactory2D.sparse.appendColumn(layer.forwardingRules_f_de , DoubleFactory1D.sparse.make (layer.demands.size ())); layer.forwardingRules_x_de = DoubleFactory2D.sparse.appendColumn(layer.forwardingRules_x_de , DoubleFactory1D.sparse.make (layer.demands.size ())); layer.forwardingRules_Aout_ne = DoubleFactory2D.sparse.appendColumn(layer.forwardingRules_Aout_ne , DoubleFactory1D.sparse.make (netPlan.nodes.size ())); layer.forwardingRules_Ain_ne = DoubleFactory2D.sparse.appendColumn(layer.forwardingRules_Ain_ne , DoubleFactory1D.sparse.make (netPlan.nodes.size ())); layer.forwardingRules_Aout_ne.set(originNode.index, layer.forwardingRules_Aout_ne.columns()-1, 1.0); layer.forwardingRules_Ain_ne.set(destinationNode.index, layer.forwardingRules_Ain_ne.columns()-1, 1.0); } if (ErrorHandling.isDebugEnabled()) this.checkCachesConsistency(); return link; } /** * <p>Adds two links, one in each direction.</p> * <p><b>Important</b>: Self-links are not allowed.</p> * * @param originNode Link origin node * @param destinationNode Link destination node * @param capacity Link capacity. It must be greather or equal to zero * @param lengthInKm Link length. It must be greater or equal than zero. Physical distance between node pais can be otainer through the {@link #getNodePairEuclideanDistance(Node, Node) getNodePairEuclideanDistance} * (for Euclidean distance) or {@link #getNodePairHaversineDistanceInKm(Node, Node) getNodePairHaversineDistanceInKm} (for airlinea distance) methods. * @param propagationSpeedInKmPerSecond Link propagation speed in km/s. It must be greater than zero ({@code Double.MAX_VALUE} means no propagation delay, a non-positive value is changed into * 200000 km/seg, a typical speed of light in the wires) * @param attributes Map for user-defined attributes ({@code null} means 'no attribute'). Each key represents the attribute name, whereas value represents the attribute value * @param optionalLayerParameter Network layer to which add the links (optional) * @return A {@code Pair} object with the two newly created links * @see com.net2plan.interfaces.networkDesign.Link * @see com.net2plan.utils.Pair * @see com.net2plan.interfaces.networkDesign.Node */ public Pair<Link, Link> addLinkBidirectional(Node originNode, Node destinationNode , double capacity, double lengthInKm, double propagationSpeedInKmPerSecond, Map<String, String> attributes , NetworkLayer ... optionalLayerParameter) { capacity = NetPlan.adjustToTolerance(capacity); checkIsModifiable(); NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); checkInThisNetPlan(originNode); checkInThisNetPlan(destinationNode); if (originNode.equals (destinationNode)) throw new Net2PlanException("Self-links are not allowed"); if (capacity < 0) throw new Net2PlanException ("Link capacity must be non-negative"); if (lengthInKm < 0) throw new Net2PlanException ("Link length must be non-negative"); if (propagationSpeedInKmPerSecond <= 0) throw new Net2PlanException ("Propagation speed must be positive"); Link link1 = addLink (originNode, destinationNode , capacity, lengthInKm, propagationSpeedInKmPerSecond, attributes , layer); Link link2 = addLink (destinationNode , originNode , capacity, lengthInKm, propagationSpeedInKmPerSecond, attributes , layer); link1.setAttribute(KEY_STRING_BIDIRECTIONALCOUPLE , "" + link2.id); link2.setAttribute(KEY_STRING_BIDIRECTIONALCOUPLE , "" + link1.id); if (ErrorHandling.isDebugEnabled()) this.checkCachesConsistency(); return Pair.of (link1,link2); } /** * <p>Adds a new multicast traffic demand.</p> * <p><b>Important</b>: Ingress node cannot be also an egress node.</p> * * @param ingressNode Ingress node * @param egressNodes Egress node * @param offeredTraffic Offered traffic of the demand. It must be greater or equal than zero * @param attributes Map for user-defined attributes ({@code null} means 'no attribute'). Each key represents the attribute name, whereas value represents the attribute value * @param optionalLayerParameter Network layer to which add the demand (optional) * @return The newly created multicast demand * @see com.net2plan.interfaces.networkDesign.MulticastDemand * @see com.net2plan.interfaces.networkDesign.Node */ public MulticastDemand addMulticastDemand(Node ingressNode , Set<Node> egressNodes , double offeredTraffic, Map<String, String> attributes , NetworkLayer ... optionalLayerParameter) { offeredTraffic = NetPlan.adjustToTolerance(offeredTraffic); checkIsModifiable(); NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); checkInThisNetPlan(ingressNode); checkInThisNetPlan(egressNodes); if (egressNodes.contains (ingressNode)) throw new Net2PlanException("The ingress node cannot be also an egress node"); if (offeredTraffic < 0) throw new Net2PlanException ("Offered traffics must be non-negative"); for (Node n : egressNodes) n.checkAttachedToNetPlanObject(this); if (egressNodes.contains(ingressNode)) throw new Net2PlanException("The ingress node is also an egress node of the multicast demand"); if (offeredTraffic < 0) throw new Net2PlanException ("Offered traffic must be non-negative"); final long demandId = nextElementId.longValue(); nextElementId.increment(); MulticastDemand demand = new MulticastDemand (this , demandId , layer.multicastDemands.size () , layer , ingressNode , egressNodes , offeredTraffic , new AttributeMap (attributes)); cache_id2MulticastDemandMap.put (demandId , demand); layer.multicastDemands.add (demand); for (Node n : egressNodes) n.cache_nodeIncomingMulticastDemands.add (demand); ingressNode.cache_nodeOutgoingMulticastDemands.add (demand); if (ErrorHandling.isDebugEnabled()) this.checkCachesConsistency(); return demand; } /** * <p>Adds a new traffic multicast tree.</p> * * <p><b>Important</b>: Routing type must be {@link com.net2plan.utils.Constants.RoutingType#SOURCE_ROUTING SOURCE_ROUTING}.</p> * * @param demand Multi cast demand to be associated with the tree * @param carriedTraffic Carried traffic. It must be greater or equal than zero * @param occupiedLinkCapacity Occupied link capacity. If -1, it will be assumed to be equal to the carried traffic. Otherwise, it must be greater or equal than zero * @param linkSet {@code Set} of links of the multicast tree * @param attributes Map for user-defined attributes ({@code null} means 'no attribute'). Each key represents the attribute name, whereas value represents the attribute value * @return The newly reated multicast tree * @see com.net2plan.interfaces.networkDesign.MulticastTree * @see com.net2plan.interfaces.networkDesign.MulticastDemand * @see com.net2plan.interfaces.networkDesign.Link */ public MulticastTree addMulticastTree(MulticastDemand demand , double carriedTraffic, double occupiedLinkCapacity, Set<Link> linkSet , Map<String, String> attributes) { carriedTraffic = NetPlan.adjustToTolerance(carriedTraffic); occupiedLinkCapacity = NetPlan.adjustToTolerance(occupiedLinkCapacity); checkIsModifiable(); checkInThisNetPlan(demand); checkMulticastTreeValidityForDemand(linkSet , demand); if (carriedTraffic < 0) throw new Net2PlanException ("Carried traffic must be non-negative"); if (occupiedLinkCapacity < 0) occupiedLinkCapacity = carriedTraffic; NetworkLayer layer = demand.layer; final long treeId = nextElementId.longValue(); nextElementId.increment(); MulticastTree tree = new MulticastTree(this, treeId , layer.multicastTrees.size() , demand, linkSet , new AttributeMap(attributes)); cache_id2MulticastTreeMap.put(treeId, tree); layer.multicastTrees.add(tree); boolean treeIsUp = true; for (Node node : tree.cache_traversedNodes) { node.cache_nodeAssociatedulticastTrees.add (tree); if (!node.isUp) treeIsUp = false; } for (Link link : linkSet) { if (!link.isUp) treeIsUp = false; link.cache_traversingTrees.add (tree); } if (!treeIsUp) layer.cache_multicastTreesDown.add (tree); demand.cache_multicastTrees.add (tree); tree.setCarriedTraffic(carriedTraffic , occupiedLinkCapacity); if (ErrorHandling.isDebugEnabled()) this.checkCachesConsistency(); return tree; } /** * <p>Adds a new node to the network. Nodes are associated to all layers.</p> * @param xCoord Node position in x-axis * @param yCoord Node position in y-axis * @param name Node name ({@code null} will be converted to "Node " + node identifier) * @param attributes Map for user-defined attributes ({@code null} means 'no attribute'). Each key represents the attribute name, whereas value represents the attribute value * @return The newly created node object * @see com.net2plan.interfaces.networkDesign.Node */ public Node addNode(double xCoord, double yCoord, String name, Map<String, String> attributes) { checkIsModifiable(); final long nodeId = nextElementId.longValue(); nextElementId.increment(); Node node = new Node(this, nodeId, nodes.size(), xCoord, yCoord, name, new AttributeMap(attributes)); nodes.add (node); cache_id2NodeMap.put (nodeId , node); for (NetworkLayer layer : layers) { final int E = layer.links.size(); if (layer.routingType == RoutingType.HOP_BY_HOP_ROUTING) { layer.forwardingRules_Aout_ne = DoubleFactory2D.sparse.appendRow(layer.forwardingRules_Aout_ne , DoubleFactory1D.sparse.make (E)); layer.forwardingRules_Ain_ne = DoubleFactory2D.sparse.appendRow(layer.forwardingRules_Ain_ne , DoubleFactory1D.sparse.make (E)); } } if (ErrorHandling.isDebugEnabled()) this.checkCachesConsistency(); return node; } /** * <p>Adds a new protection segment. All the links must belong to the same layer</p> * * <p><b>Important</b>: Routing type must be {@link com.net2plan.utils.Constants.RoutingType#SOURCE_ROUTING SOURCE_ROUTING}.</p> * @param sequenceOfLinks Sequence of links * @param reservedCapacity Reserved capacity in each link from {@code sequenceOfLinks}. It must be greater or equal than zero * @param attributes Map for user-defined attributes ({@code null} means 'no attribute'). Each key represents the attribute name, whereas value represents the attribute value * @return The newly created protetion segment object * @see com.net2plan.interfaces.networkDesign.ProtectionSegment * @see com.net2plan.interfaces.networkDesign.Link */ public ProtectionSegment addProtectionSegment(List<Link> sequenceOfLinks, double reservedCapacity, Map<String, String> attributes) { reservedCapacity = NetPlan.adjustToTolerance(reservedCapacity); checkIsModifiable(); NetworkLayer layer = checkContiguousPath (sequenceOfLinks , null , null , null); checkInThisNetPlanAndLayer(sequenceOfLinks , layer); layer.checkRoutingType(RoutingType.SOURCE_ROUTING); if (reservedCapacity < 0) throw new Net2PlanException ("Reserved capacity must be non-negative"); if (sequenceOfLinks.size () != new HashSet<Link> (sequenceOfLinks).size()) throw new Net2PlanException ("Protection segments cannot traverse the same link more than once"); final long segmentId = nextElementId.longValue(); nextElementId.increment(); ProtectionSegment segment = new ProtectionSegment (this, segmentId , layer.protectionSegments.size (), sequenceOfLinks , reservedCapacity , new AttributeMap (attributes)); cache_id2ProtectionSegmentMap.put (segmentId , segment); layer.protectionSegments.add (segment); boolean segmentIsUp = true; for (Link link : sequenceOfLinks) { link.cache_traversingSegments.add (segment); if (!link.isUp) segmentIsUp = false; } for (Node node : segment.seqNodes) {node.cache_nodeAssociatedSegments.add (segment) ; if (!node.isUp) segmentIsUp = false; } if (!segmentIsUp) layer.cache_segmentsDown.add (segment); if (ErrorHandling.isDebugEnabled()) this.checkCachesConsistency(); return segment; } /** * <p>Adds a new traffic route </p> * * <p><b>Important</b>: Routing type must be {@link com.net2plan.utils.Constants.RoutingType#SOURCE_ROUTING SOURCE_ROUTING}.</p> * @param demand Demand associated to the route * @param carriedTraffic Carried traffic. It must be greater or equal than zero * @param occupiedLinkCapacity Occupied link capacity, it must be greater or equal than zero. * @param sequenceOfLinks Sequence of links traversed by the route * @param attributes Map for user-defined attributes ({@code null} means 'no attribute'). Each key represents the attribute name, whereas value represents the attribute value * @return The newly created route object * @see com.net2plan.interfaces.networkDesign.Route * @see com.net2plan.interfaces.networkDesign.Demand * @see com.net2plan.interfaces.networkDesign.Link */ public Route addRoute(Demand demand , double carriedTraffic, double occupiedLinkCapacity, List<Link> sequenceOfLinks, Map<String, String> attributes) { carriedTraffic = NetPlan.adjustToTolerance(carriedTraffic); occupiedLinkCapacity = NetPlan.adjustToTolerance(occupiedLinkCapacity); checkIsModifiable(); checkInThisNetPlan(demand); checkPathValidityForDemand(sequenceOfLinks, demand); demand.layer.checkRoutingType(RoutingType.SOURCE_ROUTING); if (carriedTraffic < 0) throw new Net2PlanException ("Carried traffic must be non-negative"); if (occupiedLinkCapacity < 0) occupiedLinkCapacity = carriedTraffic; NetworkLayer layer = demand.layer; final long routeId = nextElementId.longValue(); nextElementId.increment(); Route route = new Route(this, routeId, layer.routes.size(), demand , sequenceOfLinks , new AttributeMap(attributes)); layer.routes.add(route); cache_id2RouteMap.put (routeId,route); boolean isUpThisRoute = true; for (Node node : route.seqNodesRealPath) { node.cache_nodeAssociatedRoutes.add (route); if (!node.isUp) isUpThisRoute = false; } for (Link link : route.seqLinksRealPath) { Integer numPassingTimes = link.cache_traversingRoutes.get (route); if (numPassingTimes == null) numPassingTimes = 1; else numPassingTimes ++; link.cache_traversingRoutes.put (route , numPassingTimes); if (!link.isUp) isUpThisRoute = false; } demand.cache_routes.add (route); if (!isUpThisRoute) layer.cache_routesDown.add (route); route.setCarriedTraffic(carriedTraffic , occupiedLinkCapacity); if (ErrorHandling.isDebugEnabled()) this.checkCachesConsistency(); return route; } /** * <p>Adds traffic routes specified by those paths that satisfy the candidate path list options described below. Existing routes will not be removed.</p> * * <p><b>Important</b>: Routing type must be {@link com.net2plan.utils.Constants.RoutingType#SOURCE_ROUTING SOURCE_ROUTING}.</p> * * <p>The candidate path list elaborated contains a set of paths * computed for each unicast demand in the network, based on the k-shortest path idea. In general, for every demand k * paths are computed with the shortest weight according to some weights * assigned to the links.</p> * <p>The computation of paths can be configured via {@code "parameter=value"} options. There are several options to * configure, which can be combined:</p> * * <ul> * <li>{@code K}: Number of desired loopless shortest paths (default: 3). If <i>K'</i>&lt;{@code K} different paths are found between the demand node pairs, then only <i>K'</i> paths are * included in the candidate path list</li> * <li>{@code maxLengthInKm}: Maximum path length measured in kilometers allowed (default: Double.MAX_VALUE)</li> * <li>{@code maxNumHops}: Maximum number of hops allowed (default: Integer.MAX_VALUE)</li> * <li>{@code maxPropDelayInMs}: Maximum propagation delay in miliseconds allowed in a path (default: Double.MAX_VALUE)</li> * <li>{@code maxRouteCost}: Maximum path weight allowed (default: Double.MAX_VALUE)</li> * <li>{@code maxRouteCostFactorRespectToShortestPath}: Maximum path weight factor with respect to the shortest path weight (default: Double.MAX_VALUE)</li> * <li>{@code maxRouteCostRespectToShortestPath}: Maximum path weight with respect to the shortest path weight (default: Double.MAX_VALUE). While the previous one is a multiplicative factor, this one is an additive factor</li> * </ul> * * @param costs Link weight vector for the shortest path algorithm * @param paramValuePairs Parameters to be passed to the class to tune its operation. An even number of {@code String} is to be passed. For each {@code String} pair, first {@code String} * must be the name of the parameter, second a {@code String} with its value. If no name-value pairs are set, default values are used * @return Map with all the computed paths (values) per demands (keys) */ public Map<Demand,List<List<Link>>> computeUnicastCandidatePathList (double [] costs , String... paramValuePairs) { return computeUnicastCandidatePathList(defaultLayer, costs, paramValuePairs); } /** * <p>Computes the list of disjoint path pairs for each demand.</p> * * @param cpl Candidate path list per demand * @param costs Link cost vector * @param disjointType Type of disjointness: 0 for SRG-disjoint, 1 for link and node disjoint, other value means link disjoint * @return List of disjoint path pairs for each demand * @since 0.4.0 */ public static Map<Demand,List<Pair<List<Link>,List<Link>>>> computeUnicastCandidate11PathList (Map<Demand,List<List<Link>>> cpl , DoubleMatrix1D costs , int disjointType) { final boolean srgDisjoint = disjointType == 0; final boolean linkAndNodeDisjoint = disjointType == 1; final boolean linkDisjoint = !srgDisjoint && !linkAndNodeDisjoint; Map<Demand,List<Pair<List<Link>,List<Link>>>> result = new HashMap<Demand,List<Pair<List<Link>,List<Link>>>> (); for (Demand d : cpl.keySet()) { for (List<Link> path : cpl.get(d)) d.netPlan.checkInThisNetPlanAndLayer(path , d.layer); List<Pair<List<Link>,List<Link>>> pairs11ThisDemand = new ArrayList<Pair<List<Link>,List<Link>>> (); final List<List<Link>> paths = new ArrayList<List<Link>> (cpl.get(d)); final int P_d = paths.size (); for (int firstPathIndex = 0; firstPathIndex < P_d-1 ; firstPathIndex ++) { final List<Link> firstPath = paths.get(firstPathIndex); final Set<Link> firstPathLinks = new HashSet<Link> (firstPath); Set<Node> firstPathNodesButLastAndFirst = null; Set<SharedRiskGroup> firstPathSRGs = null; if (linkAndNodeDisjoint) { List<Node> firstPathSeqNodes = GraphUtils.convertSequenceOfLinksToSequenceOfNodes(firstPath); firstPathNodesButLastAndFirst = new HashSet<Node> (firstPathSeqNodes); firstPathNodesButLastAndFirst.remove(d.ingressNode); firstPathNodesButLastAndFirst.remove(d.egressNode); } else if (srgDisjoint) { firstPathSRGs = SRGUtils.getAffectingSRGs(firstPathLinks); } for (int secondPathIndex = firstPathIndex + 1; secondPathIndex < P_d ; secondPathIndex ++) { List<Link> secondPath = paths.get(secondPathIndex); boolean disjoint = true; boolean firstLink = true; if (linkDisjoint) { for (Link e : secondPath) if (firstPathLinks.contains(e)) { disjoint = false; break; } } else if (linkAndNodeDisjoint) { for (Link e : secondPath) { if (firstPathLinks.contains(e)) { disjoint = false; break; } if (firstLink) firstLink = false; else { if (firstPathNodesButLastAndFirst.contains(e.originNode)) disjoint = false; break; } } } else if (srgDisjoint) { for (SharedRiskGroup srg : SRGUtils.getAffectingSRGs(secondPath)) if (firstPathSRGs.contains(srg)) { disjoint = false; break; } } if (disjoint) { checkDisjointness (firstPath , secondPath , disjointType); pairs11ThisDemand.add (Pair.of(firstPath, secondPath)); } } } result.put (d , pairs11ThisDemand); } return result; } private static void checkDisjointness (List<Link> p1 , List<Link> p2 , int disjointnessType) { if ((p1 == null) || (p2 == null)) throw new RuntimeException ("Bad"); if (disjointnessType == 0) // SRG disjoint { Set<SharedRiskGroup> srg1 = new HashSet<SharedRiskGroup> (); for (Link e : p1) srg1.addAll (e.getSRGs()); for (Link e : p2) for (SharedRiskGroup srg : e.getSRGs()) if (srg1.contains(srg)) throw new RuntimeException ("Bad"); } else if (disjointnessType == 1) // link and node { Set<NetworkElement> resourcesP1 = new HashSet<NetworkElement> (); boolean firstLink = true; for (Link e : p1) { resourcesP1.add (e); if (firstLink) firstLink = false; else resourcesP1.add (e.getOriginNode()); } for (Link e : p2) if (resourcesP1.contains(e)) throw new RuntimeException ("Bad"); } else if (disjointnessType == 2) // link { Set<Link> linksP1 = new HashSet<Link> (p1); for (Link e : p2) if (linksP1.contains (e)) throw new RuntimeException ("Bad: p1: " + p1 + ", p2: " + p2); } else throw new RuntimeException ("Bad"); } /** * <p>Adds traffic routes specified by those paths that satisfy the candidate path list options described below. Existing routes will not be removed.</p> * * <p><b>Important</b>: Routing type must be {@link com.net2plan.utils.Constants.RoutingType#SOURCE_ROUTING SOURCE_ROUTING}.</p> * * <p>The candidate path list elaborated contains a set of paths * computed for each unicast demand in the network, based on the k-shortest path idea. In general, for every demand k * paths are computed with the shortest weight according to some weights * assigned to the links.</p> * <p>The computation of paths can be configured via {@code "parameter=value"} options. There are several options to * configure, which can be combined:</p> * * <ul> * <li>{@code K}: Number of desired loopless shortest paths (default: 3). If <i>K'&lt;</i>{@code K} different paths are found between the demand node pairs, then only <i>K'</i> paths are * included in the candidate path list</li> * <li>{@code maxLengthInKm}: Maximum path length measured in kilometers allowed (default: Double.MAX_VALUE)</li> * <li>{@code maxNumHops}: Maximum number of hops allowed (default: Integer.MAX_VALUE)</li> * <li>{@code maxPropDelayInMs}: Maximum propagation delay in miliseconds allowed in a path (default: Double.MAX_VALUE)</li> * <li>{@code maxRouteCost}: Maximum path weight allowed (default: Double.MAX_VALUE)</li> * <li>{@code maxRouteCostFactorRespectToShortestPath}: Maximum path weight factor with respect to the shortest path weight (default: Double.MAX_VALUE)</li> * <li>{@code maxRouteCostRespectToShortestPath}: Maximum path weight with respect to the shortest path weight (default: Double.MAX_VALUE). While the previous one is a multiplicative factor, this one is an additive factor</li> * </ul> * * @param layer Network layer * @param costs Link weight vector for the shortest path algorithm. If null, all the links have cost one * @param paramValuePairs Parameters to be passed to the class to tune its operation. An even number of {@code String} is to be passed. For each {@code String} pair, first {@code String} * must be the name of the parameter, second a {@code String} with its value. If no name-value pairs are set, default values are used * @return Map with all the computed paths (values) per demands (keys) */ public Map<Demand,List<List<Link>>> computeUnicastCandidatePathList (NetworkLayer layer , double [] costs , String... paramValuePairs) { checkIsModifiable(); checkInThisNetPlan(layer); layer.checkRoutingType(RoutingType.SOURCE_ROUTING); if (costs != null) if (costs.length != layer.links.size()) throw new Net2PlanException ("The array of costs must have the same length as the number of links in the layer"); int K = 3; double maxLengthInKm = Double.MAX_VALUE; int maxNumHops = Integer.MAX_VALUE; double maxPropDelayInMs = Double.MAX_VALUE; double maxRouteCost = Double.MAX_VALUE; double maxRouteCostFactorRespectToShortestPath = Double.MAX_VALUE; double maxRouteCostRespectToShortestPath = Double.MAX_VALUE; int numParameters = (int) (paramValuePairs.length / 2); if (numParameters * 2 != paramValuePairs.length) throw new Net2PlanException("A parameter has not assigned its value"); for (int contParam = 0; contParam < numParameters; contParam++) { String parameter = paramValuePairs[contParam * 2]; String value = paramValuePairs[contParam * 2 + 1]; if (parameter.equalsIgnoreCase("K")) { K = Integer.parseInt(value); if (K <= 0) throw new Net2PlanException("'K' parameter must be greater than zero"); } else if (parameter.equalsIgnoreCase("maxLengthInKm")) maxLengthInKm = Double.parseDouble(value) <= 0? Double.MAX_VALUE : Double.parseDouble(value); else if (parameter.equalsIgnoreCase("maxPropDelayInMs")) maxPropDelayInMs = Double.parseDouble(value) <= 0? Double.MAX_VALUE : Double.parseDouble(value); else if (parameter.equalsIgnoreCase("maxNumHops")) maxNumHops = Integer.parseInt(value) <= 0? Integer.MAX_VALUE : Integer.parseInt(value); else if (parameter.equalsIgnoreCase("maxRouteCost")) maxRouteCost = Double.parseDouble(value) <= 0? Double.MAX_VALUE : Double.parseDouble(value); else if (parameter.equalsIgnoreCase("maxRouteCostFactorRespectToShortestPath")) maxRouteCostFactorRespectToShortestPath = Double.parseDouble(value) <= 0? Double.MAX_VALUE : Double.parseDouble(value); else if (parameter.equalsIgnoreCase("maxRouteCostRespectToShortestPath")) maxRouteCostRespectToShortestPath = Double.parseDouble(value) <= 0? Double.MAX_VALUE : Double.parseDouble(value); else throw new RuntimeException("Unknown parameter " + parameter); } Map<Demand,List<List<Link>>> cpl = new HashMap<Demand,List<List<Link>>> (); Map<Link,Double> linkCostMap = new HashMap<Link,Double> (); for (Link e : layer.links) linkCostMap.put (e , costs == null? 1.0 : costs [e.index]); for(Demand d : layer.demands) cpl.put (d , GraphUtils.getKLooplessShortestPaths(nodes , layer.links , d.ingressNode , d.egressNode , linkCostMap , K , maxLengthInKm, maxNumHops, maxPropDelayInMs , maxRouteCost , maxRouteCostFactorRespectToShortestPath , maxRouteCostRespectToShortestPath )); return cpl; } /** * <p>Adds multiples routes from a Candidate Path List.</p> * @param cpl {@code Map} where the keys are demands and the values a list of sequence of links (each sequence is a route) */ public void addRoutesFromCandidatePathList (Map<Demand,List<List<Link>>> cpl) { checkIsModifiable(); List<Route> routes = new LinkedList<Route> (); try { for(Entry<Demand,List<List<Link>>> entry : cpl.entrySet()) for (List<Link> seqLinks : entry.getValue()) routes.add (addRoute(entry.getKey() , 0 , 0 , seqLinks , null)); } catch (Exception e) { for (Route r : routes) r.remove (); throw e; } if (ErrorHandling.isDebugEnabled()) this.checkCachesConsistency(); } /** * <p>Same as {@code addRoutesFromCandidatePathList(computeUnicastCandidatePathList(layer , costs , paramValuePairs);} * @param layer Network layer * @param costs Link weight vector for the shortest path algorithm * @param paramValuePairs Parameters to be passed to the class to tune its operation. An even number of {@code String} is to be passed. For each {@code String} pair, first {@code String} * must be the name of the parameter, second a {@code String} with its value. If no name-value pairs are set, default values are used */ public void addRoutesFromCandidatePathList (NetworkLayer layer , double [] costs , String... paramValuePairs) { addRoutesFromCandidatePathList(computeUnicastCandidatePathList(layer , costs , paramValuePairs)); } /** * <p>Same as {@code addRoutesFromCandidatePathList(computeUnicastCandidatePathList(costs , paramValuePairs);} * @param costs Link weight vector for the shortest path algorithm * @param paramValuePairs Parameters to be passed to the class to tune its operation. An even number of {@code String} is to be passed. For each {@code String} pair, first {@code String} * must be the name of the parameter, second a {@code String} with its value. If no name-value pairs are set, default values are used */ public void addRoutesFromCandidatePathList (double [] costs , String... paramValuePairs) { addRoutesFromCandidatePathList(computeUnicastCandidatePathList(costs , paramValuePairs)); } public void addRoutesAndProtectionSegmentFromCandidate11PathList (Map<Demand,List<Pair<List<Link>,List<Link>>>> cpl11) { checkIsModifiable(); List<Route> routes = new LinkedList<Route> (); List<ProtectionSegment> segments = new LinkedList<ProtectionSegment> (); try { for(Entry<Demand,List<Pair<List<Link>,List<Link>>>> entry : cpl11.entrySet()) for (Pair<List<Link>,List<Link>> pathPair : entry.getValue()) { final Route newRoute = addRoute(entry.getKey() , 0 , 0 , pathPair.getFirst() , null); routes.add (newRoute); final ProtectionSegment newSegment = addProtectionSegment(pathPair.getSecond(), 0, null); segments.add (newSegment); newRoute.addProtectionSegment(newSegment); } } catch (Exception e) { for (Route r : routes) r.remove (); for (ProtectionSegment s : segments) s.remove (); throw e; } if (ErrorHandling.isDebugEnabled()) this.checkCachesConsistency(); } // public void addMulticastTreesFromCandidateTreeList (double [] costs , String solverName , String solverLibraryName , double maxSolverTimeInSecondsPerTree , String... paramValuePairs) // { // addMulticastTreesFromCandidateTreeList (defaultLayer , costs , solverName , solverLibraryName , maxSolverTimeInSecondsPerTree , paramValuePairs); // } // /** * The same as {@code computeMulticastCandidatePathList} for the default layer * @param costs see {@code computeMulticastCandidatePathList} * @param solverName see {@code computeMulticastCandidatePathList} * @param solverLibraryName see {@code computeMulticastCandidatePathList} * @param maxSolverTimeInSecondsPerTree see {@code computeMulticastCandidatePathList} * @param candidateTreeListParamValuePairs see {@code computeMulticastCandidatePathList} * @return see {@code computeMulticastCandidatePathList} */ public Map<MulticastDemand,List<Set<Link>>> computeMulticastCandidatePathList (DoubleMatrix1D costs , String solverName , String solverLibraryName , double maxSolverTimeInSecondsPerTree , String... candidateTreeListParamValuePairs) { return computeMulticastCandidatePathList (defaultLayer , costs , solverName , solverLibraryName , maxSolverTimeInSecondsPerTree , candidateTreeListParamValuePairs); } /** * <p>Adds multicast trees specified by those trees that satisfy the options described below. Existing multicast trees will not be removed.</p> * * <p>The candidate tree list elaborated contains a set of multicast trees (each one is a set of links) computed for each multicast demand * in the network. To compute it, a ILP formulation is solved for each new multicast tree. In general, for every multicast demand k * trees are computed ranked according to its cost (weight) according to some link weights.</p> * <p>The computation of paths can be configured via {@code "parameter=value"} options. There are several options to * configure, which can be combined:</p> * * <ul> * <li>{@code K}: Number of desired multicast trees per demand (default: 3). If <i>K'&lt;</i>{@code K} different trees are found for the multicast demand, then only <i>K'</i> are * included in the candidate list</li> * <li>{@code maxCopyCapability}: the maximum number of copies of an input traffic a node can make. Then, a node can have at most this number of ouput links carrying traffic of a multicast tree (default: Double.MAX_VALUE)</li> * <li>{@code maxE2ELengthInKm}: Maximum path length measured in kilometers allowed for any tree, from the origin node, to any destination node (default: Double.MAX_VALUE)</li> * <li>{@code maxE2ENumHops}: Maximum number of hops allowed for any tree, from the origin node, to any destination node (default: Integer.MAX_VALUE)</li> * <li>{@code maxE2EPropDelayInMs}: Maximum propagation delay in miliseconds allowed in a path, for any tree, from the origin node, to any destination node (default: Double.MAX_VALUE)</li> * <li>{@code maxTreeCost}: Maximum tree weight allowed, summing the weights of the links (default: Double.MAX_VALUE)</li> * <li>{@code maxTreeCostFactorRespectToMinimumCostTree}: Trees with higher weight (cost) than the cost of the minimum cost tree, multiplied by this factor, are not returned (default: Double.MAX_VALUE)</li> * <li>{@code maxTreeCostRespectToMinimumCostTree}: Trees with higher weight (cost) than the cost of the minimum cost tree, plus this factor, are not returned (default: Double.MAX_VALUE). While the previous one is a multiplicative factor, this one is an additive factor</li> * </ul> * * @param layer the layer for which the candidate multicast tree list is computed * @param linkCosts Link weight vector for the shortest path algorithm. If {@code null}, a vector of ones is assumed * @param solverName the name of the solver to call for the internal formulation of the algorithm * @param solverLibraryName the solver library name * @param maxSolverTimeInSecondsPerTree the maximum time the solver is allowed for each of the internal formulations (one for each new tree). * The best solution found so far is returned. If non-positive, no time limit is set * @param candidateTreeListParamValuePairs Parameters to be passed to the class to tune its operation. An even number of {@code String} is to be passed. For each {@code String} pair, first {@code String} * must be the name of the parameter, second a {@code String} with its value. If no name-value pairs are set, default values are used * @return Map with a list of all the computed trees (a tree is a set of links) per multicast demands */ public Map<MulticastDemand,List<Set<Link>>> computeMulticastCandidatePathList (NetworkLayer layer, DoubleMatrix1D linkCosts , String solverName , String solverLibraryName , double maxSolverTimeInSecondsPerTree , String... candidateTreeListParamValuePairs) { checkInThisNetPlan(layer); if (linkCosts == null) linkCosts = DoubleFactory1D.dense.make (layer.links.size () , 1); if (linkCosts.size () != layer.links.size()) throw new Net2PlanException ("The array of costs must have the same length as the number of links in the layer"); Map<MulticastDemand,List<Set<Link>>> cpl = new HashMap<MulticastDemand,List<Set<Link>>> (); int K = 3; int maxCopyCapability = Integer.MAX_VALUE; double maxE2ELengthInKm = Double.MAX_VALUE; int maxE2ENumHops = Integer.MAX_VALUE; double maxE2EPropDelayInMs = Double.MAX_VALUE; double maxTreeCost = Double.MAX_VALUE; double maxTreeCostFactorRespectToMinimumCostTree = Double.MAX_VALUE; double maxTreeCostRespectToMinimumCostTree = Double.MAX_VALUE; int numParameters = (int) (candidateTreeListParamValuePairs.length / 2); if (numParameters * 2 != candidateTreeListParamValuePairs.length) throw new Net2PlanException("A parameter has not assigned its value"); for (int contParam = 0; contParam < numParameters; contParam++) { String parameter = candidateTreeListParamValuePairs[contParam * 2]; String value = candidateTreeListParamValuePairs[contParam * 2 + 1]; if (parameter.equalsIgnoreCase("K")) { K = Integer.parseInt(value); if (K <= 0) throw new Net2PlanException("'K' parameter must be greater than zero"); } else if (parameter.equalsIgnoreCase("maxCopyCapability")) maxCopyCapability = Integer.parseInt (value) <= 0? Integer.MAX_VALUE : Integer.parseInt (value); else if (parameter.equalsIgnoreCase("maxE2ELengthInKm")) maxE2ELengthInKm = Double.parseDouble(value) <= 0? Double.MAX_VALUE : Double.parseDouble(value); else if (parameter.equalsIgnoreCase("maxE2EPropDelayInMs")) maxE2EPropDelayInMs = Double.parseDouble(value) <= 0? Double.MAX_VALUE : Double.parseDouble(value); else if (parameter.equalsIgnoreCase("maxE2ENumHops")) maxE2ENumHops = Integer.parseInt (value) <= 0? Integer.MAX_VALUE : Integer.parseInt (value); else if (parameter.equalsIgnoreCase("maxTreeCost")) maxTreeCost = Double.parseDouble(value) <= 0? Double.MAX_VALUE : Double.parseDouble(value); else if (parameter.equalsIgnoreCase("maxTreeCostFactorRespectToMinimumCostTree")) maxTreeCostFactorRespectToMinimumCostTree = Double.parseDouble(value) <= 0? Double.MAX_VALUE : Double.parseDouble(value); else if (parameter.equalsIgnoreCase("maxTreeCostRespectToMinimumCostTree")) maxTreeCostRespectToMinimumCostTree = Double.parseDouble(value) <= 0? Double.MAX_VALUE : Double.parseDouble(value); else throw new RuntimeException("Unknown parameter " + parameter); } final DoubleMatrix2D Aout_ne = (layer.routingType == RoutingType.SOURCE_ROUTING)? getMatrixNodeLinkOutgoingIncidence(layer) : layer.forwardingRules_Aout_ne; final DoubleMatrix2D Ain_ne = (layer.routingType == RoutingType.SOURCE_ROUTING)? getMatrixNodeLinkIncomingIncidence(layer) : layer.forwardingRules_Ain_ne; for (MulticastDemand d : layer.multicastDemands) { List<Set<Link>> trees = GraphUtils.getKMinimumCostMulticastTrees(layer.links , d.getIngressNode() , d.getEgressNodes() , Aout_ne , Ain_ne , linkCosts , solverName , solverLibraryName , maxSolverTimeInSecondsPerTree , K , maxCopyCapability , maxE2ELengthInKm , maxE2ENumHops, maxE2EPropDelayInMs , maxTreeCost , maxTreeCostFactorRespectToMinimumCostTree , maxTreeCostRespectToMinimumCostTree); cpl.put(d, trees); } return cpl; } /** * <p>Adds multiple multicast trees from a Candidate Tree list.</p> * @param cpl {@code Map} where the keys are multicast demands and the values lists of link sets * @see com.net2plan.interfaces.networkDesign.MulticastDemand * @see com.net2plan.interfaces.networkDesign.Link */ public void addMulticastTreesFromCandidateTreeList (Map<MulticastDemand,List<Set<Link>>> cpl) { checkIsModifiable(); List<MulticastTree> trees = new LinkedList<MulticastTree> (); try { for(Entry<MulticastDemand,List<Set<Link>>> entry : cpl.entrySet()) for (Set<Link> linkSet : entry.getValue()) trees.add(addMulticastTree(entry.getKey(), 0, 0, linkSet, null)); } catch (Exception e) { for (MulticastTree t : trees) t.remove (); throw e; } if (ErrorHandling.isDebugEnabled()) this.checkCachesConsistency(); } /** * <p>Adds a new SRG.</p> * @param mttfInHours Mean Time To Fail (in hours). Must be greater than zero * @param mttrInHours Mean Time To Repair (in hours). Must be greater than zero * @param attributes Map for user-defined attributes ({@code null} means 'no attribute'). Each key represents the attribute name, whereas value represents the attribute value * @return The newly created shared risk group object * @see com.net2plan.interfaces.networkDesign.SharedRiskGroup */ public SharedRiskGroup addSRG(double mttfInHours, double mttrInHours, Map<String, String> attributes) { checkIsModifiable(); if (mttfInHours <= 0) throw new Net2PlanException ("Mean Time To Fail must be a positive value"); if (mttrInHours <= 0) throw new Net2PlanException ("Mean Time To Repair must be a positive value"); final long srgId = nextElementId.longValue(); nextElementId.increment(); SharedRiskGroup srg = new SharedRiskGroup(this, srgId, srgs.size(), new HashSet<Node> (), new HashSet<Link> () , mttfInHours , mttrInHours , new AttributeMap(attributes)); srgs.add (srg); cache_id2srgMap.put (srgId , srg); if (ErrorHandling.isDebugEnabled()) this.checkCachesConsistency(); return srg; } /** * <p>Assigns the information from the input {@code NetPlan}.</p> * * <p><b>Important</b>: A shadow copy is made, so changes in the input object will be reflected in this one. For deep copies use {@link #copyFrom(com.net2plan.interfaces.networkDesign.NetPlan) copyFrom()}</p> * * @param netPlan Network plan to be copied * @since 0.3.0 */ public void assignFrom(NetPlan netPlan) { checkIsModifiable(); this.DEFAULT_ROUTING_TYPE = netPlan.DEFAULT_ROUTING_TYPE; this.isModifiable = netPlan.isModifiable; this.networkDescription = netPlan.networkDescription; this.networkName = netPlan.networkName; this.defaultLayer = netPlan.defaultLayer; this.nextElementId = netPlan.nextElementId; this.layers = netPlan.layers; this.nodes = netPlan.nodes; this.srgs = netPlan.srgs; this.cache_nodesDown = netPlan.cache_nodesDown; this.cache_id2LayerMap = netPlan.cache_id2LayerMap; this.cache_id2NodeMap = netPlan.cache_id2NodeMap; this.cache_id2LinkMap = netPlan.cache_id2LinkMap; this.cache_id2DemandMap = netPlan.cache_id2DemandMap; this.cache_id2MulticastDemandMap = netPlan.cache_id2MulticastDemandMap; this.cache_id2RouteMap = netPlan.cache_id2RouteMap; this.cache_id2MulticastTreeMap = netPlan.cache_id2MulticastTreeMap; this.cache_id2ProtectionSegmentMap = netPlan.cache_id2ProtectionSegmentMap; this.cache_id2srgMap = netPlan.cache_id2srgMap; this.interLayerCoupling = netPlan.interLayerCoupling; this.attributes.clear (); this.attributes.putAll(netPlan.attributes); for (Node node : netPlan.nodes) node.netPlan = this; for (SharedRiskGroup srg : netPlan.srgs) srg.netPlan = this; for (NetworkLayer layer : netPlan.layers) { layer.netPlan = this; for (Link e : layer.links) e.netPlan = this; for (Demand e : layer.demands) e.netPlan = this; for (MulticastDemand e : layer.multicastDemands) e.netPlan = this; for (Route e : layer.routes) e.netPlan = this; for (ProtectionSegment e : layer.protectionSegments) e.netPlan = this; for (MulticastTree e : layer.multicastTrees) e.netPlan = this; } if (ErrorHandling.isDebugEnabled()) this.checkCachesConsistency(); } /** * <p>Checks that the input sequence of links belong to the same layer and follow a contiguous path. Throws an exception if the path is not contiguous or the sequence of links * is empty. </p> * @param links Sequence of links * @param layer Network layer * @param originNode Origin node * @param destinationNode Destination node * @return The input layer */ public NetworkLayer checkContiguousPath (List<Link> links , NetworkLayer layer , Node originNode , Node destinationNode) { if (links.isEmpty()) throw new Net2PlanException ("Empty sequence of links"); final Link firstLink = links.iterator().next (); if (layer == null) layer = firstLink.layer; checkInThisNetPlan(layer); if (originNode != null) checkInThisNetPlan(originNode); if (destinationNode != null) checkInThisNetPlan(destinationNode); for (Link e : links) if (!e.layer.equals (layer)) throw new Net2PlanException ("The path contains links not attached to the appropriate NetPlan object or layer"); if ((originNode != null) && (!firstLink.originNode.equals (originNode))) throw new Net2PlanException ("The initial node of the sequence of links is not correct"); Node endNodePreviousLink = firstLink.originNode; for (Link link : links) { if (!endNodePreviousLink.equals (link.originNode)) throw new Net2PlanException ("This is not a contigous sequence of links"); endNodePreviousLink = link.destinationNode; } if ((destinationNode != null) && !(endNodePreviousLink.equals (destinationNode))) throw new Net2PlanException ("The end node of the sequence of links is not correct"); return layer; } /** * <p>Checks if a demand exists in this {@code NetPlan} object. Throws an exception if nonexistent.</p> * @param id Demand id */ void checkExistsDemand (long id) { if (cache_id2DemandMap.get(id) == null) throw new Net2PlanException ("Demand of id: " + id + " does not exist"); } /** * <p>Checks if a link exists in this {@code NetPlan} object. Throws an exception if nonexistent.</p> * @param id Link id */ void checkExistsLink (long id) { if (cache_id2LinkMap.get(id) == null) throw new Net2PlanException ("Link of id: " + id + " does not exist"); } /** * <p>Checks if a multicast demand exists in this {@code NetPlan} object. Throws an exception if nonexistent.</p> * @param id Multicast demand id */ void checkExistsMulticastDemand (long id) { if (cache_id2MulticastDemandMap.get(id) == null) throw new Net2PlanException ("Multicast demand of id: " + id + " does not exist"); } /** * <p>Checks if a multicast tree exists in this {@code NetPlan} object. Throws an exception if nonexistent.</p> * @param id Multicast tree id */ void checkExistsMulticastTree (long id) { if (cache_id2MulticastTreeMap.get(id) == null) throw new Net2PlanException ("Multicast tree of id: " + id + " does not exist"); } /** * <p>Checks if a network layer exists in this {@code NetPlan} object. Throws an exception if nonexistent.</p> * @param id Network layer id */ void checkExistsNetworkLayer (long id) { if (cache_id2LayerMap.get(id) == null) throw new Net2PlanException ("Network layer of id: " + id + " does not exist"); } /** * <p>Checks if a node exists in this {@code NetPlan} object. Throws an exception if nonexistent.</p> * @param id Node id */ void checkExistsNode (long id) { if (cache_id2NodeMap.get(id) == null) throw new Net2PlanException ("Node of id: " + id + " does not exist"); } /** * <p>Checks if a protection segment exists in this {@code NetPlan} object. Throws an exception if nonexistent.</p> * @param id Protection segment id */ void checkExistsProtectionSegment (long id) { if (cache_id2ProtectionSegmentMap.get(id) == null) throw new Net2PlanException ("ProtectionSegment of id: " + id + " does not exist"); } /** * <p>Checks if a route exists in this {@code NetPlan} object. Throws an exception if nonexistent.</p> * @param id Route id */ void checkExistsRoute (long id) { if (cache_id2RouteMap.get(id) == null) throw new Net2PlanException ("Route of id: " + id + " does not exist"); } /** * <p>Checks if a shared risk group exists in this {@code NetPlan} object. Throws an exception if nonexistent.</p> * @param id the SRG identifier */ void checkExistsSRG (long id) { if (cache_id2srgMap.get(id) == null) throw new Net2PlanException ("Shared risk group of id: " + id + " does not exist"); } /** * <p>Checks if all the elements are attached to this {@code NetPlan} object. * .</p> * @param elements Collection of network elements * @see com.net2plan.interfaces.networkDesign.NetworkElement */ void checkInThisNetPlan(Collection<? extends NetworkElement> elements) { for (NetworkElement e : elements) checkInThisNetPlan(e); } /** * <p>Checks if an element is attached to this {@code NetPlan} object. It is checked also if the element belongs to the input layer.</p> * @param e Network element * @param layer Network layer (optional) */ void checkInThisNetPlanAndLayer(Collection<? extends NetworkElement> elements, NetworkLayer ... optionalLayer) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayer); for (NetworkElement e : elements) checkInThisNetPlanAndLayer(e, layer); } /** * <p>Checks if a network element exists in this {@code NetPlan} object. Throws an exception if nonexistent.</p> * @param e Network element * */ void checkInThisNetPlan(NetworkElement e) { if (e == null) throw new Net2PlanException ("Network element is null"); if (e.netPlan != this) throw new Net2PlanException ("Element " + e + " is not attached to this NetPlan object."); if (e instanceof Node) { if (e != nodes.get(e.index)) throw new Net2PlanException ("Element " + e + " is not the same object as the one in netPlan object."); } else if (e instanceof SharedRiskGroup) { if (e != srgs.get(e.index)) throw new Net2PlanException ("Element " + e + " is not the same object as the one in netPlan object."); } else if (e instanceof NetworkLayer) { if (e != layers.get(e.index)) throw new Net2PlanException ("Element " + e + " is not the same object as the one in netPlan object."); } } /** * <p>Checks if an element is attached to this {@code NetPlan} object. It is checked also if the element belongs to the input layer.</p> * @param e Network element * @param layer Network layer (optional) */ void checkInThisNetPlanAndLayer(NetworkElement e, NetworkLayer layer) { if (e == null) throw new Net2PlanException ("Network element is null"); if (e.netPlan != this) throw new Net2PlanException ("Element " + e + " is not attached to this NetPlan object."); if (e instanceof Node) { if (e != nodes.get(e.index)) throw new Net2PlanException ("Element " + e + " is not the same object as the one in netPlan object."); } else if (e instanceof SharedRiskGroup) { if (e != srgs.get(e.index)) throw new Net2PlanException ("Element " + e + " is not the same object as the one in netPlan object."); } else if (e instanceof NetworkLayer) { if (e != layers.get(e.index)) throw new Net2PlanException ("Element " + e + " is not the same object as the one in netPlan object."); } if (layer != null) { layer.checkAttachedToNetPlanObject(this); if (e instanceof Demand) { if (e != layer.demands.get(e.index)) throw new Net2PlanException ("Element " + e + " is not the same object as the one in netPlan object."); } else if (e instanceof ProtectionSegment) { if (e != layer.protectionSegments.get(e.index)) throw new Net2PlanException ("Element " + e + " is not the same object as the one in netPlan object."); } else if (e instanceof Link) { if (e != layer.links.get(e.index)) throw new Net2PlanException ("Element " + e + " is not the same object as the one in netPlan object."); } else if (e instanceof MulticastDemand) { if (e != layer.multicastDemands.get(e.index)) throw new Net2PlanException ("Element " + e + " is not the same object as the one in netPlan object."); } else if (e instanceof MulticastTree) { if (e != layer.multicastTrees.get(e.index)) throw new Net2PlanException ("Element " + e + " is not the same object as the one in netPlan object."); } else if (e instanceof Route) { if (e != layer.routes.get(e.index)) throw new Net2PlanException ("Element " + e + " is not the same object as the one in netPlan object."); } } } /** * <p>Checks if the {@code NetPlan} object is modifiable. When negative, an exception will be thrown.</p> * * @since 0.4.0 */ void checkIsModifiable() { if (!isModifiable) throw new UnsupportedOperationException(UNMODIFIABLE_EXCEPTION_STRING); } /** * <p>Checks if a set of links is valid for a given multicast demand. If it is not, an exception will be thrown. If it is valid, a map is returned with the * unique sequence of links in the tree, from the ingress node to each egress node of the multicast demand.</p> * * @param linkSet Sequence of links * @param demand Multicast demand * @return Map where the keys are nodes and the values are sequences of links (see description) * @see com.net2plan.interfaces.networkDesign.Node * @see com.net2plan.interfaces.networkDesign.Link * @see com.net2plan.interfaces.networkDesign.MulticastDemand */ Pair<Map<Node,List<Link>> , Set<Node>> checkMulticastTreeValidityForDemand(Set<Link> linkSet, MulticastDemand demand) { if (linkSet.isEmpty()) throw new Net2PlanException ("The multicast tree is empty"); checkInThisNetPlan(demand); final NetworkLayer layer = demand.layer; checkInThisNetPlanAndLayer(linkSet , demand.layer); Map<Node,List<Link>> pathToEgressNode = new HashMap<Node,List<Link>> (); Map<Link,Double> linkCost = new HashMap<Link,Double> (); for (Link link : layer.links) linkCost.put (link , (linkSet.contains (link))? 1 : Double.MAX_VALUE); Set<Link> actuallyTraversedLinks = new HashSet<Link> (); for (Node egressNode : demand.egressNodes) { final List<Link> seqLinks = GraphUtils.getShortestPath(nodes , layer.links , demand.ingressNode , egressNode , linkCost); if (seqLinks == null) throw new Net2PlanException ("No path to an end node"); pathToEgressNode.put(egressNode, seqLinks); actuallyTraversedLinks.addAll(seqLinks); } if (!linkSet.equals(actuallyTraversedLinks)) throw new Net2PlanException ("Some links in the link set provided are not traversed. The structure may not be a tree"); Set<Node> traversedNodes = new HashSet<Node> (); for (Link e : linkSet) { traversedNodes.add (e.originNode); traversedNodes.add (e.destinationNode); } if (traversedNodes.size() != linkSet.size() + 1) throw new Net2PlanException ("It is not a tree"); return Pair.of (pathToEgressNode,traversedNodes); } /** * <p>Checks if a sequence of links is valid, that is all the links follow a contiguous path from the demand ingress node to the egress node. If the sequence * is not valid, an exception is thrown.</p> * @param path Sequence of links * @param d Demand * @see com.net2plan.interfaces.networkDesign.Demand * @see com.net2plan.interfaces.networkDesign.Link */ void checkPathValidityForDemand(List<Link> path, Demand d) { checkInThisNetPlan(d); checkInThisNetPlanAndLayer(path , d.layer); checkContiguousPath (path , d.layer , d.ingressNode, d.egressNode); } /** * <p>Returns a deep copy of the current design.</p> * * @return Deep copy of the current design * @since 0.2.0 */ public NetPlan copy() { this.checkCachesConsistency(); NetPlan netPlan = new NetPlan(); netPlan.checkCachesConsistency(); netPlan.copyFrom(this); // System.out.println ("************** En el copy () *********************************************************"); this.checkCachesConsistency(); netPlan.checkCachesConsistency(); return netPlan; } /** * <p>Removes all information from the current {@code NetPlan} and copy the information from the input {@code NetPlan}.</p> * @param originNetPlan Network plan to be copied from */ public void copyFrom(NetPlan originNetPlan) { checkIsModifiable(); if (originNetPlan == this) return; if (originNetPlan == null) throw new Net2PlanException ("A NetPlan object must be provided"); this.attributes.clear(); this.attributes.putAll (originNetPlan.attributes); this.netPlan = this; this.layers = new ArrayList<NetworkLayer> (); this.nodes = new ArrayList<Node> (); this.srgs = new ArrayList<SharedRiskGroup> (); this.cache_nodesDown = new HashSet<Node> (); this.cache_id2NodeMap = new HashMap <Long,Node> (); this.cache_id2LayerMap = new HashMap <Long,NetworkLayer> (); this.cache_id2srgMap= new HashMap<Long,SharedRiskGroup> (); this.cache_id2LinkMap = new HashMap<Long,Link> (); this.cache_id2DemandMap = new HashMap<Long,Demand> (); this.cache_id2MulticastDemandMap = new HashMap<Long,MulticastDemand> (); this.cache_id2RouteMap = new HashMap<Long,Route> (); this.cache_id2MulticastTreeMap = new HashMap<Long,MulticastTree> (); this.cache_id2ProtectionSegmentMap = new HashMap<Long,ProtectionSegment> (); this.DEFAULT_ROUTING_TYPE = originNetPlan.DEFAULT_ROUTING_TYPE; this.isModifiable = true; this.networkDescription = originNetPlan.networkDescription; this.networkName = originNetPlan.networkName; this.nextElementId = originNetPlan.nextElementId; this.interLayerCoupling = new DirectedAcyclicGraph<NetworkLayer, DemandLinkMapping>(DemandLinkMapping.class); /* Create the new network elements, not all the fields filled */ for (Node originNode : originNetPlan.nodes) { Node newElement = new Node (this , originNode.id , originNode.index , originNode.nodeXYPositionMap.getX(), originNode.nodeXYPositionMap.getY(), originNode.name, originNode.attributes); cache_id2NodeMap.put(originNode.id, newElement); nodes.add (newElement); if (!originNode.isUp) cache_nodesDown.add (newElement); } for (SharedRiskGroup originSrg : originNetPlan.srgs) { SharedRiskGroup newElement = new SharedRiskGroup (this , originSrg.id , originSrg.index , null , null, originSrg.meanTimeToFailInHours , originSrg.meanTimeToRepairInHours , originSrg.attributes); cache_id2srgMap.put(originSrg.id, newElement); srgs.add (newElement); } for (NetworkLayer originLayer : originNetPlan.layers) { NetworkLayer newLayer = new NetworkLayer (this , originLayer.id , originLayer.index , originLayer.demandTrafficUnitsName , originLayer.description , originLayer.name , originLayer.linkCapacityUnitsName , originLayer.attributes); cache_id2LayerMap.put(originLayer.id, newLayer); layers.add (newLayer); if (originLayer.id == originNetPlan.defaultLayer.id) this.defaultLayer = newLayer; for (Demand originDemand : originLayer.demands) { Demand newElement = new Demand (this , originDemand.id , originDemand.index , newLayer , this.cache_id2NodeMap.get(originDemand.ingressNode.id) , this.cache_id2NodeMap.get(originDemand.egressNode.id) , originDemand.offeredTraffic , originDemand.attributes); cache_id2DemandMap.put(originDemand.id, newElement); newLayer.demands.add (newElement); } for (MulticastDemand originDemand : originLayer.multicastDemands) { Set<Node> newEgressNodes = new HashSet<Node> (); for (Node oldEgressNode : originDemand.egressNodes) newEgressNodes.add (this.cache_id2NodeMap.get(oldEgressNode.id)); MulticastDemand newElement = new MulticastDemand (this , originDemand.id , originDemand.index , newLayer , this.cache_id2NodeMap.get(originDemand.ingressNode.id) , newEgressNodes , originDemand.offeredTraffic , originDemand.attributes); cache_id2MulticastDemandMap.put(originDemand.id, newElement); newLayer.multicastDemands.add (newElement); } for (Link originLink : originLayer.links) { Link newElement = new Link (this , originLink.id , originLink.index , newLayer , this.cache_id2NodeMap.get(originLink.originNode.id) , this.cache_id2NodeMap.get(originLink.destinationNode.id) , originLink.lengthInKm , originLink.propagationSpeedInKmPerSecond , originLink.capacity , originLink.attributes); cache_id2LinkMap.put(originLink.id, newElement); newLayer.links.add (newElement); } for (Route originRoute : originLayer.routes) { List<Link> newSeqLinksRealPath = new LinkedList<Link> (); for (Link oldLink : originRoute.seqLinksRealPath) { Link newLink = this.cache_id2LinkMap.get(oldLink.id); newSeqLinksRealPath.add (newLink); } Route newElement = new Route (this , originRoute.id , originRoute.index , cache_id2DemandMap.get(originRoute.demand.id) , newSeqLinksRealPath , originRoute.attributes); newElement.carriedTraffic = originRoute.carriedTraffic; newElement.carriedTrafficIfNotFailing = originRoute.carriedTrafficIfNotFailing; newElement.occupiedLinkCapacity = originRoute.occupiedLinkCapacity; newElement.occupiedLinkCapacityIfNotFailing = originRoute.occupiedLinkCapacityIfNotFailing; cache_id2RouteMap.put(originRoute.id, newElement); newLayer.routes.add (newElement); } for (MulticastTree originTree : originLayer.multicastTrees) { Set<Link> newSetLinks = new HashSet<Link> (); for (Link oldLink : originTree.linkSet) newSetLinks.add (this.cache_id2LinkMap.get(oldLink.id)); MulticastTree newElement = new MulticastTree (this , originTree.id , originTree.index , cache_id2MulticastDemandMap.get(originTree.demand.id) , newSetLinks , originTree.attributes); cache_id2MulticastTreeMap.put(originTree.id, newElement); newLayer.multicastTrees.add (newElement); newElement.carriedTraffic = originTree.carriedTraffic; newElement.occupiedLinkCapacity = originTree.occupiedLinkCapacity; newElement.carriedTrafficIfNotFailing = originTree.carriedTrafficIfNotFailing; newElement.occupiedLinkCapacityIfNotFailing = originTree.occupiedLinkCapacityIfNotFailing; } for (ProtectionSegment originSegment : originLayer.protectionSegments) { List<Link> newSeqLinks = new LinkedList<Link> (); for (Link oldLink : originSegment.seqLinks) newSeqLinks.add (this.cache_id2LinkMap.get(oldLink.id)); ProtectionSegment newElement = new ProtectionSegment (this , originSegment.id , originSegment.index , newSeqLinks , originSegment.capacity , originSegment.attributes); cache_id2ProtectionSegmentMap.put(originSegment.id, newElement); newLayer.protectionSegments.add (newElement); } } /* Copy the rest of the fields */ for (Node newNode : this.nodes) newNode.copyFrom (originNetPlan.nodes.get(newNode.index)); for (SharedRiskGroup newSrg : this.srgs) newSrg.copyFrom (originNetPlan.srgs.get(newSrg.index)); for (NetworkLayer newLayer : this.layers) newLayer.copyFrom (originNetPlan.layers.get(newLayer.index)); this.interLayerCoupling = new DirectedAcyclicGraph<NetworkLayer, DemandLinkMapping>(DemandLinkMapping.class); for (NetworkLayer layer : originNetPlan.interLayerCoupling.vertexSet()) this.interLayerCoupling.addVertex(this.netPlan.getNetworkLayerFromId(layer.id)); for (DemandLinkMapping mapping : originNetPlan.interLayerCoupling.edgeSet()) { if (mapping.isEmpty()) throw new RuntimeException ("Bad"); DemandLinkMapping newMapping = new DemandLinkMapping(); for (Entry<Demand,Link> originEntry : mapping.getDemandMap().entrySet()) newMapping.put (this.netPlan.getDemandFromId(originEntry.getKey().id) , this.netPlan.getLinkFromId(originEntry.getValue().id)); for (Entry<MulticastDemand,Set<Link>> originEntry : mapping.getMulticastDemandMap().entrySet()) { Set<Link> newSetLink = new HashSet<Link> (); for (Link originLink : originEntry.getValue()) newSetLink.add (this.netPlan.getLinkFromId(originLink.id)); newMapping.put (this.netPlan.getMulticastDemandFromId(originEntry.getKey().id) , newSetLink); } try { this.interLayerCoupling.addDagEdge(newMapping.getDemandSideLayer () , newMapping.getLinkSideLayer (), newMapping); } catch (Exception e) { throw new RuntimeException ("Bad: " + e); } } if (ErrorHandling.isDebugEnabled()) this.checkCachesConsistency(); } /** * <p>Returns the values of a given attribute for all the provided network elements.</p> * @param collection Collection of network elements * @param attribute Attribute name * @return Map with the value of each attribute per network element (value may be {@code null} if not defined * @see com.net2plan.interfaces.networkDesign.NetworkElement */ public static Map<NetworkElement,String> getAttributes (Collection<? extends NetworkElement> collection , String attribute) { Map<NetworkElement,String> attributes = new HashMap<NetworkElement,String> (); for (NetworkElement e : collection) attributes.put (e , e.getAttribute (attribute)); return attributes; } /** * <p>Returns the values of a given attribute for all the provided network elements, as a {@code DoubleMatrix1D} vector.</p> * @param collection Collection of network elements * @param attribute Attribute name * @param defaultValue If an element has value for the attribute, or it is not a double (it fails in the {@code Double.parseDouble} conversion), then this value is set * @return array with one element per {@code NetworkElement}, in the same order as the input {@code Collection}. * @see com.net2plan.interfaces.networkDesign.NetworkElement */ public static DoubleMatrix1D getAttributeValues (Collection<? extends NetworkElement> collection , String attributeName , double defaultValue) { DoubleMatrix1D res = DoubleFactory1D.dense.make(collection.size()); int counter = 0; for (NetworkElement e : collection) { double val = defaultValue; String value = e.getAttribute(attributeName); if (value != null) try { val = Double.parseDouble(value); } catch (Exception ex) {} res.set(counter ++ , val); } return res; } /** * <p>Returns the demand with the given index.</p> * @param index Demand index * @param optionalLayerParameter Network layer (optional) * @return The demand with the given index (or {@code null} if nonexistent, index lower than 0 or greater than the number of elements minus one) * @see com.net2plan.interfaces.networkDesign.Demand */ public Demand getDemand (int index , NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter (optionalLayerParameter); if ((index < 0) || (index > layer.demands.size () -1)) return null; else return layer.demands.get(index); } /** * <p>Returns the demand with the given unique identifier.</p> * @param uid Demand unique id * @return The demand with the given unique id (or {@code null} if nonexistent) * @see com.net2plan.interfaces.networkDesign.Demand */ public Demand getDemandFromId (long uid) { return cache_id2DemandMap.get(uid); } /** * <p>Returns the array of demand unique ids for the given layer (i-th position, corresponds to index i). If no layer is provided, the default layer is used.</p> * @param optionalLayerParameter Network layer (optional) * @return ArrayList of demand ids for the given layer (or the default layer if no input was provided) * @see com.net2plan.interfaces.networkDesign.Demand */ public ArrayList<Long> getDemandIds (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); ArrayList<Long> res = new ArrayList<Long> (); for (Demand e : layer.demands) res.add (e.id); return res; } /** * <p>Returns the array of demands for the given layer (i-th position, corresponds to index i). If no layer is provided, the default layer is used.</p> * @param optionalLayerParameter Network layer (optional) * @return List of demands for the given layer (or the default layer if no input was provided) * @see com.net2plan.interfaces.networkDesign.Demand */ public List<Demand> getDemands (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); return (List<Demand>) Collections.unmodifiableList(layer.demands); } /** * <p>Returns the demands that have blocked traffic in the given layer. If no layer is provided, the default layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return List of demands with blocked traffic * @see com.net2plan.interfaces.networkDesign.Demand */ public List<Demand> getDemandsBlocked (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); List<Demand> res = new LinkedList<Demand> (); for (Demand d : layer.demands) if (d.isBlocked()) res.add (d); return res; } /** * <p>Returns the set of unicast demands that are coupled.</p> * @param optionalLayerParameter Network layer (optional) * @return {@code Set} of unicast demands that have blocked traffic for the given layer (or the defaukt layer if no input was provided) */ public Set<Demand> getDemandsCoupled (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); Set<Demand> res = new HashSet<Demand> (); for (Demand demand : layer.demands) if (demand.coupledUpperLayerLink != null) res.add (demand); return res; } /** * <p>Returns the total blocked traffic, summing up all the unicast demands, in the given layer. If no layer is provided, the default layer is assumed.</p> * * @param optionalLayerParameter Network layer (optional) * @return Total blocked trafic */ public double getDemandTotalBlockedTraffic(NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); double accum = 0; for (Demand d : layer.demands) accum += Math.max(0 , d.offeredTraffic - d.carriedTraffic); return accum; } /** * <p>Returns the total carried traffic, summing up for all the unicast demands, in the given layer. If no layer is provided, the default layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return Total carried traffic */ public double getDemandTotalCarriedTraffic(NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); double accum = 0; for (Demand d : layer.demands) accum += d.carriedTraffic; return accum; } /** * <p>Returns the total offered traffic, summing up for all the unicast demands, in the given layer. If no layer is provided, the default layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return Total offered traffic */ public double getDemandTotalOfferedTraffic(NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); double accum = 0; for (Demand d : layer.demands) accum += d.offeredTraffic; return accum; } /** * <p>Returns the name of the traffic units of the demands of the given layer. If no layer is provided, the default layer is assumed.</p> * * @param optionalLayerParameter Network layer (optional) * @return {@code String} with the traffic units name of the demands */ public String getDemandTrafficUnitsName (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); return layer.demandTrafficUnitsName; } /** * <p>Returns the traffic that is carried using a forwarding rule, in the given layer. If no layer is provided, the default layer is assumed.</p> * * <p><b>Important</b>: Routing type must be {@link com.net2plan.utils.Constants.RoutingType#HOP_BY_HOP_ROUTING HOP_BY_HOP_ROUTING}.</p> * @param demand Outgoing demand * @param link Link * @return Carried traffic by the given link from the given demand using a forwarding rule */ public double getForwardingRuleCarriedTraffic(Demand demand , Link link) { checkInThisNetPlan(demand); checkInThisNetPlanAndLayer(link , demand.layer); demand.layer.checkRoutingType(RoutingType.HOP_BY_HOP_ROUTING); return demand.layer.forwardingRules_x_de.get(demand.index,link.index); } /** * <p>Returns the forwarding rules for the given layer. If no layer is provided, the default layer is assumed.</p> * * <p><b>Important</b>: Routing type must be {@link com.net2plan.utils.Constants.RoutingType#HOP_BY_HOP_ROUTING HOP_BY_HOP_ROUTING}.</p> * @param optionalLayerParameter Network layer (optional) * @return The forwarding rules as a map of splitting factor (value) per demand and link (key) * @see com.net2plan.utils.Pair */ public Map<Pair<Demand,Link>,Double> getForwardingRules (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); layer.checkRoutingType(RoutingType.HOP_BY_HOP_ROUTING); Map<Pair<Demand,Link>,Double> res = new HashMap<Pair<Demand,Link>,Double> (); IntArrayList ds = new IntArrayList (); IntArrayList es = new IntArrayList (); DoubleArrayList vals = new DoubleArrayList (); layer.forwardingRules_f_de.getNonZeros(ds,es,vals); for (int cont = 0 ; cont < ds.size () ; cont ++) res.put (Pair.of (layer.demands.get(ds.get(cont)) , layer.links.get(es.get(cont))) , vals.get(cont)); return res; } /** * <p>Returns the splitting factor of the forwarding rule of the given demand and link. If no layer is provided, default layer is assumed.</p> * @param demand Outgoing demand * @param link Link * @param optionalLayerParameter Network layer (optional) * @return The splitting factor */ public double getForwardingRuleSplittingFactor (Demand demand , Link link , NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); checkInThisNetPlanAndLayer(demand , layer); checkInThisNetPlanAndLayer(link , layer); layer.checkRoutingType(RoutingType.HOP_BY_HOP_ROUTING); return layer.forwardingRules_f_de.get(demand.index,link.index); } /** * <p>Returns the network layer with the given unique identifier.</p> * @param index Network layer index * @return The network layer with the given index ({@code null} if it does not exist) */ public NetworkLayer getNetworkLayer (int index) { if ((index < 0) || (index > layers.size () -1)) return null; else return layers.get(index); } /** * <p>Returns the network layer with the given name.</p> * @param name Network layer name * @return The network layer with the given name ({@code null} if it does not exist) */ public NetworkLayer getNetworkLayer (String name) { for (NetworkLayer layer : layers) if (layer.name.equals(name)) return layer; return null; } /** * <p>Returns the node with the given index.</p> * @param index Node index * @return The node with the given index ({@code null} if it does not exist, index iss lesser than zero or greater than the number of elements minus one) */ public Node getNode (int index) { if ((index < 0) || (index > nodes.size () -1)) return null; else return nodes.get(index); } /** * <p>Returns the link with the given index in the given layer. If no layer is provided, default layer is assumed.</p> * @param index Link index * @param optionalLayerParameter Network layer (optional) * @return Link with the given index or {@code null} if it does not exist, index islower than 0, or greater than the number of links minus one */ public Link getLink (int index , NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); if ((index < 0) || (index > layer.links.size () -1)) return null; else return layer.links.get(index); } /** * <p>Returns the link with the given unique identifier.</p> * @param uid Link unique id * @return Link with the given id, or {@code null} if it does not exist */ public Link getLinkFromId (long uid) { checkAttachedToNetPlanObject(); return cache_id2LinkMap.get(uid); } /** * <p>Returns the name of the capacity units of the links of the given layer. If no layer is provided, the default layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return The name of capacity units */ public String getLinkCapacityUnitsName (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); return layer.linkCapacityUnitsName; } // /** // * <p>Returns a map where keys are the unique id of network elements and the values are a pair of uid representing the end nodes.</p> // * @param links Network elements // * @return A map with the end nodes unique ids (values) of each network element (key) // * @see com.net2plan.utils.Pair // */ // public Map<Long,Pair<Long,Long>> getLinkIdMap (Collection<? extends NetworkElement> links) // { // checkInThisNetPlan(links); // Map<Long,Pair<Long,Long>> map = new HashMap<Long,Pair<Long,Long>> (); // if (links.isEmpty()) return map; // if (links.iterator().next() instanceof Link) // for (Link e : (List<Link>) links) // { // map.put(e.id, Pair.of(e.originNode.id, e.destinationNode.id)); // } // else if (links.iterator().next() instanceof Demand) // for (Demand e : (List<Demand>) links) // { // map.put(e.id, Pair.of(e.ingressNode.id, e.egressNode.id)); // } // else if (links.iterator().next() instanceof Route) // for (Route e : (List<Route>) links) // { // map.put(e.id, Pair.of(e.ingressNode.id, e.egressNode.id)); // } // else throw new Net2PlanException ("Only can make id link maps for links, demands, routes and protection segments"); // return map; // } /** * <p>Returns the array of link ids for the given layer (i-th position, corresponds to index i). If no layer is provided, the default layer is assumed.</p> * @param optionalLayerParameter Network layer (optional * @return Array of link ids */ public ArrayList<Long> getLinkIds (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); ArrayList<Long> res = new ArrayList<Long> (); for (Link e : layer.links) res.add (e.id); return res; } /** * <p>Return a list of all the links in the given layer. If no layer is provided, the default layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return All the links for the given (or default) layer */ public List<Link> getLinks (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); return (List<Link>) Collections.unmodifiableList(layer.links); } /** * <p>Returns the set of links that are a bottleneck, i.e the fraction of occupied capacity respect to the total (including the capacities in the protection segments) * is highest. If no layer is provided, the default layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return The {@code Set} of bottleneck links */ public Set<Link> getLinksAreBottleneck (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); double maxRho = 0; final double PRECISION_FACTOR = Double.parseDouble(Configuration.getOption("precisionFactor")); Set<Link> res = new HashSet<Link> (); for (Link e : layer.links) if (Math.abs (e.occupiedCapacitySummingRoutesAndCarriedTrafficByProtectionSegments / e.capacity - maxRho) < PRECISION_FACTOR) res.add (e); else if (e.occupiedCapacitySummingRoutesAndCarriedTrafficByProtectionSegments / e.capacity > maxRho) { maxRho = e.occupiedCapacitySummingRoutesAndCarriedTrafficByProtectionSegments / e.capacity; res.clear (); res.add (e); } return res; } /** * <p>Returns the set of links that have zero capacity in the given layer. If no layer is provided, the default layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return The {@code Set} of links with zero capacity */ public Set<Link> getLinksWithZeroCapacity (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); final double PRECISION_FACTOR = Double.parseDouble(Configuration.getOption("precisionFactor")); Set<Link> res = new HashSet<Link> (); for (Link e : layer.links) if (e.capacity < PRECISION_FACTOR) res.add (e); return res; } /** * <p>Returns the set of links that are coupled to a multicast demand in the given layer. If no layer is provided, the default layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return The {@code Set} of links coupled to a multicast demand * @see com.net2plan.interfaces.networkDesign.MulticastDemand */ public Set<Link> getLinksCoupledToMulticastDemands (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); Set<Link> res = new HashSet<Link> (); for (Link link : layer.links) if (link.coupledLowerLayerMulticastDemand != null) res.add (link); return res; } /** * <p>Returns the set of links that are couple to a unicast demand in the given layer. If no layer is provided, the default layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return The {@code Set} of links coupled to a unicast demand * @see com.net2plan.interfaces.networkDesign.Demand */ public Set<Link> getLinksCoupledToUnicastDemands (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); Set<Link> res = new HashSet<Link> (); for (Link link : layer.links) if (link.coupledLowerLayerDemand != null) res.add (link); return res; } /** * <p>Returns the set of links that are down in the given layer. If no layer is provided, the default layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return The {@code Set} of links that are down */ public Set<Link> getLinksDown (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); return Collections.unmodifiableSet(layer.cache_linksDown); } /** * <p>Returns the set of links that are down in all layers.</p> * @return The {@code Set} of links down */ public Set<Link> getLinksDownAllLayers () { Set<Link> res = new HashSet<Link> (); for (NetworkLayer layer : layers) res.addAll (layer.cache_linksDown); return res; } /** * <p>Returns the set of links that are up in the given layer. If no layer is provided, the default layer is assumed.</p> * @param optionalLayerParameter Network layer )optional) * @return The {@code Set} of links that are up */ public Set<Link> getLinksUp (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); Set<Link> res = new HashSet<Link> (layer.links); res.removeAll (layer.cache_linksDown); return res; } /** * <p>Returns the set of links that are up in all layers.</p> * @return The {@code Set} of links that are up */ public Set<Link> getLinksUpAllLayers () { Set<Link> res = new HashSet<Link> (); for (NetworkLayer layer : layers) res.addAll (getLinksUp (layer)); return res; } /** * <p>Returns the set of links oversuscribed: the total occupied capacity (including the traffic in the protection segments) exceeds the link capacity * (including the reserved capacity by the protection segments). If no layer is provided, the default layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return The {@code Set} of oversubscribed links */ public Set<Link> getLinksOversubscribed (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); Set<Link> res = new HashSet<Link> (); for (Link e : layer.links) if (e.capacity < e.occupiedCapacitySummingRoutesAndCarriedTrafficByProtectionSegments) res.add (e); return res; } /** * <p>Returns the demand-link incidence matrix (a <i>D</i>x<i>E</i> matrix in * which an element <i>&delta;<sub>de</sub></i> is equal to the number of * times which traffic routes carrying traffic from demand <i>d</i> traverse * link <i>e</i>). If no layer is provided, the default layer is assumed.</p> * * @param optionalLayerParameter Network layer (optional) * @return The demand-link incidence matrix */ public DoubleMatrix2D getMatrixDemand2LinkAssignment(NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); DoubleMatrix2D delta_dr = getMatrixDemand2RouteAssignment(layer); DoubleMatrix2D delta_er = getMatrixLink2RouteAssignment(layer); return delta_dr.zMult(delta_er.viewDice(), null); } /** * <p>Returns the route-srg incidence matrix (an <i>R</i>x<i>S</i> matrix in which an element <i>&delta;<sub>rs</sub></i> equals 1 if route <i>r</i> * fails when SRG <i>s</i> is affected. If no layer is provided, the default layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return The route-srg incidence matrix */ public DoubleMatrix2D getMatrixRoute2SRGAffecting (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); DoubleMatrix2D A_rs = DoubleFactory2D.sparse.make (layer.routes.size () , srgs.size ()); for (Route r : layer.routes) for (Link e : r.seqLinksRealPath) for (SharedRiskGroup srg : e.cache_srgs) A_rs.set (r.index , srg.index , 1.0); return A_rs; } /** * <p>Returns the protection segment-srg incidence matrix (an <i>P</i>x<i>S</i> matrix in which an element <i>&delta;<sub>ps</sub></i> equals 1 if protection segment <i>p</i> * fails when SRG <i>s</i> is affected. If no layer is provided, the default layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return The protection segment-srg incidence matrix */ public DoubleMatrix2D getMatrixProtectionSegment2SRGAffecting (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); DoubleMatrix2D A_rs = DoubleFactory2D.sparse.make (layer.protectionSegments.size () , srgs.size ()); for (ProtectionSegment r : layer.protectionSegments) for (Link e : r.seqLinks) for (SharedRiskGroup srg : e.cache_srgs) A_rs.set (r.index , srg.index , 1.0); return A_rs; } /** * <p>Returns the multicast tree-srg incidence matrix (an <i>T</i>x<i>S</i> matrix in which an element <i>&delta;<sub>ts</sub></i> equals 1 when multicast tree <i>t</i> * fails when SRG <i>s</i> is affected. If no layer is provided, the default layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return The multicast tree-srg incidence matrix */ public DoubleMatrix2D getMatrixMulticastTree2SRGAffecting (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); DoubleMatrix2D A_rs = DoubleFactory2D.sparse.make (layer.multicastTrees.size () , srgs.size ()); for (MulticastTree r : layer.multicastTrees) for (Link e : r.linkSet) for (SharedRiskGroup srg : e.cache_srgs) A_rs.set (r.index , srg.index , 1.0); return A_rs; } /** * <p>Returns the multicast demand-link incidence matrix (a <i>D</i>x<i>E</i> matrix in * which an element <i>&delta;<sub>de</sub></i> is equal to the number of * times which multicast trees carrying traffic from demand <i>d</i> traverse * link <i>e</i>). If no layer is provided, the default layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return The multicast demand-link incidence matrix */ public DoubleMatrix2D getMatrixMulticastDemand2LinkAssignment(NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); DoubleMatrix2D delta_dr = getMatrixMulticastDemand2MulticastTreeAssignment(layer); DoubleMatrix2D delta_er = getMatrixLink2MulticastTreeAssignment(layer); return delta_dr.zMult(delta_er.viewDice(), null); } /** * <p>Returns the demand-link incidence matrix (<i>D</i>x<i>E</i> in which an element <i>&delta;<sub>de</sub></i> is equal to the amount of traffic of each demand carried in each link). Rows * and columns are in increasing order of demand and link identifiers, respectively. If no layer is provided, the default layer is assumed</p> * * <p><b>Important</b>: Routing type must be {@link com.net2plan.utils.Constants.RoutingType#HOP_BY_HOP_ROUTING HOP_BY_HOP_ROUTING}.</p> * @param optionalLayerParameter Network layer (optional) * @return Splitting ratio matrix */ public DoubleMatrix2D getMatrixDemand2LinkTrafficCarried(NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); if (layer.routingType == RoutingType.HOP_BY_HOP_ROUTING) return layer.forwardingRules_x_de.copy(); DoubleMatrix2D x_de = DoubleFactory2D.sparse.make (layer.demands.size () , layer.links.size ()); for (Route r : layer.routes) for (Link e : r.seqLinksRealPath) x_de.set (r.demand.index , e.index , x_de.get(r.demand.index , e.index) + r.carriedTraffic); return x_de; } public DoubleMatrix2D getMatrixDestination2LinkTrafficCarried(NetworkLayer ... optionalLayerParameter) { DoubleMatrix2D x_de = getMatrixDemand2LinkTrafficCarried(optionalLayerParameter); return this.getMatrixNodeDemandIncomingIncidence().zMult(x_de , null); } /** * <p>Returns the demand-route incidence matrix (a <i>D</i>x<i>R</i> matrix in * which an element <i>&delta;<sub>dr</sub></i> is equal to 1 if traffic * route <i>r</i> is able to carry traffic from demand <i>d</i>). If no layer is provided, the default layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return The demand-route incidence matrix */ public DoubleMatrix2D getMatrixDemand2RouteAssignment (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); layer.checkRoutingType(RoutingType.SOURCE_ROUTING); int D = layer.demands.size (); int R = layer.routes.size (); DoubleMatrix2D delta_dr = DoubleFactory2D.sparse.make(D, R); for (Route r : layer.routes) delta_dr.set (r.demand.index , r.index , 1); return delta_dr; } /** * <p>Returns the multicast demand-multicast tree incidence matrix (a <i>D</i>x<i>T</i> matrix in * which an element <i>&delta;<sub>dt</sub></i> is equal to 1 if multicast tree <i>t</i> is able to carry traffic from multicast demand <i>d</i>). * If no layer is provided, the default layer is * assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return The multicast demand-multicast tree incidence matrix */ public DoubleMatrix2D getMatrixMulticastDemand2MulticastTreeAssignment (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); int D = layer.multicastDemands.size (); int T = layer.multicastTrees.size (); DoubleMatrix2D delta_dt = DoubleFactory2D.sparse.make(D, T); for (MulticastTree t : layer.multicastTrees) delta_dt.set (t.demand.index , t.index , 1); return delta_dt; } /** * <p>Returns the splitting ratio matrix (fractions of traffic entering a node from * demand 'd', leaving that node through link 'e'). Rows and columns are in * increasing order of demand and link identifiers, respectively. If no layer is provided, the default layer is assumed</p> * * <p><b>Important</b>: Routing type must be {@link com.net2plan.utils.Constants.RoutingType#HOP_BY_HOP_ROUTING HOP_BY_HOP_ROUTING}.</p> * @param optionalLayerParameter Network layer (optional) * @return Splitting ratio matrix */ public DoubleMatrix2D getMatrixDemandBasedForwardingRules (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); if (layer.routingType == RoutingType.HOP_BY_HOP_ROUTING) return layer.forwardingRules_f_de.copy (); else return GraphUtils.convert_xp2xde(layer.links , layer.demands , layer.routes); } /** * <p>A destination-based routing in the form of fractions <i>f<sub>te</sub></i> (fraction of the traffic targeted to node <i>t</i> that arrives (or is generated in) node <i>a</i>(<i>e</i>) * (the initial node of link <i>e</i>), that is forwarded through link <i>e</i>). If no layer is provided, the default layer is assumed.</p> * @param optionalLayer Network layer (optional) * @return A destination-based routing from a given network design */ public DoubleMatrix2D getMatrixDestinationBasedForwardingRules (NetworkLayer ... optionalLayer) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayer); DoubleMatrix2D x_te = null; if (layer.routingType == RoutingType.HOP_BY_HOP_ROUTING) x_te = GraphUtils.convert_xde2xte(nodes ,layer.links , layer.demands , layer.forwardingRules_f_de); else x_te = GraphUtils.convert_xp2xte(nodes,layer.links,layer.demands,layer.routes); return GraphUtils.convert_xte2fte(nodes , layer.links , x_te); } /** * Returns the link-protection segment assignment matrix (an <i>E</i>x<i>R</i> matrix in * which an element <i>&delta;<sub>ep</sub></i> is equal to the number of * times which protection segment <i>r</i> traverses link <i>e</i>). * @param optionalLayerParameter Network layer (optional) * @return The link-protection segment assignment matrix */ public DoubleMatrix2D getMatrixLink2ProtectionSegmentAssignment (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); layer.checkRoutingType(RoutingType.SOURCE_ROUTING); DoubleMatrix2D delta_er = DoubleFactory2D.sparse.make(layer.links.size(), layer.protectionSegments.size()); for (ProtectionSegment r : layer.protectionSegments) for (Link e : r.seqLinks) delta_er.set (e.index , r.index , delta_er.get (e.index , r.index) + 1); return delta_er; } /** *<p>Returns the link-route incidence matrix (an <i>E</i>x<i>R</i> matrix in * which an element <i>&delta;<sub>ep</sub></i> is equal to the number of * times which traffic route <i>r</i> traverses link <i>e</i>). If no layer is provided, the default layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return The link-route incidene matrix */ public DoubleMatrix2D getMatrixLink2RouteAssignment (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); layer.checkRoutingType(RoutingType.SOURCE_ROUTING); int E = layer.links.size(); int R = layer.routes.size (); DoubleMatrix2D delta_er = DoubleFactory2D.sparse.make(E, R); for (Route r : layer.routes) for (Link e : r.seqLinksRealPath) delta_er.set (e.index , r.index , delta_er.get (e.index , r.index) + 1); return delta_er; } /** * <p>Returns the link-multicast incidence matrix (an <i>E</i>x<i>T</i> matrix in which an element <i>&delta;<sub>et</sub></i> is equal * to the number of times a multicast tree <i>t</i> traverse link <i>e</i>. If no layer is provided, the default layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return The link-multicast tree incidence matrix */ public DoubleMatrix2D getMatrixLink2MulticastTreeAssignment (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); int E = layer.links.size(); int T = layer.multicastTrees.size (); DoubleMatrix2D delta_et = DoubleFactory2D.sparse.make(E, T); for (MulticastTree t : layer.multicastTrees) for (Link e : t.linkSet) delta_et.set (e.index , t.index , delta_et.get (e.index , t.index) + 1); return delta_et; } /** * <p>Returns the link-srg assignment matrix (an <i>E</i>x<i>S</i> matrix in which an element <i>&delta;<sub>es</sub></i> equals 1 if link <i>e</i> * fails when SRG <i>s</i> is affected. If no layer is provided, the default layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return The link-srg incidence matrix */ public DoubleMatrix2D getMatrixLink2SRGAssignment (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); DoubleMatrix2D delta_es = DoubleFactory2D.sparse.make (layer.links.size() , srgs.size()); for (SharedRiskGroup s : srgs) { for (Link e : s.links) if (e.layer.equals (layer)) delta_es.set (e.index , s.index , 1); for (Node n : s.nodes) { for (Link e : n.cache_nodeIncomingLinks) if (e.layer.equals(layer)) delta_es.set (e.index , s.index , 1); for (Link e : n.cache_nodeOutgoingLinks) if (e.layer.equals(layer)) delta_es.set (e.index , s.index , 1); } } return delta_es; } /** * <p>Returns the multicast demand-link incidence matrix (<i>D</i>x<i>E</i> in which an element <i>&delta;<sub>de</sub></i> is equal to the amount of traffic of * each multicast demand carried in each link). Rows * and columns are in increasing order of demand and link identifiers, respectively. If no layer is provided, the default layer is assumed</p> * * <p><b>Important</b>: Routing type must be {@link com.net2plan.utils.Constants.RoutingType#HOP_BY_HOP_ROUTING HOP_BY_HOP_ROUTING}.</p> * @param optionalLayerParameter Network layer (optional) * @return Splitting ratio matrix */ public DoubleMatrix2D getMatrixMulticastDemand2LinkTrafficCarried(NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); DoubleMatrix2D x_de = DoubleFactory2D.sparse.make (layer.multicastDemands.size () , layer.links.size ()); for (MulticastTree t : layer.multicastTrees) for (Link e : t.linkSet) x_de.set (t.demand.index , e.index , x_de.get(t.demand.index , e.index) + t.carriedTraffic); return x_de; } /** * <p>Returns the <i>N</i>x<i>N</i> Euclidean distance matrix (derived * from node coordinates), where <i>N</i> is the number of nodes within the network.</p> * @return The Euclidean distance matrix */ public DoubleMatrix2D getMatrixNode2NodeEuclideanDistance () { int N = nodes.size(); DoubleMatrix2D out = DoubleFactory2D.dense.make(N, N); for(Node node_1 : nodes) { for (Node node_2 : nodes) { if (node_1.index >= node_2.index) continue; double physicalDistance = getNodePairEuclideanDistance(node_1, node_2); out.setQuick(node_1.index, node_2.index, physicalDistance); out.setQuick(node_2.index, node_1.index, physicalDistance); } } return out; } /** * <p>Returns the link-link bidirectionality matrix (a <i>E</i>x<i>E</i> matrix where the element <i>&delta;<sub>ee'</sub></i> equals 1 when each position <i>e</i> and <i>e'</i> represent a bidirectional * link at the given layer. If no layer is provided, default layer is assumed</p> * @param optionalLayerParameter Network layer (optional) * @return The link-link bidirectionality matrix */ public DoubleMatrix2D getMatrixLink2LinkBidirectionalityMatrix (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); final int E = layer.links.size(); DoubleMatrix2D out = DoubleFactory2D.dense.make(E, E); for(Link e_1 : layer.links) { final String idBidirPair_st = e_1.getAttribute(KEY_STRING_BIDIRECTIONALCOUPLE); if (idBidirPair_st == null) throw new Net2PlanException ("Some links are not bidirectional. Use this method for networks created using addLinkBidirectional"); final long idBidirPair = Long.parseLong (idBidirPair_st); final Link linkPair = netPlan.getLinkFromId(idBidirPair); if (linkPair == null) throw new Net2PlanException ("Some links are not bidirectional."); if ((linkPair.getOriginNode() != e_1.getDestinationNode()) ||(linkPair.getDestinationNode() != e_1.getOriginNode())) throw new Net2PlanException ("Some links are not bidirectional."); out.set(e_1.getIndex () , linkPair.getIndex () , 1.0); out.set(linkPair.getIndex () , e_1.getIndex () , 1.0); } return out; } /** * <p>Returns the <i>N</i>x<i>N</i> Haversine distance matrix (derived * from node coordinates, where 'xCoord' is equal to longitude and 'yCoord' * is equal to latitude), where <i>N</i> is the number of nodes within the network.</p> * * @return Haversine distance matrix * @see <a href="http://www.movable-type.co.uk/scripts/latlong.html">Calculate distance, bearing and more between Latitude/Longitude points</a> */ public DoubleMatrix2D getMatrixNode2NodeHaversineDistanceInKm () { int N = nodes.size(); DoubleMatrix2D out = DoubleFactory2D.dense.make(N, N); for(Node node_1 : nodes) { for (Node node_2 : nodes) { if (node_1.index >= node_2.index) continue; double physicalDistance = getNodePairHaversineDistanceInKm(node_1, node_2); out.setQuick(node_1.index, node_2.index, physicalDistance); out.setQuick(node_2.index, node_1.index, physicalDistance); } } return out; } /** * <p>Returns the traffic matrix, where rows and columns represent the ingress * node and the egress node, respectively, in increasing order of identifier. If no layer is provided, the default layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return The traffic matrix */ public DoubleMatrix2D getMatrixNode2NodeOfferedTraffic(NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); int N = nodes.size(); DoubleMatrix2D trafficMatrix = DoubleFactory2D.dense.make(N, N); for (Demand d : layer.demands) trafficMatrix.setQuick(d.ingressNode.index, d.egressNode.index, trafficMatrix.get(d.ingressNode.index, d.egressNode.index) + d.offeredTraffic); return trafficMatrix; } /** * <p>Returns a <i>N</i>x<i>N</i> matrix where each position accounts from the humber of demands that node <i>i</i> (row) as ingress node and <i>j</i> (column) as egress node. * If no layer is provided, the default layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return Adjacency matrix */ public DoubleMatrix2D getMatrixNodeDemandAdjacency (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); int N = nodes.size (); DoubleMatrix2D delta_nn = DoubleFactory2D.sparse.make(N , N); for (Demand d : layer.demands) delta_nn.set (d.ingressNode.index , d.egressNode.index , delta_nn.get (d.ingressNode.index , d.egressNode.index) + 1); return delta_nn; } /** * <p>Returns a <i>N</i>x<i>N</i> matrix where each position accounts from the humber of multicast demands that node <i>i</i> (row) as ingress node and <i>j</i> (column) as an egress node. * If no layer is provided, the default layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return Adjacency matrix */ public DoubleMatrix2D getMatrixNodeMulticastDemandAdjacency (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); int N = nodes.size (); DoubleMatrix2D delta_nn = DoubleFactory2D.sparse.make(N , N); for (MulticastDemand d : layer.multicastDemands) for (Node egressNode : d.egressNodes) delta_nn.set (d.ingressNode.index , egressNode.index , delta_nn.get (d.ingressNode.index , egressNode.index) + 1); return delta_nn; } /** * <p>Returns the node-demand incidence matrix (a <i>N</i>x<i>D</i> in which an element <i>&delta;<sub>nd</sub></i> equals 1 if <i>n</i> is the ingress node of <i>d</i>, * -1 if <i>n</i> is the egress node of <i>d</i> and 0 otherwise). * If no layer is provided, the default layer is assumed.</p> * @param optionalLayerParameter Network layer * @return The node-demand incidence matrix */ public DoubleMatrix2D getMatrixNodeDemandIncidence (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); int N = nodes.size (); int D = layer.demands.size (); DoubleMatrix2D delta_nd = DoubleFactory2D.sparse.make(N , D); for (Demand d : layer.demands) { delta_nd.set (d.ingressNode.index , d.index , 1); delta_nd.set (d.egressNode.index , d.index , -1); } return delta_nd; } /** * <p>Returns the node-multicast demand incidence matrix (a <i>N</i>x<i>D</i> in which an element <i>&delta;<sub>nd</sub></i> equals 1 if <i>n</i> is the ingress node of <i>d</i>, * -1 if <i>n</i> is an egress node of <i>d</i> and 0 otherwise). * If no layer is provided, the default layer is assumed.</p> * @param optionalLayerParameter Network layer * @return The node-multicast demand incidence matrix */ public DoubleMatrix2D getMatrixNodeMulticastDemandIncidence (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); int N = nodes.size (); int MD = layer.multicastDemands.size (); DoubleMatrix2D delta_nd = DoubleFactory2D.sparse.make(N , MD); for (MulticastDemand d : layer.multicastDemands) { delta_nd.set (d.ingressNode.index , d.index , 1); for (Node egressNode : d.egressNodes) delta_nd.set (egressNode.index , d.index , -1); } return delta_nd; } /** * <p>Returns the node-demand incoming incidence matrix (a <i>N</i>x<i>D</i> matrix in which element <i>&delta;<sub>nd</sub></i> equals 1 if demand <i>d</i> is terminated * in node <i>n</i> and 0 otherwise. If no layer is provided, the default layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return The node-demand incoming incidence matrix */ public DoubleMatrix2D getMatrixNodeDemandIncomingIncidence (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); int N = nodes.size (); int D = layer.demands.size (); DoubleMatrix2D delta_nd = DoubleFactory2D.sparse.make(N , D); for (Demand d : layer.demands) delta_nd.set (d.egressNode.index , d.index , 1); return delta_nd; } /** * <p>Returns the node-multicast demand incoming incidence matrix (a <i>N</i>x<i>D</i> matrix in which element <i>&delta;<sub>nd</sub></i> equals 1 if multicast demand <i>d</i> is terminated * in node <i>n</i> and 0 otherwise. If no layer is provided, the default layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return The node-multicast demand incoming incidence matrix */ public DoubleMatrix2D getMatrixNodeMulticastDemandIncomingIncidence (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); int N = nodes.size (); int MD = layer.multicastDemands.size (); DoubleMatrix2D delta_nd = DoubleFactory2D.sparse.make(N , MD); for (MulticastDemand d : layer.multicastDemands) for (Node egressNode : d.egressNodes) delta_nd.set (egressNode.index , d.index , 1); return delta_nd; } /** * <p>Returns the node-demand outgoing incidence matrix (a <i>N</i>x<i>D</i> matrix in which element <i>&delta;<sub>nd</sub></i> equals 1 if demand <i>d</i> is initiated * in node <i>n</i> and 0 otherwise. If no layer is provided, the default layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return The node-demand outgoing incidence matrix */ public DoubleMatrix2D getMatrixNodeDemandOutgoingIncidence (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); int N = nodes.size (); int D = layer.demands.size (); DoubleMatrix2D delta_nd = DoubleFactory2D.sparse.make(N , D); for (Demand d : layer.demands) delta_nd.set (d.ingressNode.index , d.index , 1); return delta_nd; } /** * <p>Returns the node-multicast demand outgoing incidence matrix (a <i>N</i>x<i>D</i> matrix in which element <i>&delta;<sub>nd</sub></i> equals 1 if demand <i>d</i> is initiated * in node <i>n</i> and 0 otherwise. If no layer is provided, the default layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return The node-multicast demand outgoing incidence matrix */ public DoubleMatrix2D getMatrixNodeMulticastDemandOutgoingIncidence (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); int N = nodes.size (); int MD = layer.multicastDemands.size (); DoubleMatrix2D delta_nd = DoubleFactory2D.sparse.make(N , MD); for (MulticastDemand d : layer.multicastDemands) delta_nd.set (d.ingressNode.index , d.index , 1); return delta_nd; } /** * <p>Returns the node-link adjacency matrix (a <i>N</i>x<i>N</i> matrix in which element <i>&delta;<sub>ij</sub></i> is equals to the number of links from node <i>i</i> to node <i>j</i>. * If no layer is provided, the default layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return The node-link adjacency matrix */ public DoubleMatrix2D getMatrixNodeLinkAdjacency (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); int N = nodes.size (); DoubleMatrix2D delta_nn = DoubleFactory2D.sparse.make(N , N); for (Link e : layer.links) delta_nn.set (e.originNode.index , e.destinationNode.index , delta_nn.get (e.originNode.index , e.destinationNode.index) + 1); return delta_nn; } /** * <p>Returns the node-link incidence matrix (a <i>N</i>x<i>E</i> matrix in which element <i>&delta;<sub>ne</sub></i> equals 1 if link <i>e</i> is initiated in node <i>n</i>, -1 * if link <i>e</i> ends in node <i>n</i>, and 0 otherwise. If no layer is provided, the default layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return The node-link incidence matrix */ public DoubleMatrix2D getMatrixNodeLinkIncidence (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); int N = nodes.size (); int E = layer.links.size (); DoubleMatrix2D delta_ne = DoubleFactory2D.sparse.make(N , E); for (Link e : layer.links) { delta_ne.set (e.originNode.index , e.index , 1); delta_ne.set (e.destinationNode.index , e.index , -1); } return delta_ne; } /** * <p>Returns the node-link incoming incidence matrix (a <i>N</i>x<i>E</i> matrix in which element <i>&delta;<sub>ne</sub></i> equals 1 if link <i>e</i> is terminated in node <i>n</i>, * and 0 otherwise. If no layer is provided, the default layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return The node-link incoming incidence matrix */ public DoubleMatrix2D getMatrixNodeLinkIncomingIncidence (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); int N = nodes.size (); int E = layer.links.size (); DoubleMatrix2D delta_ne = DoubleFactory2D.sparse.make(N , E); for (Link e : layer.links) delta_ne.set (e.destinationNode.index , e.index , 1); return delta_ne; } /** * <p>Returns the node-link outgoing incidence matrix (a <i>N</i>x<i>E</i> matrix in which element <i>&delta;<sub>ne</sub></i> equals 1 if link <i>e</i> is initiated in node <i>n</i>, * and 0 otherwise. If no layer is provided, the default layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return The node-link outgoing incidence matrix */ public DoubleMatrix2D getMatrixNodeLinkOutgoingIncidence (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); int N = nodes.size (); int E = layer.links.size (); DoubleMatrix2D delta_ne = DoubleFactory2D.sparse.make(N , E); for (Link e : layer.links) delta_ne.set (e.originNode.index , e.index , 1); return delta_ne; } /** * <p>Returns the multicast demand with the given index in the given layer. If no layer is provided, default layer is assumed.</p> * @param index Multicast demand index * @param optionalLayerParameter Network layer (optional) * @return The multicast demand ({@code null} if it does not exist, or index is lower than 0, or greater the number of elements minus one). */ public MulticastDemand getMulticastDemand (int index , NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); if ((index < 0) || (index > layer.multicastDemands.size () -1)) return null; else return layer.multicastDemands.get(index); } /** * <p>Returns the multicast demand with the given unique identifier.</p> * @param uid Multicast demand unique id * @return The multicast demand, or {@code null} if it does not exist */ public MulticastDemand getMulticastDemandFromId (long uid) { checkAttachedToNetPlanObject(); return cache_id2MulticastDemandMap.get(uid); } /** * <p>Returns the array of multicast demand ids for the given layer (i-th position, corresponds to index i). If no layer is provided, the default layer is assumed.</p> * @param optionalLayerParameter network layer (optional) * @return The {@code ArrayList} of multicast demand unique ids */ public ArrayList<Long> getMulticastDemandIds (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); ArrayList<Long> res = new ArrayList<Long> (); for (MulticastDemand e : layer.multicastDemands) res.add (e.id); return res; } /** * <p>Returns the list of multicast demands for the given layer (i-th position, corresponds to multicast demand with index i). If no layer is provided, the default layer is used</p> * @param optionalLayerParameter Network layer (optional) * @return The list of multicast demands */ public List<MulticastDemand> getMulticastDemands (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); return (List<MulticastDemand>) Collections.unmodifiableList(layer.multicastDemands); } /** * <p>Returns the multicast demands that have blocked traffic in the given layer. If no layer is provided, the default layer is assumed</p> * @param optionalLayerParameter Network layer (optional) * @return The multicast demands with blocked traffic */ public List<MulticastDemand> getMulticastDemandsBlocked (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); List<MulticastDemand> res = new LinkedList<MulticastDemand> (); for (MulticastDemand d : layer.multicastDemands) if (d.isBlocked()) res.add (d); return res; } /** * <p>Returns the set of multicas demands that are coupled.</p> * @param optionalLayerParameter Network layer (optional) * @return the {@code Set} of multicast demands */ public Set<MulticastDemand> getMulticastDemandsCoupled (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); Set<MulticastDemand> res = new HashSet<MulticastDemand> (); for (MulticastDemand demand : layer.multicastDemands) if (demand.coupledUpperLayerLinks != null) res.add (demand); return res; } /** * <p>Returns the total blocked traffic, summing up for all the multicast demands, in the given layer. If no layer is provided, the default layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return The total blocked traffic for all multicast demands */ public double getMulticastDemandTotalBlockedTraffic(NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); double accum = 0; for (MulticastDemand d : layer.multicastDemands) accum += Math.max(0 , d.offeredTraffic - d.carriedTraffic); return accum; } /** * <p>Returns the total carried traffic, summing up for all the multicast demands, in the given layer. If no layer is provided, the default layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return The total carried traffic for all multicast demands */ public double getMulticastDemandTotalCarriedTraffic(NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); double accum = 0; for (MulticastDemand d : layer.multicastDemands) accum += d.carriedTraffic; return accum; } /** * <p>Returns the total offered traffic, summing up for all the multicast demands, in the given layer. If no layer is provided, the default layer is assumed</p> * @param optionalLayerParameter Network layer (optional) * @return the total offered traffic for all multicast demands */ public double getMulticastDemandTotalOfferedTraffic(NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); double accum = 0; for (MulticastDemand d : layer.multicastDemands) accum += d.offeredTraffic; return accum; } /** * <p>Returns the multicast tree with the given index in the given layer. if no layer is provided, default layer is assumed.</p> * @param index Multicast tree index * @param optionalLayerParameter Network layer (optional) * @return The multicast tree ({@code null}if it does not exist, index islower than 0, or greater than the number of elements minus one) */ public MulticastTree getMulticastTree (int index , NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); if ((index < 0) || (index > layer.multicastTrees.size () -1)) return null; else return layer.multicastTrees.get(index); } /** * <p>Returns the multicast tree with the given unique identifier.</p> * @param uid Multicast tree unique id * @return The multicast tree ({@code null} if it does not exist */ public MulticastTree getMulticastTreeFromId (long uid) { checkAttachedToNetPlanObject(); return cache_id2MulticastTreeMap.get(uid); } /** * <p>Returns the array of multicast tree ids for the given layer (i-th position, corresponds to index i). If no layer is provided, the default layer is assumed.</p> * @param optionalLayerParameter network layer (optional) * @return the {@code ArrayList} of multicast trees unique ids */ public ArrayList<Long> getMulticastTreeIds (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); ArrayList<Long> res = new ArrayList<Long> (); for (MulticastTree e : layer.multicastTrees) res.add (e.id); return res; } /** * <p>Returns the array of multicast trees for the given layer (i-th position, corresponds to index i). If no layer is provided, the default layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return The {@code List} of multicast trees */ public List<MulticastTree> getMulticastTrees (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); return (List<MulticastTree>) Collections.unmodifiableList(layer.multicastTrees); } /** * <p>Returns the set of multicast trees that are down (i.e. that traverse a link or node that has failed).</p> * @param optionalLayerParameter Network layer (optional) * @return the {@code Set} of multicast trees that are down */ public Set<MulticastTree> getMulticastTreesDown (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); Set<MulticastTree> res = new HashSet<MulticastTree> (); for (MulticastTree r : layer.multicastTrees) if (r.isDown()) res.add (r); return res; } /** * <p>Returns the description associated to the {@code NetPlan} object</p> * @return The network description as a {@code String} */ public String getNetworkDescription () { return this.networkDescription; } /** * <p>Return the network element with the given unique id.</p> * @param id Unique id * @return The network element ({@code null} if it does not exist) * @see com.net2plan.interfaces.networkDesign.NetworkElement */ public NetworkElement getNetworkElement (long id) { NetworkElement e; e = cache_id2DemandMap.get(id); if (e != null) return e; e = cache_id2LayerMap.get(id); if (e != null) return e; e = cache_id2LinkMap.get(id); if (e != null) return e; e = cache_id2MulticastDemandMap.get(id); if (e != null) return e; e = cache_id2MulticastTreeMap.get(id); if (e != null) return e; e = cache_id2NodeMap.get(id); if (e != null) return e; e = cache_id2ProtectionSegmentMap.get(id); if (e != null) return e; e = cache_id2RouteMap.get(id); if (e != null) return e; e = cache_id2srgMap.get(id); if (e != null) return e; return null; } /** * <p>Returns the first network element among the ones passed as input parameters, that has the given key-value as attribute. </p> * * @param listOfElements Lit of network elements * @param attribute Attribute name * @param value Attribute value * @return First network element encountered with the given key-value ({@code null}if no network element matches or the input {@code null} or empty * @see com.net2plan.interfaces.networkDesign.NetworkElement */ public static NetworkElement getNetworkElementByAttribute(Collection<? extends NetworkElement> listOfElements , String attribute, String value) { if (listOfElements == null) return null; for (NetworkElement e : listOfElements) { String atValue = e.attributes.get (attribute); if (atValue != null) if (atValue.equals(value)) return e; } return null; } /** * Returns the next identifier for a new network element (layer, node, link, demand...) * * @return Next identifier */ public long getNetworkElementNextId() { final long elementId = nextElementId.longValue(); if (elementId < 0) throw new Net2PlanException(TEMPLATE_NO_MORE_NETWORK_ELEMENTS_ALLOWED); return elementId; } /** * <p>Returns all the network elements among the ones passed as input parameters, that have the given key-value as attribute. * Returns an empty list if no network element mathces this, the input list of elements is null or empty</p> * @param listOfElements List of network elements * @param attribute Attribute name * @param value Attribute value * @return List of all network elements with the attribute key-value */ public static Collection<? extends NetworkElement> getNetworkElementsByAttribute(Collection <? extends NetworkElement> listOfElements , String attribute, String value) { List<NetworkElement> res = new LinkedList<NetworkElement> (); if (listOfElements == null) return res; for (NetworkElement e : listOfElements) { String atValue = e.attributes.get (attribute); if (atValue != null) if (atValue.equals(value)) res.add (e); } return res; } /** * <p>Returns the network layer with the given unique identifier.</p> * @param uid Network layer unique id * @return The network layer with the given id ({@code null} if it does not exist) */ public NetworkLayer getNetworkLayerFromId (long uid) { return cache_id2LayerMap.get(uid); } /** * <p> Return the default network layer.</p> * @return The default network layer */ public NetworkLayer getNetworkLayerDefault () { return defaultLayer; } /** * <p>Returns the array of layer ids (i-th position, corresponds to index i).</p> * @return The {@code ArraList} of network layers */ public ArrayList<Long> getNetworkLayerIds () { ArrayList<Long> res = new ArrayList<Long> (); for (NetworkLayer n : layers) res.add (n.id); return res; } /** * <p>Returns network layers in bottom-up order, that is, starting from the * lower layers to the upper layers following coupling relationships. For layers * at the same hierarchical level, no order is guaranteed.</p> * * @return The {@code Set} of network layers in topological order * @since 0.3.0 */ public Set<NetworkLayer> getNetworkLayerInTopologicalOrder() { Set<NetworkLayer> layers_topologicalSort = new LinkedHashSet<NetworkLayer>(); Iterator<NetworkLayer> it = interLayerCoupling.iterator(); while(it.hasNext()) layers_topologicalSort.add(it.next()); return layers_topologicalSort; } /** * <p>Returns the array of network layers (i-th position, corresponds to index i).</p> * @return The {@code List} of network layers */ public List<NetworkLayer> getNetworkLayers () { return (List<NetworkLayer>) Collections.unmodifiableList(layers); } /** * <p>Returns the name associated to the netPlan object</p> * @return The network name */ public String getNetworkName () { return this.networkName; } /** * <p>Returns the node with the given unique identifier.</p> * @param uid Node unique id * @return The node with the given id ({@code null} if it does not exist) */ public Node getNodeFromId (long uid) { return cache_id2NodeMap.get(uid); } /** * <p>Returns the first node with the given name.</p> * @param name Node name * @return The first node with the given name ({@code null} if it does not exist) */ public Node getNodeByName(String name) { for (Node n : nodes) if (n.name.equals (name)) return n; return null; } /** * <p>Returns the array of node ids (i-th position, corresponds to index i)</p> * @return The {@code ArrayList} of nodes */ public ArrayList<Long> getNodeIds () { ArrayList<Long> res = new ArrayList<Long> (); for (Node n : nodes) res.add (n.id); return res; } /** * <p>Gets the set of demands at the given layer from the input nodes (if {@code returnDemandsInBothDirections} is {@code true}, also the reversed links are included). If no layer is provided, the default layer is assumed.</p> * @param originNode Origin node * @param destinationNode Destination node * @param returnDemandsInBothDirections Assume both directions * @param optionalLayerParameter network layer (optional) * @return the {@code Set} of demands that have the origin and destination for the given input */ public Set<Demand> getNodePairDemands (Node originNode, Node destinationNode , boolean returnDemandsInBothDirections , NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); checkInThisNetPlan(originNode); checkInThisNetPlan(destinationNode); Set<Demand> res = new HashSet<Demand> (); for (Demand e : originNode.cache_nodeOutgoingDemands) if (e.layer.equals (layer) && e.egressNode.equals (destinationNode)) res.add (e); if (returnDemandsInBothDirections) for (Demand e : originNode.cache_nodeIncomingDemands) if (e.layer.equals (layer) && e.ingressNode.equals (destinationNode)) res.add (e); return res; } /** * <p>Gets the Euclidean distance for a node pair.</p> * @param originNode Origin node * @param destinationNode Destination node * @return The Euclidean distance between a node pair */ public double getNodePairEuclideanDistance(Node originNode, Node destinationNode) { checkInThisNetPlan(originNode); checkInThisNetPlan(destinationNode); return Math.sqrt (Math.pow (originNode.nodeXYPositionMap.getX() - destinationNode.nodeXYPositionMap.getX(), 2) + Math.pow (originNode.nodeXYPositionMap.getY() - destinationNode.nodeXYPositionMap.getY() , 2)); } /** * <p>Gets the Haversine distance for a node pair.</p> * @param originNode Origin node * @param destinationNode Destination node * @return The Harvesine distance between a node pair * @see <a href="http://www.movable-type.co.uk/scripts/latlong.html">Calculate distance, bearing and more between Latitude/Longitude points</a> */ public double getNodePairHaversineDistanceInKm(Node originNode, Node destinationNode) { checkInThisNetPlan(originNode); checkInThisNetPlan(destinationNode); return GraphUtils.computeHaversineDistanceInKm(originNode.nodeXYPositionMap, destinationNode.nodeXYPositionMap); } /** * <p>Gets the set of links at the given layer from the given nodes (if {@code returnLinksInBothDirections} is {@code true}, also the reversed links are included). If no layer is provided, the default layer is assumed.</p> * @param originNode Origin node * @param destinationNode Destination node * @param returnLinksInBothDirections Include links in both direction * @param optionalLayerParameter Network layer (optional) * @return the {@code Set} of links between a pair of nodes */ public Set<Link> getNodePairLinks (Node originNode, Node destinationNode , boolean returnLinksInBothDirections , NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); checkInThisNetPlan(originNode); checkInThisNetPlan(destinationNode); Set<Link> res = new HashSet<Link> (); for (Link e : originNode.cache_nodeOutgoingLinks) if (e.layer.equals (layer) && e.destinationNode.equals (destinationNode)) res.add (e); if (returnLinksInBothDirections) for (Link e : originNode.cache_nodeIncomingLinks) if (e.layer.equals (layer) && e.originNode.equals (destinationNode)) res.add (e); return res; } /** * <p>Gets the set of routes at the given layer from the given nodes (if {@code returnRoutesInBothDirections} is {@code true}, also the reversed routes are included). * If no layer is provided, the default layer is assumed.</p> * @param originNode Origin node * @param destinationNode Destination node * @param returnRoutesInBothDirections Include routes in both directions * @param optionalLayerParameter Network layer (optional) * @return The {@code Set} of routes between a pair of nodes */ public Set<Route> getNodePairRoutes (Node originNode, Node destinationNode , boolean returnRoutesInBothDirections , NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); checkInThisNetPlan(originNode); checkInThisNetPlan(destinationNode); Set<Route> res = new HashSet<Route> (); for (Demand e : originNode.cache_nodeOutgoingDemands) if (e.layer.equals (layer) && e.egressNode.equals (destinationNode)) res.addAll (e.cache_routes); if (returnRoutesInBothDirections) for (Demand e : originNode.cache_nodeIncomingDemands) if (e.layer.equals (layer) && e.ingressNode.equals (destinationNode)) res.addAll (e.cache_routes); return res; } /** * <p>Return the set of protection segments at the given layer for the given nodes (if {@code returnSegmentsInBothDirections} is {@code true}, also the reversed protection segments are included) * If no layer is provided, default layer is assumed.</p> * @param originNode Origin node * @param destinationNode Destination node * @param returnSegmentsInBothDirections Include protection segments in both directions * @param optionalLayerParameter Network layer (optional) * @return The {@code Set} of protection segments between a pair of nodes */ public Set<ProtectionSegment> getNodePairProtectionSegments (Node originNode, Node destinationNode , boolean returnSegmentsInBothDirections , NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); checkInThisNetPlan(originNode); checkInThisNetPlan(destinationNode); Set<ProtectionSegment> res = new HashSet<ProtectionSegment> (); for (ProtectionSegment s : originNode.cache_nodeAssociatedSegments) { if ((s.originNode == originNode) && (s.destinationNode == destinationNode)) res.add (s); if (returnSegmentsInBothDirections) if ((s.originNode == destinationNode) && (s.destinationNode == originNode)) res.add (s); } return res; } /** * <p>Returns the array of nodes (i-th position, corresponds to index i).</p> * @return The {@code List} of nodes */ public List<Node> getNodes () { return (List<Node>) Collections.unmodifiableList(nodes); } // /** // * Computes the shortest path between the end nodes, using the given link costs (if null, the shortest path is in number of hops), for the // * given layer. If no layer is provided, the default layer is assumed. An infinite cost makes the link unusable. Returns null if no path exists // */ // public List<Link> computeShortestPath (Node origin , Node destination , DoubleMatrix1D linkCosts , NetworkLayer ... optionalLayerParameter) // { // checkIsModifiable(); // if (optionalLayerParameter.length >= 2) throw new Net2PlanException ("None or one layer parameter can be supplied"); // NetworkLayer layer = (optionalLayerParameter.length == 1)? optionalLayerParameter [0] : defaultLayer; // if (linkCosts == null) linkCosts = DoubleFactory1D.dense.make (layer.links.size() , 1.0); // if (linkCosts.size () != layer.links.size()) throw new Net2PlanException ("Wrong cost vector"); // final Map<Long,Pair<Long,Long>> netPlanLinkMap = getLinkIdMap (layer.links); // Map<Long,Double> linkCost = new HashMap<Long,Double> (); // for (Link link : layer.links) // linkCost.put(link.id, linkCosts.get(link.index)); // final List<Long> seqLinkIds = GraphUtils.getShortestPath(netPlanLinkMap, origin.id , destination.id , linkCost); // List<Link> seqLinks = new LinkedList<Link> (); for (long id : seqLinkIds) seqLinks.add (cache_id2LinkMap.get(id)); // return seqLinks; // } // /** * <p>Returns the set of nodes that are down (iteration order corresponds to ascending order of indexes).</p> * @return The {@code Set} of nodes that are down */ public Set<Node> getNodesDown () { return Collections.unmodifiableSet(cache_nodesDown); } /** * <p>Returns the set of nodes that are up (iteration order correspond to ascending order of indexes).</p> * @return The {@code Set} of nodes that are up */ public Set<Node> getNodesUp () { Set<Node> res = new HashSet<Node> (nodes); res.removeAll(cache_nodesDown); return res; } /** * <p>Returns the number of demands at the given layer. If no layer is provided, the default layer is assumed.</p> * @param optionalLayerParameter network layer (optional) * @return The number of demands */ public int getNumberOfDemands (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); return layer.demands.size(); } /** * <p>Returns the number of non-zero forwarding rules at the given layer. If no layer is provided, the default layer is assumed.</p> * @param optionalLayerParameter network layer (optional) * @return The number of non-zero forwarding rules */ public int getNumberOfForwardingRules (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); layer.checkRoutingType(RoutingType.HOP_BY_HOP_ROUTING); IntArrayList ds = new IntArrayList (); IntArrayList es = new IntArrayList (); DoubleArrayList vals = new DoubleArrayList (); layer.forwardingRules_f_de.getNonZeros(ds , es , vals); return ds.size (); } /** * <p>Returns the number of layers defined.</p> * @return The number of layers */ public int getNumberOfLayers () { return layers.size(); } /** * <p>Returns the number of links at the given layer. If no layer is provided, the default layer is assumed.</p> * @param optionalLayerParameter network layer * @return The number of links */ public int getNumberOfLinks (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); return layer.links.size(); } /** * <p>Returns the number of multicast demands at the given layer. If no layer is provided, the default layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return The number of multicast demands */ public int getNumberOfMulticastDemands (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); return layer.multicastDemands.size(); } /** * <p>Returns the number of multicast trees at the given layer. If no layer is provided, the default layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return The number of multicast trees */ public int getNumberOfMulticastTrees (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); return layer.multicastTrees.size(); } /** * <p>Returns the number of network nodes,</p> * @return The number of nodes */ public int getNumberOfNodes () { return nodes.size(); } /** * <p>Returns the number of node pairs.</p> * @return The number of node pairs */ public int getNumberOfNodePairs () { return nodes.size() * (nodes.size()-1); } /** * <p>Returns the number of protection segments at the given layer. If no layer is provided, the default layer is assumed.</p> * @param optionalLayerParameter network layer (optional) * @return The number of protection segments */ public int getNumberOfProtectionSegments (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); layer.checkRoutingType(RoutingType.SOURCE_ROUTING); return layer.protectionSegments.size(); } /** * <p>Returns the number of routes at the given layer. If no layer is provided, the default layer is assumed.</p> * @param optionalLayerParameter network layer (optional) * @return The number of routes */ public int getNumberOfRoutes (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); layer.checkRoutingType(RoutingType.SOURCE_ROUTING); return layer.routes.size(); } /** * <p>Returns the number of shared risk groups (SRGs) defined</p> * @return The number of defined shared risk groups */ public int getNumberOfSRGs () { return srgs.size(); } /** * <p>Returns the protection segment with the given index in the given layer. if no layer is provided, default layer is assumed.</p> * @param index Protection segment index * @param optionalLayerParameter network layer (optional) * @return The protection segment with the given index ({@code null} if it does not exist, index is lesser thatn zero or greater that the number of elements minus one) */ public ProtectionSegment getProtectionSegment (int index , NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); layer.checkRoutingType(RoutingType.SOURCE_ROUTING); if ((index < 0) || (index > layer.protectionSegments.size () -1)) return null; else return layer.protectionSegments.get(index); } /** * <p>Returns the protection segment with the given unique identifier.</p> * @param uid Protection segment unique id * @return The protection segment with the given id ({@code null} if it does not exist) */ public ProtectionSegment getProtectionSegmentFromId (long uid) { return cache_id2ProtectionSegmentMap.get(uid); } /** * <p>Returns the array of protection segment ids for the given layer (i-th position, corresponds to index i). If no layer is provided, the default layer is assumed</p> * @param optionalLayerParameter Network layer (optional) * @return The {@code ArrayList} of protection segments unique ids */ public ArrayList<Long> getProtectionSegmentIds (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); layer.checkRoutingType(RoutingType.SOURCE_ROUTING); ArrayList<Long> res = new ArrayList<Long> (); for (ProtectionSegment e : layer.protectionSegments) res.add (e.id); return res; } /** * <p>Returns the array of protection segmets for the given layer (i-th position, corresponds to index i). If no layer is provided, the default layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return The {@code List} of protection segments */ public List<ProtectionSegment> getProtectionSegments (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); layer.checkRoutingType(RoutingType.SOURCE_ROUTING); return (List<ProtectionSegment>) Collections.unmodifiableList(layer.protectionSegments); } /** * <p>Returns the set of protection segments that are down (traverse a link or node that is failed). If no layer is provided, default layer is assumed.</p> * @param optionalLayerParameter network layer (optional) * @return The {@code Set} of protection segments that are down */ public Set<ProtectionSegment> getProtectionSegmentsDown (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); layer.checkRoutingType(RoutingType.SOURCE_ROUTING); Set<ProtectionSegment> res = new HashSet<ProtectionSegment> (); for (ProtectionSegment r : layer.protectionSegments) if (r.isDown()) res.add (r); return res; } /** * <p>Returns the route with the given index in the given layer. if no layer is provided, default layer is assumed</p> * @param index Route index * @param optionalLayerParameter network layer (optional) * @return The route with the given index ({@code null} if it does not exist, index is lesser than zero or greater than the number of elements minus one) */ public Route getRoute (int index , NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); layer.checkRoutingType(RoutingType.SOURCE_ROUTING); layer.checkRoutingType(RoutingType.SOURCE_ROUTING); if ((index < 0) || (index > layer.routes.size () -1)) return null; else return layer.routes.get(index); } /** * <p>Returns the route with the given unique identifier.</p> * @param uid Rute unique id * @return The route with the given id ({@code null} if it does not exist) */ public Route getRouteFromId (long uid) { return cache_id2RouteMap.get(uid); } /** * <p>Returns the array of route ids for the given layer (i-th position, corresponds to index i). If no layer is provided, the default layer is assumed</p> * @param optionalLayerParameter Network layer (optional) * @return The {@code ArrayList} of route ides */ public ArrayList<Long> getRouteIds (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); layer.checkRoutingType(RoutingType.SOURCE_ROUTING); ArrayList<Long> res = new ArrayList<Long> (); for (Route e : layer.routes) res.add (e.id); return res; } /** * <p>Returns the array of route ids for the given layer (i-th position, corresponds to index i). If no layer is provided, the default layer is assumed</p> * @param optionalLayerParameter network layer (optional) * @return the {@code List} of routes */ public List<Route> getRoutes (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); layer.checkRoutingType(RoutingType.SOURCE_ROUTING); return (List<Route>) Collections.unmodifiableList(layer.routes); } /** * <p>Returns the set of routes that are down (traverse a link or node that is failed). If no layer is provided, default layer is assumed</p> * @param optionalLayerParameter network layer (optional) * @return The {@code Set} of routes that are down */ public Set<Route> getRoutesDown (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); layer.checkRoutingType(RoutingType.SOURCE_ROUTING); Set<Route> res = new HashSet<Route> (); for (Route r : layer.routes) if (r.isDown()) res.add (r); return res; } /** * <p>Returns the routing type of the given layer. If no layer is provided, the default layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return The routing type of the given layer * @see com.net2plan.utils.Constants.RoutingType */ public RoutingType getRoutingType(NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); return layer.routingType; } /** * <p>Returns the shared risk group with the given unique identifier.</p> * @param uid SRG unique id * @return The shared risk group with the given unique id (@code null if it does not exist) */ public SharedRiskGroup getSRGFromId (long uid) { return cache_id2srgMap.get(uid); } /** * <p>Returns the shared risk group with the given index</p> * @param index SRG index * @return The shared risk group with the given index ({@code null} if it does not exist, index is lesser than zero or greater than the number of elements minus one) */ public SharedRiskGroup getSRG (int index) { if ((index < 0) || (index > srgs.size () -1)) return null; else return srgs.get(index); } /** * <p>Returns the array of shared risk group ids (i-th position, corresponds to index i)</p> * @return The {@code ArrayList} of Shared Risk Groups unique ids */ public ArrayList<Long> getSRGIds () { ArrayList<Long> res = new ArrayList<Long> (); for (SharedRiskGroup n : srgs) res.add (n.id); return res; } /** * <p>Returns the array of shared risk groups (i-th position, corresponds to index i).</p> * @return The {@code List} of Shared Risk Groups */ public List<SharedRiskGroup> getSRGs () { return (List<SharedRiskGroup>) Collections.unmodifiableList(srgs); } /** * <p>Returns a vector with the carried traffic per demand, at the given layer. i-th vector corresponds to i-th index of the element. If no layer is provided, the defaulf layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return The vector of carried traffic per demand */ public DoubleMatrix1D getVectorDemandCarriedTraffic(NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); DoubleMatrix1D res = DoubleFactory1D.dense.make(layer.demands.size()); for (Demand e : layer.demands) res.set(e.index, e.carriedTraffic); return res; } /** * <p>Retuns a vector with the values of all given network elements for the given attribute key.</p> * <p><b>Important:</b> Each element must have the attribute set and value must be of type {@code double}</p> * @param collection Network elements * @param attributeKey Attribute name * @return The vector of values for the given attribute name for all network elements */ public DoubleMatrix1D getVectorAttributeValues (Collection<? extends NetworkElement> collection , String attributeKey) { DoubleMatrix1D res = DoubleFactory1D.dense.make (collection.size()); int counter = 0; for (NetworkElement e : collection) if (e.getAttribute(attributeKey) != null) res.set (counter ++ , Double.parseDouble(e.getAttribute(attributeKey))); else throw new Net2PlanException ("The element does not contain the attribute " + attributeKey); return res; } /** * <p>Sets the given attributes values to all the given network elements.</p> * @param collection Network elements * @param attributeKey Attribute name * @param values Attribute values (must have the same size as {@code collection} */ public void setVectorAttributeValues (Collection<? extends NetworkElement> collection , String attributeKey , DoubleMatrix1D values) { if (values.size () != collection.size()) throw new Net2PlanException ("The number of elements in the collection and the number of values to assign must be the same"); int counter = 0; for (NetworkElement e : collection) e.setAttribute(attributeKey , Double.toString(values.get (counter ++))); } /** * <p>Returns the vector with the worst propagation time (in ms) per demand at the given layer. i-th vector corresponds to i-th index of the element. If no layer is provided, default layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return The vector with the worst propagation time in ms per demand */ public DoubleMatrix1D getVectorDemandWorseCasePropagationTimeInMs (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); DoubleMatrix1D res = DoubleFactory1D.dense.make(layer.demands.size()); for (Demand e : layer.demands) res.set(e.index, e.getWorseCasePropagationTimeInMs()); return res; } /** * <p>Returns the vector with the worst propagation time (in ms) per multicast demand at the given layer. i-th vector corresponds to i-th index of the element.. If no layer is provided, default layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return The vector with the worst propagation time in ms per multicast demand */ public DoubleMatrix1D getVectorMulticastDemandWorseCasePropagationTimeInMs (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); DoubleMatrix1D res = DoubleFactory1D.dense.make(layer.demands.size()); for (MulticastDemand e : layer.multicastDemands) res.set(e.index, e.getWorseCasePropagationTimeInMs()); return res; } /** * <p>Returns a vector where each index equals the demand index and the value is 1 if said demand traverses oversubscrined links, 0 otherwise. If no layer is provided, default layer is assumed.</p> * @param optionalLayerParameter network layer (optional) * @return The vector indicating if each demand traverses oversubscribed links */ public DoubleMatrix1D getVectorDemandTraversesOversubscribedLink (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); DoubleMatrix1D res = DoubleFactory1D.dense.make(layer.demands.size()); for (Demand e : layer.demands) res.set(e.index, e.isTraversingOversubscribedLinks()? 1 : 0); return res; } /** * <p>Returns the vector indicating wheter a multicast demnd traverses (1) or not (0) oversubscribes links at the given layer. * i-th vector corresponds to i-th index of the element. If no layer is provided, the defaulf layer is assumed </p> * @param optionalLayerParameter network layer (optional) * @return The vector indicating if each multicast demand traverses oversubscribed links */ public DoubleMatrix1D getVectorMulticastDemandTraversesOversubscribedLink (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); DoubleMatrix1D res = DoubleFactory1D.dense.make(layer.multicastDemands.size()); for (MulticastDemand e : layer.multicastDemands) res.set(e.index, e.isTraversingOversubscribedLinks()? 1 : 0); return res; } /** * <p>Returns a vector with the availability per Shared Risk Group (SRG).</p> * @return The vector with the availability per Shared Risk group */ public DoubleMatrix1D getVectorSRGAvailability () { DoubleMatrix1D res = DoubleFactory1D.dense.make(srgs.size()); for (SharedRiskGroup e : srgs) res.set(e.index, e.getAvailability()); return res; } /** * <p>Returns a vector with the offered traffic per demand, at the given layer. i-th vector corresponds to i-th index of the element. If no layer is provided, the defaulf layer is assumed.</p> * @param optionalLayerParameter network layer (optional) * @return The vector with the offered traffic per demand */ public DoubleMatrix1D getVectorDemandOfferedTraffic(NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); DoubleMatrix1D res = DoubleFactory1D.dense.make(layer.demands.size()); for (Demand e : layer.demands) res.set(e.index, e.offeredTraffic); return res; } /** * <p>Returns a vector with the blocked traffic per demand, at the given layer. i-th vector corresponds to i-th index of the element. If no layer is provided, the defaulf layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return The vector with the blocked traffic per demand */ public DoubleMatrix1D getVectorDemandBlockedTraffic(NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); DoubleMatrix1D res = DoubleFactory1D.dense.make(layer.demands.size()); for (Demand e : layer.demands) res.set(e.index, Math.max (0 , e.offeredTraffic - e.carriedTraffic)); return res; } /** * <p>Returns a vector with the capacity per link, at the given layer. i-th vector corresponds to i-th index of the element. If no layer is provided, the defaulf layer is assumed.</p> * @param optionalLayerParameter network layer (optional) * @return The vector with the capacity per link */ public DoubleMatrix1D getVectorLinkCapacity(NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); DoubleMatrix1D res = DoubleFactory1D.dense.make(layer.links.size()); for (Link e : layer.links) res.set(e.index, e.capacity); return res; } /** * <p>Returns a vector with the capacity per link, at the given layer. i-th vector corresponds to i-th index of the element. If no layer is provided, the defaulf layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return The vector with the spare capacity per link */ public DoubleMatrix1D getVectorLinkSpareCapacity(NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); DoubleMatrix1D res = DoubleFactory1D.dense.make(layer.links.size()); for (Link e : layer.links) res.set(e.index, Math.max(0 , e.capacity - e.carriedTrafficSummingRoutesAndCarriedTrafficByProtectionSegments)); return res; } /** * <p>Returns a vector with the capacity per link reserved for protection, at the given layer. i-th vector corresponds to i-th index of the element. If no layer is provided, the defaulf layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return The vector with the capacity per link reserver for protection */ public DoubleMatrix1D getVectorLinkCapacityReservedForProtection (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); DoubleMatrix1D res = DoubleFactory1D.dense.make(layer.links.size()); for (Link e : layer.links) res.set(e.index, e.getReservedCapacityForProtection()); return res; } /** * <p>Returns a vector with the length in km in the links, at the given layer. i-th vector corresponds to i-th index of the element. If no layer is provided, the defaulf layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return The vector with the length un km per link */ public DoubleMatrix1D getVectorLinkLengthInKm (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); DoubleMatrix1D res = DoubleFactory1D.dense.make(layer.links.size()); for (Link e : layer.links) res.set(e.index, e.lengthInKm); return res; } /** * <p>Returns a vector with the propagation delay in milliseconds in the links, at the given layer. i-th vector corresponds to i-th index of the element. If no layer is provided, the defaulf layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return The vector with the propagation time per link */ public DoubleMatrix1D getVectorLinkPropagationDelayInMiliseconds (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); DoubleMatrix1D res = DoubleFactory1D.dense.make(layer.links.size()); for (Link e : layer.links) res.set(e.index, e.getPropagationDelayInMs()); return res; } /** * <p>Returns a vector with the propagation speed in km/s in the links, at the given layer. i-th vector corresponds to i-th index of the element. If no layer is provided, the defaulf layer is assumed.</p> * @param optionalLayerParameter network layer (optional) * @return The vector with the propagation speed in km/s per link */ public DoubleMatrix1D getVectorLinkPropagationSpeedInKmPerSecond (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); DoubleMatrix1D res = DoubleFactory1D.dense.make(layer.links.size()); for (Link e : layer.links) res.set(e.index, e.propagationSpeedInKmPerSecond); return res; } /** * <p>Returns a vector with the total carried traffic per link (counting the traffic in the traversed protection segments), at the given layer. i-th vector corresponds to i-th index of the element. * If no layer is provided, the defaulf layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return The vector with the total carried traffic per link */ public DoubleMatrix1D getVectorLinkTotalCarriedTraffic (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); DoubleMatrix1D res = DoubleFactory1D.dense.make(layer.links.size()); for (Link e : layer.links) res.set(e.index, e.carriedTrafficSummingRoutesAndCarriedTrafficByProtectionSegments); return res; } /** * <p>Returns a vector with the total occupied capacity in the links (counting the capacity occupied by the traffic in the traversed protection segments), at the given layer. * i-th vector corresponds to i-th index of the element. If no layer is provided, the defaulf layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return The vector with the tootal occupied capacity per link */ public DoubleMatrix1D getVectorLinkTotalOccupiedCapacity (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); DoubleMatrix1D res = DoubleFactory1D.dense.make(layer.links.size()); for (Link e : layer.links) res.set(e.index, e.occupiedCapacitySummingRoutesAndCarriedTrafficByProtectionSegments); return res; } /** * <p>Returns a vector with the up/down state in the links (1 up, 0 down), at the given layer. i-th vector corresponds to i-th index of the element. * If no layer is provided, the defaulf layer is assumed</p> * @param optionalLayerParameter Network layer (optional) * @return The vector with the up/down state in the links */ public DoubleMatrix1D getVectorLinkUpState (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); DoubleMatrix1D res = DoubleFactory1D.dense.make(layer.links.size()); for (Link e : layer.links) res.set(e.index, e.isUp? 1 : 0); return res; } /** * <p>Returns a vector with the utilization per link, at the given layer. Utilization is measured as the total link occupied capacity by the link traffic * including the one in the protection segments, divided by the total link capacity (accounting the reserved capacity by the protection segments). * i-th vector corresponds to i-th index of the element. If no layer is provided, the defaulf layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return The vector with the utilization per link */ public DoubleMatrix1D getVectorLinkUtilizationIncludingProtectionSegments (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); DoubleMatrix1D res = DoubleFactory1D.dense.make(layer.links.size()); for (Link e : layer.links) res.set(e.index, e.getUtilizationIncludingProtectionSegments()); return res; } /** * <p>Returns a vector with the utilization per link, at the given layer. Utilization is measured as the total link occupied capacity by the link traffic * <b>not</b> including the one in the protection segments, divided by the total link capacity, <b>not</b> including that reserved by the protection segments. * i-th vector corresponds to i-th index of the element. If no layer is provided, the defaulf layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return The link utilization vector (not including protection segments) */ public DoubleMatrix1D getVectorLinkUtilizationNotIncludingProtectionSegments (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); DoubleMatrix1D res = DoubleFactory1D.dense.make(layer.links.size()); for (Link e : layer.links) res.set(e.index, e.getUtilizationNotIncludingProtectionSegments()); return res; } /** * <p>Returns a vector with the oversubscibed traffic (oversubscribed traffic being the sum of all carried traffic, including protection segments minus the capacity, or 0 if such substraction is negative) in each link at the given layer. * i-th vector corresponds to i-th index of the element. If no layer is provided, default layer is assumed. </p> * @param optionalLayerParameter network layer (optional) * @return The vector with the oversubscribed traffic per link */ public DoubleMatrix1D getVectorLinkOversubscribedTraffic (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); DoubleMatrix1D res = DoubleFactory1D.dense.make(layer.links.size()); for (Link e : layer.links) res.set(e.index, Math.max(0 , e.occupiedCapacitySummingRoutesAndCarriedTrafficByProtectionSegments - e.capacity)); return res; } /** * <p>Returns a vector with the carried traffic per multicast demand, at the given layer. i-th vector corresponds to i-th index of the element. If no layer is provided, the defaulf layer is assumed</p> * @param optionalLayerParameter network layer (optional) * @return The vector with the carried traffic per multicast demand */ public DoubleMatrix1D getVectorMulticastDemandCarriedTraffic(NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); DoubleMatrix1D res = DoubleFactory1D.dense.make(layer.multicastDemands.size()); for (MulticastDemand e : layer.multicastDemands) res.set(e.index, e.carriedTraffic); return res; } /** * <p>Returns a vector with the offered traffic per multicast demand, at the given layer. i-th vector corresponds to i-th index of the element. If no layer is provided, the defaulf layer is assumed.</p> * @param optionalLayerParameter network layer (optional) * @return The vector with the offered traffic per multicast demand */ public DoubleMatrix1D getVectorMulticastDemandOfferedTraffic(NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); DoubleMatrix1D res = DoubleFactory1D.dense.make(layer.multicastDemands.size()); for (MulticastDemand e : layer.multicastDemands) res.set(e.index, e.offeredTraffic); return res; } /** * <p>Returns a vector with the blocked traffic per multicast demand, at the given layer. i-th vector corresponds to i-th index of the element. If no layer is provided, the defaulf layer is assumed.</p> * @param optionalLayerParameter network layer (optional) * @return The vector with the blocked traffic per multicast demand */ public DoubleMatrix1D getVectorMulticastDemandBlockedTraffic(NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); DoubleMatrix1D res = DoubleFactory1D.dense.make(layer.multicastDemands.size()); for (MulticastDemand e : layer.multicastDemands) res.set(e.index, Math.max(0 , e.offeredTraffic - e.carriedTraffic)); return res; } /** * <p>Returns a vector with the carried traffic per multicast tree, at the given layer. i-th vector corresponds to i-th index of the element. If no layer is provided, the defaulf layer is assumed.</p> * @param optionalLayerParameter network layer (optional) * @return The vector with the carried traffic per multicast tree */ public DoubleMatrix1D getVectorMulticastTreeCarriedTraffic (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); DoubleMatrix1D res = DoubleFactory1D.dense.make(layer.multicastTrees.size()); for (MulticastTree e : layer.multicastTrees) res.set(e.index, e.carriedTraffic); return res; } /** * <p>Returns a vector with the number of links per multicast tree, at the given layer. i-th vector corresponds to i-th index of the element. If no layer is provided, the defaulf layer is assumed.</p> * @param optionalLayerParameter network layer (optional) * @return The vector with the number of links per multicast tree */ public DoubleMatrix1D getVectorMulticastTreeNumberOfLinks (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); DoubleMatrix1D res = DoubleFactory1D.dense.make(layer.multicastTrees.size()); for (MulticastTree e : layer.multicastTrees) res.set(e.index, e.linkSet.size ()); return res; } /** * <p>Returns a vector with the avergage number of hops per multicast tree at the given layer. i-th vector corresponds to i-th index of the element. If no layer is provided, the defaulf layer is assumed. </p> * @param optionalLayerParameter network layer (optional) * @return The average number of hops per multicast tree */ public DoubleMatrix1D getVectorMulticastTreeAverageNumberOfHops (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); DoubleMatrix1D res = DoubleFactory1D.dense.make(layer.multicastTrees.size()); for (MulticastTree e : layer.multicastTrees) res.set(e.index, e.getTreeAveragePathLengthInHops()); return res; } /** * <p>Returns a vector with the occupied capacity traffic per multicast tree, at the given layer. i-th vector corresponds to i-th index of the element. If no layer is provided, the defaulf layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return The vector with the occupied capacity per multicast tree */ public DoubleMatrix1D getVectorMulticastTreeOccupiedCapacity (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); DoubleMatrix1D res = DoubleFactory1D.dense.make(layer.multicastTrees.size()); for (MulticastTree e : layer.multicastTrees) res.set(e.index, e.occupiedLinkCapacity); return res; } /** * <p>Returns a vector with the up/down state of the nodes (1 up, 0 down). i-th vector corresponds to i-th index of the element</p> * @return The vector with the up/down state of the nodes. */ public DoubleMatrix1D getVectorNodeUpState () { DoubleMatrix1D res = DoubleFactory1D.dense.make(nodes.size()); for (Node e : nodes) res.set(e.index, e.isUp? 1 : 0); return res; } /** * <p>Returns the vector with the total outgoing offered traffic per node at the given layer. i-th vector corresponds to i-th index of the element. if no layer is provided, default layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return The vector with the total outgoing offered traffic per node */ public DoubleMatrix1D getVectorNodeIngressUnicastTraffic (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); DoubleMatrix1D res = DoubleFactory1D.dense.make(nodes.size()); for (Node n : nodes) { double traf = 0; for (Demand d: n.cache_nodeOutgoingDemands) if (d.layer == layer) traf += d.offeredTraffic; res.set (n.index , traf); } return res; } /** * <p>Returns the vector with the total incoming offered traffic per node at the given layer. i-th vector corresponds to i-th index of the element. if no layer is provided, default layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return The vector with the total incoming offered traffic per node */ public DoubleMatrix1D getVectorNodeEgressUnicastTraffic (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); DoubleMatrix1D res = DoubleFactory1D.dense.make(nodes.size()); for (Node n : nodes) { double traf = 0; for (Demand d: n.cache_nodeIncomingDemands) if (d.layer == layer) traf += d.offeredTraffic; res.set (n.index , traf); } return res; } /** * <p>Returns a vector with the carried traffic per protection segment, at the given layer. i-th vector corresponds to i-th index of the element. If no layer is provided, the defaulf layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return The vector with the carried traffic per protection segment */ public DoubleMatrix1D getVectorProtectionSegmentCarriedTraffic (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); layer.checkRoutingType(RoutingType.SOURCE_ROUTING); DoubleMatrix1D res = DoubleFactory1D.dense.make(layer.protectionSegments.size()); for (ProtectionSegment e : layer.protectionSegments) res.set(e.index, e.carriedTrafficSummingRoutesAndCarriedTrafficByProtectionSegments); return res; } /** * <p>Returns a vector with the length in km per protection segment, at the given layer. i-th vector corresponds to i-th index of the element. If no layer is provided, the defaulf layer is assumed.</p> * @param optionalLayerParameter network layer (optional) * @return The vector with the length in km per protection segment */ public DoubleMatrix1D getVectorProtectionSegmentLengthInKm (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); layer.checkRoutingType(RoutingType.SOURCE_ROUTING); DoubleMatrix1D res = DoubleFactory1D.dense.make(layer.protectionSegments.size()); for (ProtectionSegment e : layer.protectionSegments) res.set(e.index, e.lengthInKm); return res; } /** * <p>Returns a vector with the number of links per protection segment, at the given layer. i-th vector corresponds to i-th index of the element. If no layer is provided, the defaulf layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return The vector with the number of links per protection segment */ public DoubleMatrix1D getVectorProtectionSegmentNumberOfLinks (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); layer.checkRoutingType(RoutingType.SOURCE_ROUTING); DoubleMatrix1D res = DoubleFactory1D.dense.make(layer.protectionSegments.size()); for (ProtectionSegment e : layer.protectionSegments) res.set(e.index, e.seqLinks.size()); return res; } /** * <p>Returns a vector with the occupied capacity traffic per protection segment, at the given layer. i-th vector corresponds to i-th index of the element. If no layer is provided, the defaulf layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return The vector with the occupied capacity traffic per protection segment */ public DoubleMatrix1D getVectorProtectionSegmentOccupiedCapacity (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); layer.checkRoutingType(RoutingType.SOURCE_ROUTING); DoubleMatrix1D res = DoubleFactory1D.dense.make(layer.protectionSegments.size()); for (ProtectionSegment e : layer.protectionSegments) res.set(e.index, e.occupiedCapacitySummingRoutesAndCarriedTrafficByProtectionSegments); return res; } /** * <p>Returns a vector with the carried traffic per route, at the given layer. i-th vector corresponds to i-th index of the element. If no layer is provided, the defaulf layer is assumed</p> * @param optionalLayerParameter Network layer (optional) * @return The vector with the carried traffic per route */ public DoubleMatrix1D getVectorRouteCarriedTraffic (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); layer.checkRoutingType(RoutingType.SOURCE_ROUTING); DoubleMatrix1D res = DoubleFactory1D.dense.make(layer.routes.size()); for (Route e : layer.routes) res.set(e.index, e.carriedTraffic); return res; } /** * <p>Returns a vector with the offered traffic (from its associated demand) per route at the given layer. i-th vector corresponds to i-th index of the element. If no layer is provided, the defaulf layer is assumed. </p> * @param optionalLayerParameter Network layer (optional) * @return The vector with the offered traffic per route (from is associated demand) */ public DoubleMatrix1D getVectorRouteOfferedTrafficOfAssociatedDemand (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); layer.checkRoutingType(RoutingType.SOURCE_ROUTING); DoubleMatrix1D res = DoubleFactory1D.dense.make(layer.routes.size()); for (Route e : layer.routes) res.set(e.index, e.demand.offeredTraffic); return res; } /** * <p>Returns a vector with the offered traffic per multicast tree from its associated multicast demand, at the given layer. i-th vector corresponds to i-th index of the element. If no layer is provided, the defaulf layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return The vector with the offered traffic per multicast tree from its associated multicast demand */ public DoubleMatrix1D getVectorMulticastTreeOfferedTrafficOfAssociatedMulticastDemand (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); DoubleMatrix1D res = DoubleFactory1D.dense.make(layer.multicastTrees.size()); for (MulticastTree e : layer.multicastTrees) res.set(e.index, e.demand.offeredTraffic); return res; } /** * <p>Returns a vector with the length in km per route, at the given layer. i-th vector corresponds to i-th index of the element. If no layer is provided, the defaulf layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return The vector with the length in km per route */ public DoubleMatrix1D getVectorRouteLengthInKm (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); layer.checkRoutingType(RoutingType.SOURCE_ROUTING); DoubleMatrix1D res = DoubleFactory1D.dense.make(layer.routes.size()); for (Route e : layer.routes) res.set(e.index, e.getLengthInKm()); return res; } /** * <p>Returns a vector with the propagation delay in seconds per route, at the given layer. i-th vector corresponds to i-th index of the element. If no layer is provided, the defaulf layer is assumed.</p> * @param optionalLayerParameter network layer (optional) * @return The vector with the propagation delay in seconds per route */ public DoubleMatrix1D getVectorRoutePropagationDelayInMiliseconds (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); layer.checkRoutingType(RoutingType.SOURCE_ROUTING); DoubleMatrix1D res = DoubleFactory1D.dense.make(layer.routes.size()); for (Route e : layer.routes) res.set(e.index, e.getPropagationDelayInMiliseconds()); return res; } /** * <p>Returns a vector with the number of links per route (including the links in the traversed protection segments if any), at the given layer. i-th vector corresponds to i-th index of the element. * If no layer is provided, the defaulf layer is assumed.</p> * @param optionalLayerParameter network layer (optional) * @return The vector with the number of links per route */ public DoubleMatrix1D getVectorRouteNumberOfLinks (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); layer.checkRoutingType(RoutingType.SOURCE_ROUTING); DoubleMatrix1D res = DoubleFactory1D.dense.make(layer.routes.size()); for (Route e : layer.routes) res.set(e.index, e.seqLinksRealPath.size()); return res; } /** * <p>Returns an array with the cost of each route in the layer. The cost of a route is given by the sum * of the costs of its links, given by the provided cost vector. If the route traverses protection segments, the cost * of its links is included. If the cost vector provided is {@code null}, * all links have cost one.</p> * @param costs Costs array * @param optionalLayerParameter Network layer (optional) * @return The cost of each route in the network * @see com.net2plan.interfaces.networkDesign.Route */ public DoubleMatrix1D computeRouteCostVector (double [] costs , NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); layer.checkRoutingType(RoutingType.SOURCE_ROUTING); if (costs == null) costs = DoubleUtils.ones(layer.links.size ()); else if (costs.length != layer.links.size()) throw new Net2PlanException ("The array of costs must have the same length as the number of links in the layer"); DoubleMatrix1D res = DoubleFactory1D.dense.make (layer.routes.size()); for (Route r : layer.routes) for (Link link : r.seqLinksRealPath) res.set (r.index , res.get(r.index) + costs [link.index]); return res; } /** * <p>Returns an array with the cost of each multicast tree in the layer. The cost of a multicast tree is given by the sum * of the costs in its links, given by the provided cost vector. If the cost vector provided is {@code null}, * all links have cost one. </p> * @param costs Costs array * @param optionalLayerParameter Network layer (optional) * @return The cost of each multicast tree * @see com.net2plan.interfaces.networkDesign.MulticastTree */ public DoubleMatrix1D computeMulticastTreeCostVector (double [] costs , NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); if (costs.length != layer.links.size()) throw new Net2PlanException ("The array of costs must have the same length as the number of links in the layer"); DoubleMatrix1D res = DoubleFactory1D.dense.make (layer.routes.size()); for (MulticastTree t : layer.multicastTrees) for (Link link : t.linkSet) res.set (t.index , res.get(t.index) + costs [link.index]); return res; } /** * <p>Returns a vector with the occupied capacity traffic per route, at the given layer. i-th vector corresponds to i-th index of the element. If no layer is provided, the defaulf layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return The vector with the occupied traffic per route */ public DoubleMatrix1D getVectorRouteOccupiedCapacity (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); layer.checkRoutingType(RoutingType.SOURCE_ROUTING); DoubleMatrix1D res = DoubleFactory1D.dense.make(layer.routes.size()); for (Route e : layer.routes) res.set(e.index, e.occupiedLinkCapacity); return res; } /** * <p>Returns {@code true} if the network has one or more demands at the given layer. If no layer is provided, the default layer is assumed.</p> * @param optionalLayerParameter network layer (optional) * @return {@code True} if the network has demands at the given layer, {@code false} otherwise */ public boolean hasDemands (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); return layer.demands.size() > 0; } /** * <p>Returns {@code true} if the network has at least one non-zero forwarding rule splitting ratio in any demand-link pair, in the given layer. If no layer is provided, the default layer is assumed.</p> * @param optionalLayerParameter network layer (optional) * @return {@code True} if the network has at least one forwarding rule, {@code false} otherwise */ public boolean hasForwardingRules (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); layer.checkRoutingType(RoutingType.HOP_BY_HOP_ROUTING); IntArrayList rows = new IntArrayList (); IntArrayList cols = new IntArrayList (); DoubleArrayList vals = new DoubleArrayList (); layer.forwardingRules_f_de.getNonZeros(rows,cols,vals); return (rows.size () != 0); } /** * <p>Returns {@code true} if the network has one or more links at the given layer. If no layer is provided, the default layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return {@code True} if the network has one or more links, {@code false} otherwise */ public boolean hasLinks (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); return layer.links.size() > 0; } /** * <p>Returns {@code true} if the network has one or more multicast demands at the given layer. If no layer is provided, the default layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return {@code True} if the network has one or more multicast demand, {@code false} otherwise */ public boolean hasMulticastDemands (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); return layer.multicastDemands.size() > 0; } /** * <p>Returns {@code true} if the network has one or more multicast trees at the given layer. If no layer is provided, the default layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return {@code True} if the network has one or more multicast trees, {@code false} otherwise */ public boolean hasMulticastTrees (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); return layer.multicastTrees.size() > 0; } /** * <p>Returns {@code true} if the network has nodes.</p> * @return {@code True} if the network has nodes, {@code false} otherwise */ public boolean hasNodes () { return nodes.size() > 0; } /** * <p>Returns {@code true} if the network has one or more protection segments at the given layer. If no layer is provided, the default layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return {@code True} if the network has one or more protection segments, {@code false} otherwise */ public boolean hasProtectionSegments (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); layer.checkRoutingType(RoutingType.SOURCE_ROUTING); return layer.protectionSegments.size() > 0; } /** * <p>Returns {@code true} if the network has one or moreroutes at the given layer. If no layer is provided, the default layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return {@code True} if the network has one or more routes, {@code false} otherwise */ public boolean hasRoutes (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); layer.checkRoutingType(RoutingType.SOURCE_ROUTING); return layer.routes.size() > 0; } /** * <p>Returns {@code true} if the network has one or more shared risk groups (SRGs) defined.</p> * @return {@code True} if the network has SRGs defined, {@code false} otherwise */ public boolean hasSRGs () { return srgs.size() > 0; } /** * <p>Returns {@code true} if the network has at least one routing cycle at the given layer. If no layer is provided, default layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return {@code True} if there is at least one routing cycle, {@code false} otherwise */ public boolean hasUnicastRoutingLoops (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); for (Demand d : layer.demands) if (d.getRoutingCycleType() != RoutingCycleType.LOOPLESS) return true; return false; } /** * <p>Indicates whether or not a further coupling between two layers would be valid. * This can be used to check if a new coupling would create cycles in the topology * of layers, that is, if layer hierarchy is not broken.</p> * @param lowerLayer Network lower layer * @param upperLayer Network upper layer * @return {@code True} if coupling between both input layers is valid, {@code false} otherwise */ public boolean isLayerCouplingValid(NetworkLayer lowerLayer , NetworkLayer upperLayer) { checkInThisNetPlan(lowerLayer); checkInThisNetPlan(upperLayer); if (lowerLayer.equals (upperLayer)) return false; DemandLinkMapping coupling_thisLayerPair = interLayerCoupling.getEdge(lowerLayer, upperLayer); if (coupling_thisLayerPair == null) { coupling_thisLayerPair = new DemandLinkMapping(); boolean valid; try { valid = interLayerCoupling.addDagEdge(lowerLayer, upperLayer, coupling_thisLayerPair); } catch (DirectedAcyclicGraph.CycleFoundException ex) { valid = false; } if (valid) interLayerCoupling.removeEdge(lowerLayer, upperLayer); else return false; } return true; } /** * <p>Returns {@code true} if in the given layer, the traffic of any multicast demand is carried by more than one multicast tree. If no layer is provided, the default layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @return {@code True} if traffic from at least one multicast demand is carried trhough two or more multicast trees, {@code false} otherwise */ public boolean isMulticastRoutingBifurcated (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); for (MulticastDemand d : layer.multicastDemands) if (d.isBifurcated ()) return true; return false; } /** * <p>Returns {@code true} if the network has more than one layer.</p> * @return {@code True} if the network has two or more layers, {@code false} otherwise */ public boolean isMultilayer () { return layers.size() > 1; } /** * <p>Returns {@code true} if the network has just one layer</p> * @return {@code True} if network has only one layer, {@code false} otherwise */ public boolean isSingleLayer () { return layers.size() == 1; } /** * <p>Returns {@code true} if in the given layer, the traffic of any demand is carried by more than one route (in {@link com.net2plan.utils.Constants.RoutingType#SOURCE_ROUTING SOURCE_ROUTING}), * or a node sends traffic of a demand to more than * one link (in {@link com.net2plan.utils.Constants.RoutingType#HOP_BY_HOP_ROUTING HOP_BY_HOP_ROUTING}). If no layer is provided, the default layer is assumed</p> * @param optionalLayerParameter Network layer (optional) * @return {@code True} if unicast traffic is bifurcated (see description), {@code false} otherwise */ public boolean isUnicastRoutingBifurcated (NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); for (Demand d : layer.demands) if (d.isBifurcated ()) return true; return false; } /** * <p>Indicates whether or not a path, multicast tree or arbitrary collection of links (and/or protection segments) is up. * This means that all links are up, and all end nodes of the links are also up</p> * @param linksAndOrProtectionSegments Sequence of links * @return {@code True} if all links in the sequence are up, {@code false} otherwise */ public boolean isUp (Collection<Link> linksAndOrProtectionSegments) { checkInThisNetPlan(linksAndOrProtectionSegments); for (Link e : linksAndOrProtectionSegments) { e.checkAttachedToNetPlanObject(this); if (!e.isUp ()) return false; if (!e.originNode.isUp) return false; if (!e.destinationNode.isUp) return false; } return true; } /** * <p>Removes a layer, and any associated link, demand, route, protection segment or forwarding rule. If this layer is the default, the new default layer is the one with index 0 (the smallest identifier) </p> * @param optionalLayerParameter Network layer (optional) */ public void removeNetworkLayer (NetworkLayer ... optionalLayerParameter) { checkIsModifiable(); NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); checkAttachedToNetPlanObject(); netPlan.checkIsModifiable(); if (netPlan.layers.size () == 1) throw new Net2PlanException("At least one layer must exist"); for (ProtectionSegment segment : new LinkedList<ProtectionSegment> (layer.protectionSegments)) segment.remove (); for (Route route : new LinkedList<Route> (layer.routes)) route.remove (); for (MulticastTree tree : new LinkedList<MulticastTree> (layer.multicastTrees)) tree.remove (); for (Link link : new LinkedList<Link> (layer.links)) link.remove (); for (Demand demand : new LinkedList<Demand> (layer.demands)) demand.remove (); for (MulticastDemand demand : new LinkedList<MulticastDemand> (layer.multicastDemands)) demand.remove (); netPlan.interLayerCoupling.removeVertex(layer); netPlan.cache_id2LayerMap.remove(layer.id); NetPlan.removeNetworkElementAndShiftIndexes(netPlan.layers , layer.index); if (netPlan.defaultLayer.equals(layer)) netPlan.defaultLayer = netPlan.layers.get (0); if (ErrorHandling.isDebugEnabled()) netPlan.checkCachesConsistency(); removeId (); } /** * <p>Removes all the demands defined in the given layer. If no layer is provided, default layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) */ public void removeAllDemands(NetworkLayer ... optionalLayerParameter) { checkIsModifiable(); NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); for (Demand d : new ArrayList<Demand> (layer.demands)) d.remove (); if (ErrorHandling.isDebugEnabled()) this.checkCachesConsistency(); } /** * <p>Removes all the forwarding rules in the given layer. If no layer is provided, default layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) */ public void removeAllForwardingRules(NetworkLayer ... optionalLayerParameter) { checkIsModifiable(); NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); layer.checkRoutingType(RoutingType.HOP_BY_HOP_ROUTING); layer.forwardingRules_f_de = DoubleFactory2D.sparse.make (layer.demands.size() , layer.links.size()); layer.forwardingRules_x_de = DoubleFactory2D.sparse.make (layer.demands.size() , layer.links.size()); for (Demand d : layer.demands) { d.routingCycleType = RoutingCycleType.LOOPLESS; d.carriedTraffic = 0; if (d.coupledUpperLayerLink != null) d.coupledUpperLayerLink.capacity = d.carriedTraffic; } for (Link e : layer.links) { e.carriedTrafficSummingRoutesAndCarriedTrafficByProtectionSegments = e.getMulticastCarriedTraffic(); e.occupiedCapacitySummingRoutesAndCarriedTrafficByProtectionSegments = e.getMulticastOccupiedLinkCapacity(); } if (ErrorHandling.isDebugEnabled()) this.checkCachesConsistency(); } /** * <p>Removes all the links defined in the given layer. If no layer is provided, default layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) */ public void removeAllLinks(NetworkLayer ... optionalLayerParameter) { checkIsModifiable(); NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); for (Link e : new ArrayList<Link> (layer.links)) e.remove (); if (ErrorHandling.isDebugEnabled()) this.checkCachesConsistency(); } /** * <p>Removes all the multicast demands defined in the given layer. If no layer is provided, default layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) */ public void removeAllMulticastDemands(NetworkLayer ... optionalLayerParameter) { checkIsModifiable(); NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); for (MulticastDemand d : new ArrayList<MulticastDemand> (layer.multicastDemands)) d.remove (); if (ErrorHandling.isDebugEnabled()) this.checkCachesConsistency(); } /** * <p>Removes all the multicast trees defined in the given layer. If no layer is provided, default layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) */ public void removeAllMulticastTrees (NetworkLayer ... optionalLayerParameter) { checkIsModifiable(); NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); for (MulticastTree t : new ArrayList<MulticastTree> (layer.multicastTrees)) t.remove (); if (ErrorHandling.isDebugEnabled()) this.checkCachesConsistency(); } /** * <p>Removes all the multicast trees carrying no traffic and occupying no link capacity defined in the given layer. If no layer is provided, default layer is used.</p> * * @param toleranceTrafficAndCapacityValueToConsiderUnusedTree Tolerance capacity to consider a link unsused * @param optionalLayerParameter Network layer (optional) */ public void removeAllMulticastTreesUnused (double toleranceTrafficAndCapacityValueToConsiderUnusedTree , NetworkLayer ... optionalLayerParameter) { checkIsModifiable(); NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); for (MulticastTree t : new ArrayList<MulticastTree> (layer.multicastTrees)) if ((t.carriedTraffic < toleranceTrafficAndCapacityValueToConsiderUnusedTree) && (t.occupiedLinkCapacity < toleranceTrafficAndCapacityValueToConsiderUnusedTree)) t.remove (); if (ErrorHandling.isDebugEnabled()) this.checkCachesConsistency(); } /** * <p>Removes all the network layers (everything but the nodes and the SRGs). Removes all the links, demands and multicast demands of the defualt layer, it does not remove it </p> */ public void removeAllNetworkLayers () { checkIsModifiable(); for (NetworkLayer layer : new ArrayList<NetworkLayer> (layers)) { if (layer != defaultLayer) { removeNetworkLayer (layer); continue; } removeAllLinks(layer); removeAllDemands(layer); removeAllMulticastDemands(layer); } if (ErrorHandling.isDebugEnabled()) this.checkCachesConsistency(); } /** * <p>Removes all the network nodes.</p> */ public void removeAllNodes () { checkIsModifiable(); for (NetworkLayer layer : layers) if (layer.routingType == RoutingType.HOP_BY_HOP_ROUTING) removeAllForwardingRules(layer); // to speed up things for (Node n : new ArrayList<Node> (nodes)) n.remove (); if (ErrorHandling.isDebugEnabled()) this.checkCachesConsistency(); } /** * <p>Removes all the protection segments defined in the given layer. If no layer is provided, default layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) */ public void removeAllProtectionSegments(NetworkLayer ... optionalLayerParameter) { checkIsModifiable(); NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); layer.checkRoutingType(RoutingType.SOURCE_ROUTING); for (ProtectionSegment s : new ArrayList<ProtectionSegment> (layer.protectionSegments)) s.remove (); if (ErrorHandling.isDebugEnabled()) this.checkCachesConsistency(); } /** * <p>Removes all the routes defined in the given layer. If no layer is provided, default layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) */ public void removeAllRoutes(NetworkLayer ... optionalLayerParameter) { checkIsModifiable(); NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); layer.checkRoutingType(RoutingType.SOURCE_ROUTING); for (Route r : new ArrayList<Route> (layer.routes)) r.remove (); if (ErrorHandling.isDebugEnabled()) this.checkCachesConsistency(); } /** * <p>Removes all the routes defined in the given layer that do not carry traffic nor occupy link capacity in the given layer. If no layer is provided, default layer is assumed.</p> * @param toleranceTrafficAndCapacityValueToConsiderUnusedRoute Tolerance traffic to consider a route unused * @param optionalLayerParameter Network layer (optional) */ public void removeAllRoutesUnused (double toleranceTrafficAndCapacityValueToConsiderUnusedRoute , NetworkLayer ... optionalLayerParameter) { checkIsModifiable(); NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); layer.checkRoutingType(RoutingType.SOURCE_ROUTING); for (Route r : new ArrayList<Route> (layer.routes)) if ((r.carriedTraffic < toleranceTrafficAndCapacityValueToConsiderUnusedRoute) && (r.occupiedLinkCapacity < toleranceTrafficAndCapacityValueToConsiderUnusedRoute)) r.remove (); if (ErrorHandling.isDebugEnabled()) this.checkCachesConsistency(); } /** * <p>Removes all the unsused links (those whith lesser capacity than {@code toleranceCapacityValueToConsiderUnusedLink}) defined in the given layer. If no layer is provided, default layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) * @param toleranceCapacityValueToConsiderUnusedLink Tolerance capacity to consider a link unsused */ public void removeAllLinksUnused (double toleranceCapacityValueToConsiderUnusedLink , NetworkLayer ... optionalLayerParameter) { checkIsModifiable(); NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); for (Link e : new ArrayList<Link> (layer.links)) if (e.capacity < toleranceCapacityValueToConsiderUnusedLink) e.remove (); if (ErrorHandling.isDebugEnabled()) this.checkCachesConsistency(); } /** * <p>Removes all the routing information (unicast and multicast) for the given layer, irrespective of the routing type * setting. For source routing, all routes and protection segments are removed. * For hop-by-hop routing, all forwarding rules are removed. If no layer is provided, the default layer is assumed.</p> * @param optionalLayerParameter Network layer (optional) */ public void removeAllUnicastRoutingInformation(NetworkLayer ... optionalLayerParameter) { checkIsModifiable(); NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); switch(layer.routingType) { case SOURCE_ROUTING: removeAllRoutes(layer); removeAllProtectionSegments(layer); break; case HOP_BY_HOP_ROUTING: removeAllForwardingRules(layer); break; default: throw new RuntimeException("Bad"); } if (ErrorHandling.isDebugEnabled()) this.checkCachesConsistency(); } /** * <p>Removes all the shared risk groups.</p> */ public void removeAllSRGs () { checkIsModifiable(); for (SharedRiskGroup s : new ArrayList<SharedRiskGroup> (srgs)) s.remove (); if (ErrorHandling.isDebugEnabled()) this.checkCachesConsistency(); } /** * <p>Resets the state of the network to an empty {@code NetPlan}.</p> */ public void reset() { checkIsModifiable(); assignFrom(new NetPlan()); if (ErrorHandling.isDebugEnabled()) this.checkCachesConsistency(); } /** * <p>Saves the current network plan to a given file. If extension {@code .n2p} * is not in the file name, it will be added automatically.</p> * @param file Output file */ public void saveToFile(File file) { String filePath = file.getPath(); if (!filePath.toLowerCase(Locale.getDefault()).endsWith(".n2p")) file = new File(filePath + ".n2p"); FileOutputStream fos = null; try { fos = new FileOutputStream(file); saveToOutputStream(fos); } catch (FileNotFoundException e) { if (fos != null) { try { fos.close(); } catch (IOException ex) { } } throw new Net2PlanException(e.getMessage()); } } /** * <p>Saves the current network plan to a given output stream.</p> * @param outputStream Output stream */ public void saveToOutputStream(OutputStream outputStream) { try { XMLOutputFactory2 output = (XMLOutputFactory2) XMLOutputFactory2.newFactory(); XMLStreamWriter2 writer = (XMLStreamWriter2) output.createXMLStreamWriter(outputStream); writer.writeStartDocument("UTF-8", "1.0"); XMLUtils.indent(writer, 0); writer.writeStartElement("network"); writer.writeAttribute("description", getNetworkDescription()); writer.writeAttribute("name", getNetworkName()); writer.writeAttribute("version", Version.getFileFormatVersion()); //Set<Long> nodeIds_thisNetPlan = new HashSet<Long> (getNodeIds()); for (Node node : nodes) { boolean emptyNode = node.attributes.isEmpty(); XMLUtils.indent(writer, 1); if (emptyNode) writer.writeEmptyElement("node"); else writer.writeStartElement("node"); Point2D position = node.nodeXYPositionMap; writer.writeAttribute("id", Long.toString(node.id)); writer.writeAttribute("xCoord", Double.toString(position.getX())); writer.writeAttribute("yCoord", Double.toString(position.getY())); writer.writeAttribute("name", node.name); writer.writeAttribute("isUp", Boolean.toString (node.isUp)); for (Entry<String, String> entry : node.attributes.entrySet()) { XMLUtils.indent(writer, 2); writer.writeEmptyElement("attribute"); writer.writeAttribute("key", entry.getKey()); writer.writeAttribute("value", entry.getValue()); } if (!emptyNode) { XMLUtils.indent(writer, 1); writer.writeEndElement(); } } for(NetworkLayer layer : layers) { XMLUtils.indent(writer, 1); writer.writeStartElement("layer"); writer.writeAttribute("id", Long.toString(layer.id)); writer.writeAttribute("name", layer.name); writer.writeAttribute("description", layer.description); writer.writeAttribute("linkCapacityUnitsName", layer.linkCapacityUnitsName); writer.writeAttribute("demandTrafficUnitsName", layer.demandTrafficUnitsName); for(Link link : layer.links) { boolean emptyLink = link.attributes.isEmpty(); XMLUtils.indent(writer, 2); if (emptyLink) writer.writeEmptyElement("link"); else writer.writeStartElement("link"); writer.writeAttribute("id", Long.toString(link.id)); writer.writeAttribute("originNodeId", Long.toString(link.originNode.id)); writer.writeAttribute("destinationNodeId", Long.toString(link.destinationNode.id)); writer.writeAttribute("capacity", Double.toString(link.capacity)); writer.writeAttribute("lengthInKm", Double.toString(link.lengthInKm)); writer.writeAttribute("propagationSpeedInKmPerSecond", Double.toString(link.propagationSpeedInKmPerSecond)); writer.writeAttribute("isUp", Boolean.toString(link.isUp)); for (Entry<String, String> entry : link.attributes.entrySet()) { XMLUtils.indent(writer, 3); writer.writeEmptyElement("attribute"); writer.writeAttribute("key", entry.getKey()); writer.writeAttribute("value", entry.getValue()); } if (!emptyLink) { XMLUtils.indent(writer, 2); writer.writeEndElement(); } } for(Demand demand : layer.demands) { boolean emptyDemand = demand.attributes.isEmpty(); XMLUtils.indent(writer, 2); if (emptyDemand) writer.writeEmptyElement("demand"); else writer.writeStartElement("demand"); writer.writeAttribute("id", Long.toString(demand.id)); writer.writeAttribute("ingressNodeId", Long.toString(demand.ingressNode.id)); writer.writeAttribute("egressNodeId", Long.toString(demand.egressNode.id)); writer.writeAttribute("offeredTraffic", Double.toString(demand.offeredTraffic)); for (Entry<String, String> entry : demand.attributes.entrySet()) { XMLUtils.indent(writer, 3); writer.writeEmptyElement("attribute"); writer.writeAttribute("key", entry.getKey()); writer.writeAttribute("value", entry.getValue()); } if (!emptyDemand) { XMLUtils.indent(writer, 2); writer.writeEndElement(); } } for(MulticastDemand demand : layer.multicastDemands) { boolean emptyDemand = demand.attributes.isEmpty(); XMLUtils.indent(writer, 2); if (emptyDemand) writer.writeEmptyElement("multicastDemand"); else writer.writeStartElement("multicastDemand"); writer.writeAttribute("id", Long.toString(demand.id)); writer.writeAttribute("ingressNodeId", Long.toString(demand.ingressNode.id)); List<Long> egressNodeIds = new LinkedList<Long> (); for (Node n : demand.egressNodes) egressNodeIds.add (n.id); writer.writeAttribute("egressNodeIds", CollectionUtils.join(egressNodeIds, " ")); writer.writeAttribute("offeredTraffic", Double.toString(demand.offeredTraffic)); for (Entry<String, String> entry : demand.attributes.entrySet()) { XMLUtils.indent(writer, 3); writer.writeEmptyElement("attribute"); writer.writeAttribute("key", entry.getKey()); writer.writeAttribute("value", entry.getValue()); } if (!emptyDemand) { XMLUtils.indent(writer, 2); writer.writeEndElement(); } } for(MulticastTree tree : layer.multicastTrees) { boolean emptyTree = tree.attributes.isEmpty(); XMLUtils.indent(writer, 3); if (emptyTree) writer.writeEmptyElement("multicastTree"); else writer.writeStartElement("multicastTree"); writer.writeAttribute("id", Long.toString(tree.id)); writer.writeAttribute("demandId", Long.toString(tree.demand.id)); writer.writeAttribute("carriedTraffic", Double.toString(tree.carriedTraffic)); writer.writeAttribute("occupiedCapacity", Double.toString(tree.occupiedLinkCapacity)); writer.writeAttribute("carriedTrafficIfNotFailing", Double.toString(tree.carriedTrafficIfNotFailing)); writer.writeAttribute("occupiedLinkCapacityIfNotFailing", Double.toString(tree.occupiedLinkCapacityIfNotFailing)); List<Long> linkIds = new LinkedList<Long> (); for (Link e : tree.linkSet) linkIds.add (e.id); writer.writeAttribute("currentSetLinks", CollectionUtils.join(linkIds , " ")); linkIds = new LinkedList<Long> (); for (Link e : tree.initialSetLinksWhenWasCreated) linkIds.add (e.id); writer.writeAttribute("linkIds", CollectionUtils.join(linkIds , " ")); for (Entry<String, String> entry : tree.attributes.entrySet()) { XMLUtils.indent(writer, 4); writer.writeEmptyElement("attribute"); writer.writeAttribute("key", entry.getKey()); writer.writeAttribute("value", entry.getValue()); } if (!emptyTree) { XMLUtils.indent(writer, 3); writer.writeEndElement(); } } if (layer.routingType == RoutingType.SOURCE_ROUTING) { boolean emptySourceRouting = !hasProtectionSegments(layer) && !hasRoutes(layer); XMLUtils.indent(writer, 2); if (emptySourceRouting) writer.writeEmptyElement("sourceRouting"); else writer.writeStartElement("sourceRouting"); for(ProtectionSegment segment : layer.protectionSegments) { boolean emptySegment = segment.attributes.isEmpty(); XMLUtils.indent(writer, 3); if (emptySegment) writer.writeEmptyElement("protectionSegment"); else writer.writeStartElement("protectionSegment"); writer.writeAttribute("id", Long.toString(segment.id)); writer.writeAttribute("reservedCapacity", Double.toString(segment.capacity)); List<Long> seqLinks = new LinkedList<Long> (); for (Link e : segment.seqLinks) seqLinks.add (e.id); writer.writeAttribute("seqLinks", CollectionUtils.join(seqLinks, " ")); for (Entry<String, String> entry : segment.attributes.entrySet()) { XMLUtils.indent(writer, 4); writer.writeEmptyElement("attribute"); writer.writeAttribute("key", entry.getKey()); writer.writeAttribute("value", entry.getValue()); } if (!emptySegment) { XMLUtils.indent(writer, 3); writer.writeEndElement(); } } for(Route route : layer.routes) { boolean emptyRoute = route.attributes.isEmpty(); XMLUtils.indent(writer, 3); if (emptyRoute) writer.writeEmptyElement("route"); else writer.writeStartElement("route"); writer.writeAttribute("id", Long.toString(route.id)); writer.writeAttribute("demandId", Long.toString(route.demand.id)); writer.writeAttribute("carriedTraffic", Double.toString(route.carriedTraffic)); writer.writeAttribute("occupiedCapacity", Double.toString(route.occupiedLinkCapacity)); writer.writeAttribute("carriedTrafficIfNotFailing", Double.toString(route.carriedTrafficIfNotFailing)); writer.writeAttribute("occupiedLinkCapacityIfNotFailing", Double.toString(route.occupiedLinkCapacityIfNotFailing)); List<Long> initialSeqLinksWhenCreated = new LinkedList<Long> (); for (Link e : route.initialSeqLinksWhenCreated) initialSeqLinksWhenCreated.add (e.id); List<Long> seqLinksAndProtectionSegments = new LinkedList<Long> (); for (Link e : route.seqLinksAndProtectionSegments) seqLinksAndProtectionSegments.add (e.id); List<Long> backupSegmentList = new LinkedList<Long> (); for (ProtectionSegment e : route.potentialBackupSegments) backupSegmentList.add (e.id); writer.writeAttribute("seqLinks", CollectionUtils.join(initialSeqLinksWhenCreated, " ")); writer.writeAttribute("currentSeqLinksAndProtectionSegments", CollectionUtils.join(seqLinksAndProtectionSegments, " ")); writer.writeAttribute("backupSegmentList", CollectionUtils.join(backupSegmentList, " ")); for (Entry<String, String> entry : route.attributes.entrySet()) { XMLUtils.indent(writer, 4); writer.writeEmptyElement("attribute"); writer.writeAttribute("key", entry.getKey()); writer.writeAttribute("value", entry.getValue()); } if (!emptyRoute) { XMLUtils.indent(writer, 3); writer.writeEndElement(); } } if (!emptySourceRouting) { XMLUtils.indent(writer, 2); writer.writeEndElement(); } } else { boolean emptyHopByHopRouting = !hasForwardingRules(layer); XMLUtils.indent(writer, 2); if (emptyHopByHopRouting) writer.writeEmptyElement("hopByHopRouting"); else writer.writeStartElement("hopByHopRouting"); IntArrayList rows = new IntArrayList (); IntArrayList cols = new IntArrayList (); DoubleArrayList vals = new DoubleArrayList (); layer.forwardingRules_f_de.getNonZeros(rows,cols,vals); for(int cont = 0 ; cont < rows.size () ; cont ++) { final int indexDemand = rows.get (cont); final int indexLink = cols.get (cont); final double splittingRatio = vals.get (cont); XMLUtils.indent(writer, 3); writer.writeEmptyElement("forwardingRule"); writer.writeAttribute("demandId", Long.toString(layer.demands.get(indexDemand).id)); writer.writeAttribute("linkId", Long.toString(layer.links.get(indexLink).id)); writer.writeAttribute("splittingRatio", Double.toString(splittingRatio)); } if (!emptyHopByHopRouting) { XMLUtils.indent(writer, 2); writer.writeEndElement(); } } for (Entry<String, String> entry : layer.attributes.entrySet()) { XMLUtils.indent(writer, 2); writer.writeEmptyElement("attribute"); writer.writeAttribute("key", entry.getKey()); writer.writeAttribute("value", entry.getValue()); } XMLUtils.indent(writer, 1); writer.writeEndElement(); } for (SharedRiskGroup srg : srgs) { boolean emptySRG = srg.attributes.isEmpty() && srg.nodes.isEmpty() && srg.links.isEmpty(); XMLUtils.indent(writer, 1); if (emptySRG) writer.writeEmptyElement("srg"); else writer.writeStartElement("srg"); writer.writeAttribute("id", Long.toString(srg.id)); writer.writeAttribute("meanTimeToFailInHours", Double.toString(srg.meanTimeToFailInHours)); writer.writeAttribute("meanTimeToRepairInHours", Double.toString(srg.meanTimeToRepairInHours)); for (Node node : srg.nodes) { XMLUtils.indent(writer, 2); writer.writeEmptyElement("node"); writer.writeAttribute("id", Long.toString(node.id)); } for (Link link : srg.links) { XMLUtils.indent(writer, 2); writer.writeEmptyElement("link"); writer.writeAttribute("linkId", Long.toString(link.id)); } for (Entry<String, String> entry : srg.attributes.entrySet()) { XMLUtils.indent(writer, 2); writer.writeEmptyElement("attribute"); writer.writeAttribute("key", entry.getKey()); writer.writeAttribute("value", entry.getValue()); } if (!emptySRG) { XMLUtils.indent(writer, 1); writer.writeEndElement(); } } for (DemandLinkMapping d_e : interLayerCoupling.edgeSet()) { for (Entry<Demand,Link> coupling : d_e.demandLinkMapping.entrySet()) { XMLUtils.indent(writer, 1); writer.writeEmptyElement("layerCouplingDemand"); writer.writeAttribute("lowerLayerDemandId", "" + coupling.getKey().id); writer.writeAttribute("upperLayerLinkId", "" + coupling.getValue().id); } for (Entry<MulticastDemand,Set<Link>> coupling : d_e.multicastDemandLinkMapping.entrySet()) { XMLUtils.indent(writer, 1); writer.writeEmptyElement("layerCouplingMulticastDemand"); List<Long> linkIds = new LinkedList<Long> (); for (Link e : coupling.getValue()) linkIds.add (e.id); writer.writeAttribute("lowerLayerDemandId", "" + coupling.getKey().id); writer.writeAttribute("upperLayerLinkIds", CollectionUtils.join(linkIds , " ")); } } for (Entry<String, String> entry : this.attributes.entrySet()) { XMLUtils.indent(writer, 1); writer.writeEmptyElement("attribute"); writer.writeAttribute("key", entry.getKey()); writer.writeAttribute("value", entry.getValue()); } XMLUtils.indent(writer, 0); writer.writeEndElement(); writer.writeEndDocument(); writer.flush(); writer.close(); } catch (XMLStreamException e) { throw new RuntimeException(e); } } /** * <p>Sets the failure state (up or down) for all the links in the given layer. If no layer is provided, the default layer is assumed.</p> * @param setAsUp {@code true} up, {@code false} down * @param optionalLayerParameter Network layer (optional) */ public void setAllLinksFailureState (boolean setAsUp , NetworkLayer ... optionalLayerParameter) { checkIsModifiable(); NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); if (setAsUp) setLinksAndNodesFailureState (layer.links , null , null , null); else setLinksAndNodesFailureState (null , layer.links , null , null); } /** * <p>Sets the failure state (up or down) for all the nodes.</p> * @param setAsUp {@code true} up, {@code false} down */ public void setAllNodesFailureState (boolean setAsUp) { checkIsModifiable(); if (setAsUp) setLinksAndNodesFailureState (null , null , nodes , null); else setLinksAndNodesFailureState (null , null , null , nodes); } /** * <p>Changes the failure state of the links and updates the routes/trees/segments (they do not carry traffic nor occupy capacity), and hop-by-hop routing * (no traffic is forwarded in links down)</p> * @param linksToSetAsUp Links to set as up * @param linksToSetAsDown Links to set as down * @param nodesToSetAsUp Nodes to set as up * @param nodesToSetAsDown Nodes to set as down */ public void setLinksAndNodesFailureState (Collection<Link> linksToSetAsUp , Collection<Link> linksToSetAsDown , Collection<Node> nodesToSetAsUp , Collection<Node> nodesToSetAsDown) { checkIsModifiable(); if (linksToSetAsUp != null) checkInThisNetPlan(linksToSetAsUp); if (linksToSetAsDown != null) checkInThisNetPlan(linksToSetAsDown); if (nodesToSetAsUp != null) checkInThisNetPlan(nodesToSetAsUp); if (nodesToSetAsDown != null) checkInThisNetPlan(nodesToSetAsDown); Set<Link> affectedLinks = new HashSet<Link> (); // System.out.println ("setLinksAndNodesFailureState : links to up: " + linksToSetAsUp + ", links to down: " + linksToSetAsDown + ", nodes up: " + nodesToSetAsUp + ", nodes down: " + nodesToSetAsDown); /* Take all the affected links, including the in/out links of nodes. Update their state up/down and the cache of links and nodes up down, but not the routes, trees etc. */ if (linksToSetAsUp != null) for (Link e : linksToSetAsUp) if (!e.isUp) { e.isUp = true; e.layer.cache_linksDown.remove (e); affectedLinks.add (e); } if (linksToSetAsDown != null) for (Link e : linksToSetAsDown) if (e.isUp) { e.isUp = false; e.layer.cache_linksDown.add (e); affectedLinks.add (e); } if (nodesToSetAsUp != null) for (Node node : nodesToSetAsUp) if (!node.isUp) { node.isUp = true; cache_nodesDown.remove (node); affectedLinks.addAll (node.cache_nodeOutgoingLinks); affectedLinks.addAll (node.cache_nodeIncomingLinks); } if (nodesToSetAsDown != null) for (Node node : nodesToSetAsDown) if (node.isUp) { node.isUp = false; cache_nodesDown.add (node); affectedLinks.addAll (node.cache_nodeOutgoingLinks); affectedLinks.addAll (node.cache_nodeIncomingLinks); } Set<NetworkLayer> affectedLayersHopByHopRouting = new HashSet<NetworkLayer> (); Set<Route> affectedRoutesSourceRouting = new HashSet<Route> (); Set<ProtectionSegment> affectedSegmentsSourceRouting = new HashSet<ProtectionSegment> (); Set<MulticastTree> affectedTrees = new HashSet<MulticastTree> (); for (Link link : affectedLinks) { if (link.layer.routingType == RoutingType.HOP_BY_HOP_ROUTING) { if (affectedLayersHopByHopRouting.contains(link.layer)) continue; affectedLayersHopByHopRouting.add (link.layer); } else { affectedRoutesSourceRouting.addAll (link.cache_traversingRoutes.keySet()); affectedSegmentsSourceRouting.addAll (link.cache_traversingSegments); } affectedTrees.addAll (link.cache_traversingTrees); } // System.out.println ("affected routes: " + affectedRoutesSourceRouting); for (NetworkLayer affectedLayer : affectedLayersHopByHopRouting) for (Demand d : affectedLayer.demands) d.layer.updateHopByHopRoutingDemand(d); netPlan.updateFailureStateRoutesTreesSegments(affectedRoutesSourceRouting); netPlan.updateFailureStateRoutesTreesSegments(affectedSegmentsSourceRouting); netPlan.updateFailureStateRoutesTreesSegments(affectedTrees); if (ErrorHandling.isDebugEnabled()) this.checkCachesConsistency(); } /** * <p>Sets the name of the units in which the offered traffic is measured (e.g. "Gbps") at the given layer. If no layer is provided, default layer is assumed.</p> * @param demandTrafficUnitsName Traffic units name * @param optionalLayerParameter Network layer (optional) */ public void setDemandTrafficUnitsName(String demandTrafficUnitsName , NetworkLayer ... optionalLayerParameter) { checkIsModifiable(); NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); try{ for(Demand d : layer.demands) if (d.coupledUpperLayerLink != null) if (!demandTrafficUnitsName.equals(layer.demandTrafficUnitsName)) throw new Net2PlanException("Demand traffic units name cannot be modified since there is some coupling with other layers"); } catch (Exception e) { e.printStackTrace(); throw e; } layer.demandTrafficUnitsName = demandTrafficUnitsName; } /** * <p>Sets the layer description. If no layer is provided, default layer is used.</p> * @param description Layer description * @param optionalLayerParameter Network layer (optional) */ public void setDescription (String description , NetworkLayer ... optionalLayerParameter) { checkIsModifiable(); NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); layer.description = description; } /** * <p>Adds a new forwarding rule (or override an existing one), to the layer of the demand and link (must be in the same layer).</p> * * <p><b>Important</b>: Routing type must be {@link com.net2plan.utils.Constants.RoutingType#HOP_BY_HOP_ROUTING HOP_BY_HOP_ROUTING}.</p> * @param demand Demand * @param link Link * @param splittingRatio Splitting ratio (fraction of traffic from demand 'd' entering to the origin node of link 'e', going through link 'e'). * Must be equal or greater than 0 and equal or lesser than 1. * @return The previous value of the forwarding rule */ public double setForwardingRule(Demand demand , Link link , double splittingRatio) { checkIsModifiable(); checkInThisNetPlan(demand); final NetworkLayer layer = demand.layer; final double PRECISION_FACTOR = Double.parseDouble(Configuration.getOption("precisionFactor")); checkInThisNetPlanAndLayer(link , demand.layer); layer.checkRoutingType(RoutingType.HOP_BY_HOP_ROUTING); if (splittingRatio < 0) throw new Net2PlanException("Splitting ratio must be greater or equal than zero"); if (splittingRatio > 1) throw new Net2PlanException("Splitting ratio must be lower or equal than one"); double sumOutFde = 0; for (Link e : link.originNode.getOutgoingLinks(layer)) sumOutFde += layer.forwardingRules_f_de.get(demand.index, e.index); final double previousValueFr = layer.forwardingRules_f_de.get(demand.index , link.index); if (sumOutFde + splittingRatio - previousValueFr > 1 + PRECISION_FACTOR) throw new Net2PlanException("The sum of splitting factors for outgoing links cannot exceed one"); layer.forwardingRules_f_de.set(demand.index , link.index , splittingRatio); layer.updateHopByHopRoutingDemand (demand); if (ErrorHandling.isDebugEnabled()) this.checkCachesConsistency(); return previousValueFr; } /** * <p>Adds a set of forwarding rules (or override existing ones). Demands, links and ratio are processed sequentially. All the elements must be in the same layer.</p> * * <p><b>Important</b>: Routing type must be {@link com.net2plan.utils.Constants.RoutingType#HOP_BY_HOP_ROUTING HOP_BY_HOP_ROUTING}.</p> * @param demands Demands * @param links Links * @param splittingFactors Splitting ratios (fraction of traffic from demand 'd' entering to the origin node of link 'e', going through link 'e'). * Each value must be equal or greater than 0 and equal or lesser than 1. * @param includeUnusedRules Inclue {@code true} or not {@code false} unused rules */ public void setForwardingRules(Collection<Demand> demands , Collection<Link> links , Collection<Double> splittingFactors , boolean includeUnusedRules) { checkIsModifiable(); if ((demands.size () != links.size ()) || (demands.size () != splittingFactors.size ())) throw new Net2PlanException ("The number of demands, links and aplitting factors must be the same"); if (demands.isEmpty()) return; NetworkLayer layer = demands.iterator().next().layer; checkInThisNetPlanAndLayer(demands , layer); checkInThisNetPlanAndLayer(links , layer); for (double sf : splittingFactors) if ((sf < 0) || (sf > 1)) throw new Net2PlanException("Splitting ratio must be greater or equal than zero and lower or equal than one"); layer.checkRoutingType(RoutingType.HOP_BY_HOP_ROUTING); final double PRECISION_FACTOR = Double.parseDouble(Configuration.getOption("precisionFactor")); DoubleMatrix2D original_fde = layer.forwardingRules_f_de.copy(); Iterator<Demand> it_d = demands.iterator(); Iterator<Link> it_e = links.iterator(); Iterator<Double> it_sf = splittingFactors.iterator(); Set<Demand> modifiedDemands = new HashSet<Demand> (); while (it_d.hasNext()) { final Demand demand = it_d.next (); final Link link = it_e.next (); final double splittingFactor = it_sf.next(); if (includeUnusedRules || (splittingFactor > 1E-5)) { if (splittingFactor != layer.forwardingRules_f_de.get(demand.index , link.index)) { layer.forwardingRules_f_de.set(demand.index , link.index , splittingFactor); modifiedDemands.add (demand); } } } DoubleMatrix2D A_dn = layer.forwardingRules_f_de.zMult(layer.forwardingRules_Aout_ne , null , 1 , 0 , false , true); // traffic of demand d that leaves node n if (A_dn.size() > 0) if (A_dn.getMaxLocation() [0] > 1 + PRECISION_FACTOR) { layer.forwardingRules_f_de = original_fde; throw new Net2PlanException ("The sum of the splitting factors of the output links of a node cannot exceed one"); } for (Demand demand : modifiedDemands) layer.updateHopByHopRoutingDemand (demand); if (ErrorHandling.isDebugEnabled()) this.checkCachesConsistency(); } /** * <p>Sets the forwarding rules for the given design. Any previous routing * information (either source routing or hop-by-hop routing) will be removed.</p> * @param f_de For each demand <i>d</i> (<i>d = 0</i> refers to the first demand in {@code demandIds}, <i>d = 1</i> * refers to the second one, and so on), and each link <i>e</i> (<i>e = 0</i> refers to the first link in {@code NetPlan} object, <i>e = 1</i> * refers to the second one, and so on), {@code f_de[d][e]} sets the fraction of the traffic from demand <i>d</i> that arrives (or is generated in) node <i>a(e)</i> (the origin node of link <i>e</i>), that is forwarded through link <i>e</i>. It must hold that for every node <i>n</i> different of <i>b(d)</i>, the sum of the fractions <i>f<sub>te</sub></i> along its outgoing links must be lower or equal than 1 * @param optionalLayerParameter Network layer (optional) */ public void setForwardingRules(DoubleMatrix2D f_de , NetworkLayer ... optionalLayerParameter) { checkIsModifiable(); NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); layer.checkRoutingType(RoutingType.HOP_BY_HOP_ROUTING); int D = layer.demands.size (); int E = layer.links.size (); if (f_de.rows() != D || f_de.columns() != E) throw new Net2PlanException("'f_de' should be a " + D + " x" + E + " matrix (demands x links)"); if ((D == 0) || (E == 0)) { layer.forwardingRules_f_de = f_de; return; } if ((D > 0) && (E > 0)) if ((f_de.getMinLocation() [0] < -1e-3) || (f_de.getMaxLocation() [0] > 1 + 1e-3)) throw new Net2PlanException("Splitting ratios must be greater or equal than zero and lower or equal than one"); final double PRECISION_FACTOR = Double.parseDouble(Configuration.getOption("precisionFactor")); DoubleMatrix2D A_dn = layer.forwardingRules_f_de.zMult(layer.forwardingRules_Aout_ne , null , 1 , 0 , false , true); // traffic of demand d that leaves node n if (A_dn.size () > 0) if (A_dn.getMaxLocation() [0] > 1 + PRECISION_FACTOR) throw new Net2PlanException ("The sum of the splitting factors of the output links of a node cannot exceed one"); layer.forwardingRules_f_de = f_de; for (Demand d : layer.demands) layer.updateHopByHopRoutingDemand(d); if (ErrorHandling.isDebugEnabled()) this.checkCachesConsistency(); } /** * <p>Sets the name of the units in which the link capacity is measured (e.g. "Gbps") at the given layer. If no ayer is provided, the default layer is assumed.</p> * @param name Capacity units name * @param optionalLayerParameter Network layer (optional) */ public void setLinkCapacityUnitsName(String name , NetworkLayer ... optionalLayerParameter) { checkIsModifiable(); NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); try{ for(Link e : layer.links) if ((e.coupledLowerLayerDemand != null) || (e.coupledLowerLayerMulticastDemand != null)) if (!name.equals(layer.linkCapacityUnitsName)) { throw new Net2PlanException("Link capacity units name cannot be modified since there is some coupling with other layers"); } } catch (Exception e) { e.printStackTrace(); throw e; } layer.linkCapacityUnitsName = name; } /** * <p>Sets the network description.</p> * * @param description Description (when {@code null}, it will be set to empty) * @since 0.2.3 */ public void setNetworkDescription(String description) { checkIsModifiable(); networkDescription = description == null ? "" : description; } /** * <p>Sets the default network layer.</p> * @param layer The default network layer */ public void setNetworkLayerDefault (NetworkLayer layer) { checkInThisNetPlan(layer); this.defaultLayer = layer; } /** * <p>Sets the network name.</p> * * @param name Name * @since 0.2.3 */ public void setNetworkName(String name) { checkIsModifiable(); networkName = name == null ? "" : name; } /** * <p>Checks the flow conservation constraints, and returns the traffic carried per demand.</p> * @param x_de Amount of traffic from demand {@code d} (i-th row) transmitted through link e (j-th column) in traffic units * @param xdeValueAsFractionsRespectToDemandOfferedTraffic If {@code true}, {@code x_de} values are measured as fractions [0,1] instead of traffic units * @param optionalLayerParameter Network layer (optional) * @return Carried traffic per demand (i-th position is the demand index and the value is the carried traffic) */ public DoubleMatrix1D checkMatrixDemandLinkCarriedTrafficFlowConservationConstraints (DoubleMatrix2D x_de , boolean xdeValueAsFractionsRespectToDemandOfferedTraffic , NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); final double PRECISION_FACTOR = Double.parseDouble(Configuration.getOption("precisionFactor")); if ((x_de.rows() != layer.demands.size()) || (x_de.columns() != layer.links.size ())) throw new Net2PlanException ("Wrong size of x_de matrix"); if (x_de.size () > 0) if (x_de.getMinLocation() [0] < -PRECISION_FACTOR) throw new Net2PlanException ("Carried traffics cannot be negative"); final DoubleMatrix2D trafficBased_xde = xdeValueAsFractionsRespectToDemandOfferedTraffic? DoubleFactory2D.sparse.diagonal(getVectorDemandOfferedTraffic(layer)).zMult (x_de , null) : x_de; final DoubleMatrix2D A_ne = netPlan.getMatrixNodeLinkIncidence(layer); final DoubleMatrix2D Div_dn = trafficBased_xde.zMult (A_ne.viewDice () , null); // out traffic minus in traffic of demand d in node n DoubleMatrix1D r_d = DoubleFactory1D.dense.make (layer.demands.size ()); for (Demand d : layer.demands) { final double outTrafficOfIngress = Div_dn.get(d.index , d.ingressNode.index); final double outTrafficOfEgress = Div_dn.get(d.index , d.egressNode.index); if (outTrafficOfIngress < -PRECISION_FACTOR) throw new Net2PlanException ("Flow conservation constraints are not met for this matrix (demand index " + d.index + ")"); if (outTrafficOfEgress > PRECISION_FACTOR) throw new Net2PlanException ("Flow conservation constraints are not met for this matrix (demand index " + d.index + ")"); if (Math.abs(outTrafficOfIngress + outTrafficOfEgress) > PRECISION_FACTOR) throw new Net2PlanException ("Flow conservation constraints are not met for this matrix (demand index " + d.index + ")"); IntArrayList ns = new IntArrayList (); DoubleArrayList vals = new DoubleArrayList (); Div_dn.viewRow (d.index).getNonZeros(ns , vals); for (int cont = 0; cont < ns.size () ; cont ++) { final double divergence = vals.get(cont); final int n = ns.get (cont); if ((divergence > PRECISION_FACTOR) && (n != d.ingressNode.index)) throw new Net2PlanException ("Flow conservation constraints are not met for this matrix (demand index " + d.index + ")"); if ((divergence < -PRECISION_FACTOR) && (n != d.egressNode.index)) throw new Net2PlanException ("Flow conservation constraints are not met for this matrix (demand index " + d.index + ")"); } r_d.set(d.index , outTrafficOfIngress); } return r_d; } /** * <p>Checks the flow conservation constraints, and returns the traffic carried per input output node pair.</p> * @param x_te Amount of traffic targeted to node {@code t} (i-th row) transmitted through link e (j-th column) in traffi units * @param optionalLayerParameter Network layer (optional) * @return Carried traffic per input (i-th row) output (j-th column) node pair */ public DoubleMatrix2D checkMatrixDestinationLinkCarriedTrafficFlowConservationConstraints (DoubleMatrix2D x_te , NetworkLayer ... optionalLayerParameter) { NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); final double PRECISION_FACTOR = Double.parseDouble(Configuration.getOption("precisionFactor")); if ((x_te.rows() != nodes.size()) || (x_te.columns() != layer.links.size ())) throw new Net2PlanException ("Wrong size of x_te matrix"); if (x_te.size () > 0) if (x_te.getMinLocation() [0] < -PRECISION_FACTOR) throw new Net2PlanException ("Carried traffics cannot be negative"); final DoubleMatrix2D A_ne = netPlan.getMatrixNodeLinkIncidence(layer); DoubleMatrix2D h_st = DoubleFactory2D.dense.make (nodes.size () , nodes.size ()); final DoubleMatrix2D Div_tn = x_te.zMult (A_ne.viewDice () , null); // out traffic minus in traffic of demand d in node n for (Node t : nodes) for (Node n : nodes) { final double h_nt = Div_tn.get(t.index,n.index); if ((t == n) && (h_nt > PRECISION_FACTOR)) throw new Net2PlanException ("Flow conservation constraints are not met for this matrix (destination index " + t.index + ", node index " + n.index + ")"); else if ((t != n) && (h_nt < -PRECISION_FACTOR)) throw new Net2PlanException ("Flow conservation constraints are not met for this matrix (destination index " + t.index + ", node index " + n.index + ")"); h_st.set (n.index , t.index , h_nt); } return h_st; } /** * <p>Adds traffic routes (or forwarding rules, depending on the routing type) from demand-link routing at the given layer. * If no layer is provided, default layer is assumed. If the routing is SOURCE-ROUTING, the new routing will have no closed nor open loops. If the routing is * HOP-BY-HOP routing, the new routing can have open loops. However, if the routing has closed loops (which were not removed), a {@code ClosedCycleRoutingException} * will be thrown.</p> * @param x_de Matrix containing the amount of traffic from demand <i>d</i> (rows) which traverses link <i>e</i> (columns) * @param xdeValueAsFractionsRespectToDemandOfferedTraffic If {@code true}, {code x_de} contains the fraction of the carried traffic (between 0 and 1) * @param removeCycles If true, the open and closed loops are eliminated from the routing before any processing is done. The form in which this is done guarantees that the resulting * routing uses the same or less traffic in the links for each destination than the original routing. For removing the cycles, * the method calls to {@code removeCyclesFrom_xte} using the default ILP solver defined in Net2Plan, and no limit in the maximum solver running time. * @param optionalLayerParameter Network layer (optional) */ public void setRoutingFromDemandLinkCarriedTraffic(DoubleMatrix2D x_de , boolean xdeValueAsFractionsRespectToDemandOfferedTraffic , boolean removeCycles , NetworkLayer ... optionalLayerParameter) { checkIsModifiable(); NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); final DoubleMatrix2D trafficBased_xde = xdeValueAsFractionsRespectToDemandOfferedTraffic? DoubleFactory2D.sparse.diagonal(getVectorDemandOfferedTraffic(layer)).zMult (x_de , null) : x_de; checkMatrixDemandLinkCarriedTrafficFlowConservationConstraints (trafficBased_xde , false , layer); if (removeCycles) x_de = GraphUtils.removeCyclesFrom_xde(nodes, layer.links, layer.demands, x_de, xdeValueAsFractionsRespectToDemandOfferedTraffic , Configuration.getOption("defaultILPSolver") , null, -1); if (layer.routingType == RoutingType.SOURCE_ROUTING) { removeAllRoutes(layer); removeAllProtectionSegments(layer); /* Convert the x_de variables into a set of routes for each demand */ List<Demand> demands = new LinkedList<Demand>(); List<Double> x_p = new LinkedList<Double>(); List<List<Link>> seqLinks = new LinkedList<List<Link>>(); GraphUtils.convert_xde2xp(nodes , layer.links , layer.demands , trafficBased_xde , demands, x_p, seqLinks); /* Update netPlan object adding the calculated routes */ Iterator<Demand> demands_it = demands.iterator(); Iterator<List<Link>> seqLinks_it = seqLinks.iterator(); Iterator<Double> x_p_it = x_p.iterator(); while(x_p_it.hasNext()) { Demand demand = demands_it.next(); List<Link> seqLinks_thisPath = seqLinks_it.next(); double x_p_thisPath = x_p_it.next(); addRoute(demand , x_p_thisPath , x_p_thisPath , seqLinks_thisPath, null); } } else if (layer.routingType == RoutingType.HOP_BY_HOP_ROUTING) { DoubleMatrix2D f_de = GraphUtils.convert_xde2fde(nodes , layer.links , layer.demands , trafficBased_xde); setForwardingRules(f_de, layer); } else throw new RuntimeException ("Bad"); if (ErrorHandling.isDebugEnabled()) this.checkCachesConsistency(); } /** * <p>Adds traffic routes (or forwarding rules, depending on the routing type) from destination-link routing at the given layer. * If no layer is provided, default layer is assumed. If the routing is SOURCE-ROUTING, the new routing will have no closed nor open loops. If the routing is * HOP-BY-HOP routing, the new routing can have open loops. However, if the routing has closed loops (which were not removed), a {@code ClosedCycleRoutingException} * will be thrown </p> * @param x_te For each destination node <i>t</i> (rows), and each link <i>e</i> (columns), {@code f_te[t][e]} represents the traffic targeted to node <i>t</i> that arrives (or is generated * in) node a(e) (the origin node of link e), that is forwarded through link e * @param removeCycles If true, the open and closed loops are eliminated from the routing before any processing is done. The form in which this is done guarantees that the resulting * routing uses the same or less traffic in the links for each destination than the original routing. For removing the cycles, * the method calls to {@code removeCyclesFrom_xte} using the default ILP solver defined in Net2Plan, and no limit in the maximum solver running time. * @param optionalLayerParameter Network layer (optional) */ public void setRoutingFromDestinationLinkCarriedTraffic(DoubleMatrix2D x_te , boolean removeCycles , NetworkLayer ... optionalLayerParameter) { checkIsModifiable(); NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); checkMatrixDestinationLinkCarriedTrafficFlowConservationConstraints(x_te , layer); if (removeCycles) x_te = GraphUtils.removeCyclesFrom_xte(nodes, layer.links, getMatrixNode2NodeOfferedTraffic(layer), x_te, Configuration.getOption("defaultILPSolver") , null, -1); if (layer.routingType == RoutingType.SOURCE_ROUTING) { removeAllRoutes(layer); removeAllProtectionSegments(layer); /* Convert the x_te variables into a set of routes for each demand */ DoubleMatrix2D f_te = GraphUtils.convert_xte2fte(nodes , layer.links , x_te); List<Demand> demands_p = new LinkedList<Demand>(); List<Double> x_p = new LinkedList<Double>(); List<List<Link>> seqLinks_p = new LinkedList<List<Link>>(); GraphUtils.convert_fte2xp(nodes , layer.links , layer.demands , getVectorDemandOfferedTraffic(layer) , f_te, demands_p, x_p, seqLinks_p); /* Update netPlan object adding the calculated routes */ Iterator<Demand> demands_it = demands_p.iterator(); Iterator<Double> x_p_it = x_p.iterator(); Iterator<List<Link>> seqLinks_it = seqLinks_p.iterator(); while(x_p_it.hasNext()) { Demand demand = demands_it.next(); List<Link> seqLinks_thisPath = seqLinks_it.next(); double x_p_thisPath = x_p_it.next(); addRoute(demand , x_p_thisPath , x_p_thisPath , seqLinks_thisPath, null); } } else if (layer.routingType == RoutingType.HOP_BY_HOP_ROUTING) { DoubleMatrix2D f_te = GraphUtils.convert_xte2fte(nodes , layer.links , x_te); DoubleMatrix2D f_de = GraphUtils.convert_fte2fde(layer.demands , f_te); setForwardingRules(f_de, layer); } else throw new RuntimeException ("Bad"); if (ErrorHandling.isDebugEnabled()) this.checkCachesConsistency(); } /** * <p>Sets the routing type at the given layer. If there is some previous routing information, it * will be converted to the new type. If no layer is provided, default layer is assumed. In the conversion from * HOP-BY-HOP to SOURCE-ROUTING: (i) the demands with open loops are routed so these loops are removed, and the resulting * routing consumes the same or less bandwidth in the demand traversed links, (ii) the demands with closed loops are * routed so that the traffic that enters the closed loops is not carried. These modifications are done since open or close * loops would require routes with an infinite number of links to be fairly represented.</p> * * @param optionalLayerParameter Network layer (optional) * @param newRoutingType {@link com.net2plan.utils.Constants.RoutingType RoutingType} */ public void setRoutingType(RoutingType newRoutingType , NetworkLayer ... optionalLayerParameter) { checkIsModifiable(); NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); if (layer.routingType == newRoutingType) return; switch(newRoutingType) { case HOP_BY_HOP_ROUTING: { layer.forwardingRules_x_de = GraphUtils.convert_xp2xde(layer.links, layer.demands, layer.routes); layer.forwardingRules_Aout_ne = this.getMatrixNodeLinkOutgoingIncidence(layer); layer.forwardingRules_Ain_ne = this.getMatrixNodeLinkIncomingIncidence(layer); layer.forwardingRules_f_de = DoubleFactory2D.sparse.make (layer.demands.size(),layer.links.size ()); DoubleMatrix2D A_dn = layer.forwardingRules_x_de.zMult(layer.forwardingRules_Aout_ne , null , 1 , 0 , false , true); // traffic of demand d that leaves node n removeAllProtectionSegments(layer); removeAllRoutes(layer); layer.routingType = RoutingType.HOP_BY_HOP_ROUTING; IntArrayList ds = new IntArrayList(); IntArrayList es = new IntArrayList(); DoubleArrayList trafs = new DoubleArrayList(); layer.forwardingRules_x_de.getNonZeros(ds , es , trafs); for (int cont = 0 ; cont < ds.size() ; cont ++) { final int d = ds.get(cont); final int e = es.get(cont); double outTraf = A_dn.get (d , layer.links.get(e).originNode.index); layer.forwardingRules_f_de.set (d , e , outTraf == 0? 0 : trafs.get(cont) / outTraf ); } /* update link and demand carried traffics, and demand routing cycle type */ layer.forwardingRules_x_de.assign(0); // this is recomputed inside next call for (Demand d : layer.demands) layer.updateHopByHopRoutingDemand(d); break; } case SOURCE_ROUTING: { layer.routingType = RoutingType.SOURCE_ROUTING; removeAllRoutes(layer); removeAllProtectionSegments(layer); for (Link e : layer.links) { e.carriedTrafficSummingRoutesAndCarriedTrafficByProtectionSegments = e.getMulticastCarriedTraffic(); e.occupiedCapacitySummingRoutesAndCarriedTrafficByProtectionSegments = e.getMulticastOccupiedLinkCapacity(); } for (Demand d : layer.demands) d.carriedTraffic = 0; List<Demand> d_p = new LinkedList<Demand> (); List<Double> x_p = new LinkedList<Double> (); List<List<Link>> pathList = new LinkedList<List<Link>> (); GraphUtils.convert_xde2xp(nodes, layer.links , layer.demands , layer.forwardingRules_x_de , d_p, x_p, pathList); Iterator<Demand> it_demand = d_p.iterator(); Iterator<Double> it_xp = x_p.iterator(); Iterator<List<Link>> it_pathList = pathList.iterator(); while (it_demand.hasNext()) { final Demand d = it_demand.next(); final double trafficInPath = it_xp.next(); final List<Link> seqLinks = it_pathList.next(); addRoute(d, trafficInPath , trafficInPath , seqLinks , null); } // final double PRECISION_FACTOR = Double.parseDouble(Configuration.getOption("precisionFactor")); // final int E = layer.links.size (); // Graph<Node, Link> graph = JUNGUtils.getGraphFromLinkMap(nodes , layer.links); // Transformer<Link, Double> nev = JUNGUtils.getEdgeWeightTransformer(null); // for (Demand demand : layer.demands) // { // Node ingressNode = demand.getIngressNode(); // Node egressNode = demand.getEgressNode(); // DoubleMatrix1D x_e = layer.forwardingRules_x_de.viewRow(demand.getIndex()).copy(); // // Collection<Link> incomingLinksToIngressNode = graph.getInEdges(ingressNode); // Collection<Link> outgoingLinksFromIngressNode = graph.getOutEdges(ingressNode); // if (incomingLinksToIngressNode == null) incomingLinksToIngressNode = new LinkedHashSet<Link>(); // if (outgoingLinksFromIngressNode == null) outgoingLinksFromIngressNode = new LinkedHashSet<Link>(); // // double divAtIngressNode = 0; // for(Link link : outgoingLinksFromIngressNode) // divAtIngressNode += x_e.get(link.getIndex()); // // for(Link link : incomingLinksToIngressNode) // divAtIngressNode -= x_e.get(link.getIndex()); // // while (divAtIngressNode > PRECISION_FACTOR) // { // List<Link> candidateLinks = new LinkedList<Link>(); for (int e = 0; e < E ; e ++) if (x_e.get(e) > 0)candidateLinks.add(layer.links.get(e)); // if (candidateLinks.isEmpty()) break; // // Graph<Node, Link> auxGraph = JUNGUtils.filterGraph(graph, null, null, candidateLinks, null); // List<Link> seqLinks = JUNGUtils.getShortestPath(auxGraph, nev, ingressNode, egressNode); // if (seqLinks.isEmpty()) break; // // double trafficInPath = Double.MAX_VALUE; // for(Link link : seqLinks) trafficInPath = Math.min(trafficInPath, x_e.get(link.getIndex())); // // trafficInPath = Math.min(trafficInPath, divAtIngressNode); // divAtIngressNode -= trafficInPath; // // addRoute(demand, trafficInPath , trafficInPath , seqLinks , null); // // for (Link link : seqLinks) // { // double newTrafficValue_thisLink = x_e.get(link.getIndex()) - trafficInPath; // if (newTrafficValue_thisLink < PRECISION_FACTOR) x_e.set(link.getIndex() , 0); // else x_e.set(link.getIndex(), newTrafficValue_thisLink); // } // // if (divAtIngressNode <= PRECISION_FACTOR) break; // } // } /* Remove previous 'hop-by-hop' routing information */ layer.forwardingRules_f_de = null; layer.forwardingRules_x_de = null; layer.forwardingRules_Ain_ne = null; layer.forwardingRules_Aout_ne = null; break; } default: throw new RuntimeException("Bad - Unknown routing type " + newRoutingType); } if (ErrorHandling.isDebugEnabled()) this.checkCachesConsistency(); } /** * <p>Sets the traffic demands at the given layer from a given traffic matrix, removing any previous * demand. If no layer is provided, default layer is assumed.</p> * * <p><b>Important</b>: Matrix values must be strictly non-negative and matrix size have to be <i>N</i>x<i>N</i> (where <i>N</i> is the number of nodes) * * @param optionalLayerParameter Network layer (optional * @param trafficMatrix Traffic matrix * @since 0.3.1 */ public void setTrafficMatrix(DoubleMatrix2D trafficMatrix, NetworkLayer ... optionalLayerParameter) { trafficMatrix = NetPlan.adjustToTolerance(trafficMatrix); checkIsModifiable(); NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); removeAllDemands(layer); int N = nodes.size (); if ((trafficMatrix.rows () != N) || (trafficMatrix.columns() != N)) throw new Net2PlanException ("Bad number of rows-columns in the traffic matrix"); if (trafficMatrix.size () > 0) if (trafficMatrix.getMinLocation() [0] < 0) throw new Net2PlanException ("Offered traffic must be a non-negative"); for (int n1 = 0 ; n1 < N ; n1 ++) for (int n2 = 0 ; n2 < N ; n2 ++) { if (n1 == n2) continue; addDemand(nodes.get(n1) , nodes.get(n2) , trafficMatrix.getQuick(n1, n2), null , layer); } if (ErrorHandling.isDebugEnabled()) this.checkCachesConsistency(); } /** * <p>Sets the vector of the offered traffic per demand, at the given layer. i-th vector corresponds to i-th index of the element. If no layer is provided, * the defaulf layer is assumed.</p> * @param offeredTrafficVector Offered traffic vector * @param optionalLayerParameter Network layer (optional) */ public void setVectorDemandOfferedTraffic(DoubleMatrix1D offeredTrafficVector , NetworkLayer ... optionalLayerParameter) { offeredTrafficVector = NetPlan.adjustToTolerance(offeredTrafficVector); checkIsModifiable(); NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); if (offeredTrafficVector.size() != layer.demands.size()) throw new Net2PlanException ("Wrong veector size"); if (offeredTrafficVector.size () > 0) if (offeredTrafficVector.getMinLocation() [0] < 0) throw new Net2PlanException("Offered traffic must be greater or equal than zero"); for (Demand d : layer.demands) { d.offeredTraffic = offeredTrafficVector.get (d.index); if (layer.routingType == RoutingType.HOP_BY_HOP_ROUTING) layer.updateHopByHopRoutingDemand(d); } if (ErrorHandling.isDebugEnabled()) this.checkCachesConsistency(); } /** * <p>Sets the vector of the link capacities, at the given layer. i-th vector corresponds to i-th index of the element. If no layer is provided, the defaulf layer is assumed.</p> * @param linkCapacities Link capacities * @param optionalLayerParameter Network layer (optional) */ public void setVectorLinkCapacity (DoubleMatrix1D linkCapacities , NetworkLayer ... optionalLayerParameter) { linkCapacities = NetPlan.adjustToTolerance(linkCapacities); checkIsModifiable(); NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); if (linkCapacities.size() != layer.links.size()) throw new Net2PlanException ("Wrong veector size"); if (linkCapacities.size () > 0) if (linkCapacities.getMinLocation() [0] < 0) throw new Net2PlanException("Link capacities must be greater or equal than zero"); for (Link e : layer.links) if ((e.coupledLowerLayerDemand != null) || (e.coupledLowerLayerMulticastDemand != null)) throw new Net2PlanException ("Coupled links cannot change its capacity"); for (Link e : layer.links) e.capacity = linkCapacities.get (e.index); if (ErrorHandling.isDebugEnabled()) this.checkCachesConsistency(); } /** * <p>Sets the vector of the offered traffic per multicast demand, at the given layer. i-th vector corresponds to i-th index of the element. If no layer is provided, the defaulf layer is * assumed.</p> * @param offeredTrafficVector Offered traffic vector * @param optionalLayerParameter Network layer (optional) */ public void setVectorMulticastDemandOfferedTraffic(DoubleMatrix1D offeredTrafficVector , NetworkLayer ... optionalLayerParameter) { offeredTrafficVector = NetPlan.adjustToTolerance(offeredTrafficVector); checkIsModifiable(); NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); if (offeredTrafficVector.size() != layer.multicastDemands.size()) throw new Net2PlanException ("Wrong veector size"); if (offeredTrafficVector.size () > 0) if (offeredTrafficVector.getMinLocation() [0] < 0) throw new Net2PlanException("Offered traffic must be greater or equal than zero"); for (MulticastDemand d : layer.multicastDemands) d.offeredTraffic = offeredTrafficVector.get (d.index); if (ErrorHandling.isDebugEnabled()) this.checkCachesConsistency(); } /** * <p>Sets the vector of the multicast trees carried traffics and occupied link capacities, at the given layer. i-th vector corresponds to i-th index of the element. * If occupied link capacities are {@code null}, the same amount as the carried traffic is assumed. If no layer is provided, the defaulf layer is assumed.</p> * @param carriedTraffic Carried traffic vector * @param occupiedLinkCapacity Occupied link capacity vector * @param optionalLayerParameter Network layer (optional) */ public void setVectorMulticastTreeCarriedTrafficAndOccupiedLinkCapacities (DoubleMatrix1D carriedTraffic , DoubleMatrix1D occupiedLinkCapacity , NetworkLayer ... optionalLayerParameter) { carriedTraffic = NetPlan.adjustToTolerance(carriedTraffic); occupiedLinkCapacity = NetPlan.adjustToTolerance(occupiedLinkCapacity); checkIsModifiable(); NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); if (occupiedLinkCapacity == null) occupiedLinkCapacity = carriedTraffic; if (carriedTraffic.size() != layer.multicastTrees.size()) throw new Net2PlanException ("Wrong veector size"); if (carriedTraffic.size() != occupiedLinkCapacity.size()) throw new Net2PlanException ("Wrong veector size"); if (carriedTraffic.size () > 0) if (carriedTraffic.getMinLocation() [0] < 0) throw new Net2PlanException("Carried traffics must be greater or equal than zero"); if (occupiedLinkCapacity.size () > 0) if (occupiedLinkCapacity.getMinLocation() [0] < 0) throw new Net2PlanException("Occupied link capacities must be greater or equal than zero"); for (MulticastTree t : layer.multicastTrees) t.setCarriedTraffic(carriedTraffic.get (t.index) , occupiedLinkCapacity.get(t.index)); if (ErrorHandling.isDebugEnabled()) this.checkCachesConsistency(); } /** * <p>Sets the vector of the reserved capacity for protection segments, at the given layer. i-th vector corresponds to i-th index of the element. If no layer is provided, the defaulf layer is * assumed.</p> * @param segmentCapacities Protection segment reserved capacities vector * @param optionalLayerParameter Network layer (optional) */ public void setVectorProtectionSegmentReservedCapacity (DoubleMatrix1D segmentCapacities , NetworkLayer ... optionalLayerParameter) { segmentCapacities = NetPlan.adjustToTolerance(segmentCapacities); checkIsModifiable(); NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); if (segmentCapacities.size() != layer.protectionSegments.size()) throw new Net2PlanException ("Wrong veector size"); if (segmentCapacities.size () > 0) if (segmentCapacities.getMinLocation() [0] < 0) throw new Net2PlanException("Protection segment reserved capacities must be greater or equal than zero"); layer.checkRoutingType(RoutingType.SOURCE_ROUTING); for (ProtectionSegment s : layer.protectionSegments) s.capacity = segmentCapacities.get (s.index); if (ErrorHandling.isDebugEnabled()) this.checkCachesConsistency(); } /** * <p>Sets the vector of the route carried traffics and occupied link capacities, at the given layer. i-th vector corresponds to i-th index of the element. * If occupied link capacities are {@code null}, the same amount as the carried traffic is assumed. If no layer is provided, the defaulf layer is assumed,</p> * @param carriedTraffic Carried traffic vector * @param occupiedLinkCapacity Occupied link capacity vector * @param optionalLayerParameter Network layer (optional) */ public void setVectorRouteCarriedTrafficAndOccupiedLinkCapacities (DoubleMatrix1D carriedTraffic , DoubleMatrix1D occupiedLinkCapacity , NetworkLayer ... optionalLayerParameter) { carriedTraffic = NetPlan.adjustToTolerance(carriedTraffic); occupiedLinkCapacity = NetPlan.adjustToTolerance(occupiedLinkCapacity); checkIsModifiable(); NetworkLayer layer = checkInThisNetPlanOptionalLayerParameter(optionalLayerParameter); if (occupiedLinkCapacity == null) occupiedLinkCapacity = carriedTraffic; if (carriedTraffic.size() != layer.routes.size()) throw new Net2PlanException ("Wrong veector size"); if (carriedTraffic.size() != occupiedLinkCapacity.size()) throw new Net2PlanException ("Wrong veector size"); if (carriedTraffic.size () > 0) if (carriedTraffic.getMinLocation() [0] < 0) throw new Net2PlanException("Carried traffics must be greater or equal than zero"); if (occupiedLinkCapacity.size () > 0) if (occupiedLinkCapacity.getMinLocation() [0] < 0) throw new Net2PlanException("Occupied link capacities must be greater or equal than zero"); layer.checkRoutingType(RoutingType.SOURCE_ROUTING); for (Route r : layer.routes) r.setCarriedTraffic(carriedTraffic.get (r.index) , occupiedLinkCapacity.get(r.index)); if (ErrorHandling.isDebugEnabled()) this.checkCachesConsistency(); } /** * Returns a {@code String} representation of the network design. * * @return String representation of the network design * @since 0.2.0 */ @Override public String toString() { return toString(layers); } /** * Returns a {@code String} representation of the network design only for the * given layers. * * @param layers Network layers * @return String representation of the network design */ public String toString(Collection<NetworkLayer> layers) { StringBuilder netPlanInformation = new StringBuilder(); String NEWLINE = StringUtils.getLineSeparator(); int N = nodes.size (); if (N == 0) { netPlanInformation.append("Empty network"); // return netPlanInformation.toString(); } int L = getNumberOfLayers(); int numSRGs = getNumberOfSRGs(); netPlanInformation.append("Network information"); netPlanInformation.append(NEWLINE); netPlanInformation.append("--------------------------------"); netPlanInformation.append(NEWLINE).append(NEWLINE); netPlanInformation.append("Name: ").append(this.networkName).append(NEWLINE); netPlanInformation.append("Description: ").append(networkDescription).append(NEWLINE); Map<String, String> networkAttributes_thisNetPlan = this.attributes; netPlanInformation.append("Attributes: "); netPlanInformation.append(networkAttributes_thisNetPlan.isEmpty() ? "none" : StringUtils.mapToString(networkAttributes_thisNetPlan, "=", ", ")); netPlanInformation.append(NEWLINE); netPlanInformation.append("Number of layers: ").append(L).append(NEWLINE); netPlanInformation.append("Default layer: ").append(defaultLayer.id).append(NEWLINE); netPlanInformation.append("Number of nodes: ").append(N).append(NEWLINE); netPlanInformation.append("Number of SRGs: ").append(numSRGs).append(NEWLINE); netPlanInformation.append(NEWLINE); netPlanInformation.append("Node information"); netPlanInformation.append(NEWLINE); netPlanInformation.append("--------------------------------"); netPlanInformation.append(NEWLINE).append(NEWLINE); for (Node node : nodes) { String nodeInformation = String.format("n%d (id %d), state: %s, position: (%.3g, %.3g), name: %s, attributes: %s", node.index , node.id , !node.isUp ? "down" : "up", node.nodeXYPositionMap.getX(), node.nodeXYPositionMap.getY(), node.name , node.attributes.isEmpty() ? "none" : node.attributes); netPlanInformation.append(nodeInformation); netPlanInformation.append(NEWLINE); } for (NetworkLayer layer : layers) { netPlanInformation.append(NEWLINE); netPlanInformation.append("Layer ").append(layer.index + " (id: " + layer.id + ")").append(" information"); netPlanInformation.append(NEWLINE); netPlanInformation.append("--------------------------------"); netPlanInformation.append(NEWLINE).append(NEWLINE); netPlanInformation.append("Name: ").append(layer.name).append(NEWLINE); netPlanInformation.append("Description: ").append(layer.description).append(NEWLINE); netPlanInformation.append("Link capacity units: ").append(layer.linkCapacityUnitsName).append(NEWLINE); netPlanInformation.append("Demand traffic units: ").append(layer.demandTrafficUnitsName).append(NEWLINE); netPlanInformation.append("Routing type: ").append(layer.routingType).append(NEWLINE); if (!layer.attributes.isEmpty()) { netPlanInformation.append("Attributes: "); netPlanInformation.append(StringUtils.mapToString(layer.attributes , "=", ", ")); netPlanInformation.append(NEWLINE); } netPlanInformation.append("Number of links: ").append(layer.links.size ()).append(NEWLINE); netPlanInformation.append("Number of demands: ").append(layer.demands.size ()).append(NEWLINE); netPlanInformation.append("Number of multicast demands: ").append(layer.multicastDemands.size ()).append(NEWLINE); netPlanInformation.append("Number of multicast trees: ").append(layer.multicastTrees.size ()).append(NEWLINE); if (layer.routingType == RoutingType.SOURCE_ROUTING) { netPlanInformation.append("Number of routes: ").append(layer.routes.size ()).append(NEWLINE); netPlanInformation.append("Number of protection segments: ").append(layer.protectionSegments.size ()).append(NEWLINE); } if (!layer.links.isEmpty()) { netPlanInformation.append(NEWLINE); netPlanInformation.append("Link information"); netPlanInformation.append(NEWLINE); netPlanInformation.append("--------------------------------"); netPlanInformation.append(NEWLINE).append(NEWLINE); for (Link link : layer.links) { String linkInformation = String.format("e%d (id %d), n%d (%s) -> n%d (%s), state: %s, capacity: %.3g, length: %.3g km, propagation speed: %.3g km/s, carried traffic (incl. segments): %.3g , occupied capacity (incl. traffic in segments): %.3g, attributes: %s", link.index, link.id , link.originNode.id, link.originNode.name, link.destinationNode.id, link.destinationNode.name , !link.isUp? "down" : "up", link.capacity , link.lengthInKm , link.propagationSpeedInKmPerSecond, link.carriedTrafficSummingRoutesAndCarriedTrafficByProtectionSegments , link.occupiedCapacitySummingRoutesAndCarriedTrafficByProtectionSegments , link.attributes.isEmpty() ? "none" : link.attributes); netPlanInformation.append(linkInformation); if (link.coupledLowerLayerDemand != null) netPlanInformation.append(String.format(", associated to demand %d (id %d) at layer %d (id %d)", link.coupledLowerLayerDemand.index , link.coupledLowerLayerDemand.id , link.coupledLowerLayerDemand.layer.index , link.coupledLowerLayerDemand.layer.id)); if (link.coupledLowerLayerMulticastDemand != null) netPlanInformation.append(String.format(", associated to multicast demand %d (id %d) at layer %d (id %d)", link.coupledLowerLayerMulticastDemand.index , link.coupledLowerLayerMulticastDemand.id , link.coupledLowerLayerMulticastDemand.layer.index , link.coupledLowerLayerMulticastDemand.layer.id)); netPlanInformation.append(NEWLINE); } } if (!layer.demands.isEmpty()) { netPlanInformation.append(NEWLINE); netPlanInformation.append("Demand information"); netPlanInformation.append(NEWLINE); netPlanInformation.append("--------------------------------"); netPlanInformation.append(NEWLINE).append(NEWLINE); for (Demand demand : layer.demands) { String demandInformation = String.format("d%d (id %d), n%d (%s) -> n%d (%s), offered traffic: %.3g, carried: %.3g, attributes: %s", demand.index , demand.id, demand.ingressNode.id, demand.ingressNode.name , demand.egressNode.id, demand.egressNode.name , demand.offeredTraffic , demand.carriedTraffic , demand.attributes.isEmpty() ? "none" : demand.attributes); netPlanInformation.append(demandInformation); if (demand.coupledUpperLayerLink != null) netPlanInformation.append(String.format(", associated to link %d (id %d) in layer %d (id %d)", demand.coupledUpperLayerLink.index, demand.coupledUpperLayerLink.id , demand.coupledUpperLayerLink.layer.index , demand.coupledUpperLayerLink.layer.id)); netPlanInformation.append(NEWLINE); } } if (!layer.multicastDemands.isEmpty()) { netPlanInformation.append(NEWLINE); netPlanInformation.append("Multicast demand information"); netPlanInformation.append(NEWLINE); netPlanInformation.append("--------------------------------"); netPlanInformation.append(NEWLINE).append(NEWLINE); for (MulticastDemand demand : layer.multicastDemands) { String demandInformation = String.format("d%d (id %d, n%d (%s) -> " , demand.index , demand.id , demand.ingressNode.id, demand.ingressNode.name); for (Node n : demand.egressNodes) demandInformation += " " + n + " (" + n.name + ")"; demandInformation += String.format (", offered traffic: %.3g, carried: %.3g, attributes: %s", demand.offeredTraffic, demand.carriedTraffic , demand.attributes.isEmpty() ? "none" : demand.attributes); netPlanInformation.append(demandInformation); if (demand.coupledUpperLayerLinks != null) { netPlanInformation.append(", associated to links "); for (Link e : demand.coupledUpperLayerLinks.values ()) netPlanInformation.append (" " + e.index + " (id " + e.id + "), "); netPlanInformation.append(" of layer: " + demand.coupledUpperLayerLinks.values ().iterator().next().index + " (id " + demand.coupledUpperLayerLinks.values ().iterator().next().id + ")"); } netPlanInformation.append(NEWLINE); } } if (layer.routingType == RoutingType.SOURCE_ROUTING) { if (!layer.routes.isEmpty()) { netPlanInformation.append(NEWLINE); netPlanInformation.append("Routing information"); netPlanInformation.append(NEWLINE); netPlanInformation.append("--------------------------------"); netPlanInformation.append(NEWLINE).append(NEWLINE); for (Route route : layer.routes) { String str_seqNodes = CollectionUtils.join(route.seqNodesRealPath , " => "); String str_seqLinks = CollectionUtils.join(route.seqLinksRealPath , " => "); String backupSegments = route.potentialBackupSegments.isEmpty() ? "none" : CollectionUtils.join(route.potentialBackupSegments, ", "); String routeInformation = String.format("r%d (id %d), demand: d%d (id %d), carried traffic: %.3g, occupied capacity: %.3g, seq. links: %s, seq. nodes: %s, backup segments: %s, attributes: %s", route.index , route.id , route.demand.index , route.demand.id, route.carriedTraffic, route.occupiedLinkCapacity, str_seqLinks, str_seqNodes, backupSegments, route.attributes.isEmpty() ? "none" : route.attributes); netPlanInformation.append(routeInformation); netPlanInformation.append(NEWLINE); } } if (!layer.protectionSegments.isEmpty()) { netPlanInformation.append(NEWLINE); netPlanInformation.append("Protection segment information"); netPlanInformation.append(NEWLINE); netPlanInformation.append("--------------------------------"); netPlanInformation.append(NEWLINE).append(NEWLINE); for (ProtectionSegment segment : layer.protectionSegments) { String str_seqLinks = CollectionUtils.join(segment.seqLinks, " => "); String str_seqNodes = CollectionUtils.join(segment.seqNodes, " => "); String segmentInformation = String.format("s%d (id %d), reserved bandwidth: %.3g, seq. links: %s, seq. nodes: %s, attributes: %s", segment.index , segment.id , segment.capacity , str_seqLinks, str_seqNodes, segment.attributes.isEmpty() ? "none" : segment.attributes); netPlanInformation.append(segmentInformation); netPlanInformation.append(NEWLINE); } } if (!layer.multicastTrees.isEmpty()) { netPlanInformation.append(NEWLINE); netPlanInformation.append("Multicast trees information"); netPlanInformation.append(NEWLINE); netPlanInformation.append("--------------------------------"); netPlanInformation.append(NEWLINE).append(NEWLINE); for (MulticastTree tree : layer.multicastTrees) { String str_seqNodes = CollectionUtils.join(tree.cache_traversedNodes , " , "); String str_seqLinks = CollectionUtils.join(tree.linkSet , " , "); String treeInformation = String.format("mt%d (id %d), multicast demand: md%d (id %d), carried traffic: %.3g, occupied capacity: %.3g, links: %s, nodes: %s, attributes: %s", tree.index , tree.id , tree.demand.index , tree.demand.id , tree.carriedTraffic, tree.occupiedLinkCapacity, str_seqLinks, str_seqNodes, tree.attributes.isEmpty() ? "none" : tree.attributes); netPlanInformation.append(treeInformation); netPlanInformation.append(NEWLINE); } } } else { netPlanInformation.append(NEWLINE); netPlanInformation.append("Forwarding information"); netPlanInformation.append(NEWLINE); netPlanInformation.append("--------------------------------"); netPlanInformation.append(NEWLINE).append(NEWLINE); netPlanInformation.append("f_de: ").append(NEWLINE); netPlanInformation.append(DoubleFactory2D.dense.make (layer.forwardingRules_f_de.toArray())).append(NEWLINE); netPlanInformation.append("x_de: ").append(NEWLINE); netPlanInformation.append(layer.forwardingRules_x_de).append(NEWLINE); } } if (!srgs.isEmpty()) { netPlanInformation.append(NEWLINE); netPlanInformation.append("Shared-risk group information"); netPlanInformation.append(NEWLINE); netPlanInformation.append("--------------------------------"); netPlanInformation.append(NEWLINE).append(NEWLINE); for (SharedRiskGroup srg : srgs) { String aux_nodes = srg.nodes.isEmpty() ? "none" : CollectionUtils.join(srg.nodes, " "); String aux_links = srg.links.isEmpty() ? "none" : CollectionUtils.join(srg.links, " "); String aux_mttf = StringUtils.secondsToYearsDaysHoursMinutesSeconds(srg.meanTimeToFailInHours * 3600); String aux_mttr = StringUtils.secondsToYearsDaysHoursMinutesSeconds(srg.meanTimeToRepairInHours * 3600); String srgInformation = String.format("srg%d (id %d), nodes: %s, links: %s, mttf: %s, mttr: %s, attributes: %s", srg.index , srg.id , aux_nodes, aux_links.toString(), aux_mttf, aux_mttr, srg.attributes.isEmpty() ? "none" : srg.attributes); netPlanInformation.append(srgInformation); netPlanInformation.append(NEWLINE); } } return netPlanInformation.toString(); } // /** // * Returns an unmodifiable view of the network. // * // * @return An unmodifiable view of the network // * @since 0.2.3 // */ // public NetPlan unmodifiableView() // { // NetPlan netPlan = new NetPlan(); // netPlan.assignFrom(this); // netPlan.isModifiable = false; // return netPlan; // } /** * <p>Sets the {@code NetPlan} so it cannot be modified</p> * @param isModifiable }If {@code true}, the object can be modified, {@code false} otherwise * @return The previous modifiable state */ public boolean setModifiableState (boolean isModifiable) { final boolean oldState = this.isModifiable; this.isModifiable = isModifiable; return oldState; } /** * <p>Checks if the given layer is valid and belongs to this {@code NetPlan} design. Throws and exception if the input is invalid.</p> * @param optionalLayer Network layer (optional) * @return The given layer (or the defaukt layer if no input was given) */ public NetworkLayer checkInThisNetPlanOptionalLayerParameter (NetworkLayer ... optionalLayer) { if (optionalLayer.length >= 2) throw new Net2PlanException ("None or one layer parameter can be supplied"); if (optionalLayer.length == 1) { checkInThisNetPlan(optionalLayer [0]); return optionalLayer [0]; } return defaultLayer; } NetworkElement getPeerElementInThisNetPlan (NetworkElement e) { NetworkElement res; if (e instanceof NetPlan) throw new RuntimeException ("Bad"); if (e.netPlan == null) throw new RuntimeException ("Bad"); if (e.netPlan == this) throw new RuntimeException ("Bad"); if (e instanceof Node) res = this.cache_id2NodeMap.get (e.id); else if (e instanceof Demand) res = this.cache_id2DemandMap.get (e.id); else if (e instanceof ProtectionSegment) res = this.cache_id2ProtectionSegmentMap.get (e.id); else if (e instanceof Link) res = this.cache_id2LinkMap.get (e.id); else if (e instanceof MulticastDemand) res = this.cache_id2MulticastDemandMap.get (e.id); else if (e instanceof MulticastTree) res = this.cache_id2MulticastTreeMap.get (e.id); else if (e instanceof Node) res = this.cache_id2NodeMap.get (e.id); else if (e instanceof Route) res = this.cache_id2RouteMap.get (e.id); else if (e instanceof SharedRiskGroup) res = this.cache_id2srgMap.get (e.id); else throw new RuntimeException ("Bad"); if (res.index != e.index) throw new RuntimeException ("Bad"); return res; } /* Receives a collection of routes, segments or multicast trees, and updates its failure state according to the traversing links and nodes */ void updateFailureStateRoutesTreesSegments (Collection<? extends NetworkElement> set) { for (NetworkElement thisElement : set) updateFailureStateRoutesTreesSegments (thisElement); } /* Receives a route, segment or multicast tree, and updates its failure state according to the traversing links and nodes */ void updateFailureStateRoutesTreesSegments (NetworkElement thisElement) { if (thisElement instanceof Route) { Route route = (Route) thisElement; boolean previouslyUp = !route.layer.cache_routesDown.contains (route); boolean isUp = true; for (Link e : route.seqLinksRealPath) if (!e.isUp) { isUp = false; break; } if (isUp) for (Node e : route.seqNodesRealPath) if (!e.isUp) { isUp = false; break; } // System.out.println ("Route :" + route + ", previously up:" + previouslyUp + ", isUp: " + isUp); // for (Link e : route.seqLinksRealPath) // System.out.println ("Link " + e + ", isUp: " + e.isUp); // for (Node n : route.seqNodesRealPath) // System.out.println ("Node " + n + ", isUp: " + n.isUp); if (isUp == previouslyUp) return; if (isUp) // from down to up { if (route.occupiedLinkCapacity != 0) throw new RuntimeException ("Bad"); if (route.carriedTraffic != 0) throw new RuntimeException ("Bad"); route.layer.cache_routesDown.remove (route); // System.out.println ("down to up: route.layer.cache_routesDown: " + route.layer.cache_routesDown); } else { if (route.occupiedLinkCapacity != route.occupiedLinkCapacityIfNotFailing) throw new RuntimeException ("Bad"); if (route.carriedTraffic != route.carriedTrafficIfNotFailing) throw new RuntimeException ("Bad"); route.layer.cache_routesDown.add (route); // System.out.println ("up to down : route.layer.cache_routesDown: " + route.layer.cache_routesDown); } final boolean previousDebug = ErrorHandling.isDebugEnabled(); ErrorHandling.setDebug(false); route.setCarriedTraffic(route.carriedTrafficIfNotFailing , route.occupiedLinkCapacityIfNotFailing); ErrorHandling.setDebug(previousDebug); } else if (thisElement instanceof MulticastTree) { MulticastTree tree = (MulticastTree) thisElement; boolean previouslyUp = !tree.layer.cache_multicastTreesDown.contains (tree); boolean isUp = true; for (Link e : tree.linkSet) if (!e.isUp) { isUp = false; break; } for (Node e : tree.cache_traversedNodes) if (!e.isUp) { isUp = false; break; } if (isUp == previouslyUp) return; if (isUp) // from down to up { if (tree.occupiedLinkCapacity != 0) throw new RuntimeException ("Bad"); if (tree.carriedTraffic != 0) throw new RuntimeException ("Bad"); tree.layer.cache_multicastTreesDown.remove (tree); } else { if (tree.occupiedLinkCapacity != tree.occupiedLinkCapacityIfNotFailing) throw new RuntimeException ("Bad"); if (tree.carriedTraffic != tree.carriedTrafficIfNotFailing) throw new RuntimeException ("Bad"); tree.layer.cache_multicastTreesDown.add (tree); } final boolean previousDebug = ErrorHandling.isDebugEnabled(); ErrorHandling.setDebug(false); tree.setCarriedTraffic(tree.carriedTrafficIfNotFailing , tree.occupiedLinkCapacityIfNotFailing); // updates links since all are up ErrorHandling.setDebug(previousDebug); } else if (thisElement instanceof ProtectionSegment) { ProtectionSegment segment = (ProtectionSegment) thisElement; boolean previouslyUp = !segment.layer.cache_segmentsDown.contains (segment); boolean isUp = true; for (Link e : segment.seqLinks) if (!e.isUp) { isUp = false; break; } for (Node e : segment.seqNodes) if (!e.isUp) { isUp = false; break; } if (isUp == previouslyUp) return; if (isUp) // from down to up { segment.layer.cache_segmentsDown.remove (segment); } else { segment.layer.cache_segmentsDown.add (segment); } } else throw new RuntimeException ("Bad"); } // // private Map<String,String> copyAttributeMap (Map<String,String> map) // { // Map<String,String> m = new HashMap<String,String> (); // for (Entry<String,String> e : map.entrySet ()) m.put(e.getKey(),e.getValue()); // return m; // } void checkCachesConsistency (List<? extends NetworkElement> list , Map<Long,? extends NetworkElement> cache , boolean mustBeSameSize) { if (mustBeSameSize) if (cache.size () != list.size ()) throw new RuntimeException ("Bad: cache: " + cache+ ", list: " + list); for (int cont = 0 ; cont < list.size () ; cont ++) { NetworkElement e = list.get(cont); if (e.index != cont) throw new RuntimeException ("Bad"); if (cache.get(e.id) == null) throw new RuntimeException ("Bad"); if (!e.equals (cache.get(e.id))) throw new RuntimeException ("Bad: list: " + list + ", cache: " + cache + ", e: " + e + ", cache.get(e.id): " + cache.get(e.id)); if (e != cache.get(e.id)) throw new RuntimeException ("Bad"); } } /** * <p>For debug purposes: Checks the consistency of the internal cache (nodes, srgs, layers, links, demands, multicast demands, multicast trees, routes, protection segments). If any * inconsistency is found an exception is thrown.</p> */ public void checkCachesConsistency () { // System.out.println ("Check caches consistency of object: " + hashCode()); checkCachesConsistency (nodes , cache_id2NodeMap , true); checkCachesConsistency (srgs , cache_id2srgMap , true); checkCachesConsistency (layers , cache_id2LayerMap , true); for (NetworkLayer layer : layers) { checkCachesConsistency (layer.links , cache_id2LinkMap , false); checkCachesConsistency (layer.demands , cache_id2DemandMap , false); checkCachesConsistency (layer.multicastDemands , cache_id2MulticastDemandMap , false); checkCachesConsistency (layer.multicastTrees , cache_id2MulticastTreeMap , false); checkCachesConsistency (layer.protectionSegments , cache_id2ProtectionSegmentMap, false); checkCachesConsistency (layer.routes , cache_id2RouteMap , false); } this.checkInThisNetPlan (nodes); this.checkInThisNetPlan (srgs); this.checkInThisNetPlan (layers); this.checkInThisNetPlan (defaultLayer); for (Node node : nodes) node.checkCachesConsistency(); for (SharedRiskGroup srg : srgs) srg.checkCachesConsistency(); for (NetworkLayer layer : layers) { this.checkInThisNetPlanAndLayer (layer.links , layer); this.checkInThisNetPlanAndLayer (layer.demands , layer); this.checkInThisNetPlanAndLayer (layer.multicastDemands , layer); this.checkInThisNetPlanAndLayer (layer.multicastTrees , layer); this.checkInThisNetPlanAndLayer (layer.routes , layer); this.checkInThisNetPlanAndLayer (layer.protectionSegments , layer); layer.checkCachesConsistency(); for (Link link : layer.links) link.checkCachesConsistency(); for (Demand demand : layer.demands) demand.checkCachesConsistency(); for (MulticastDemand demand : layer.multicastDemands) demand.checkCachesConsistency(); for (Route route : layer.routes) route.checkCachesConsistency(); for (MulticastTree tree : layer.multicastTrees) tree.checkCachesConsistency(); for (ProtectionSegment segment : layer.protectionSegments) segment.checkCachesConsistency(); if (layer.routingType == RoutingType.HOP_BY_HOP_ROUTING) { for (int d = 0 ; d < layer.demands.size() ; d ++) { final Demand demand = layer.demands.get (d); for (int e = 0 ; e < layer.links.size () ; e ++) { final Link link = layer.links.get(e); final double f_de = layer.forwardingRules_f_de.get(d, e); final double x_de = layer.forwardingRules_x_de.get(d, e); if (f_de < 0) throw new RuntimeException ("Bad"); if (f_de > 1) throw new RuntimeException ("Bad"); final Node a_e = layer.links.get(e).originNode; double linkInitialNodeOutTraffic = 0; double linkInitialNodeOutRules = 0; for (Link outLink : a_e.getOutgoingLinks(layer)) { final int out_a_e = outLink.index; linkInitialNodeOutTraffic += layer.forwardingRules_x_de.get(d, out_a_e); linkInitialNodeOutRules += layer.forwardingRules_f_de.get(d, out_a_e); } final boolean linkUp = link.isUp && link.originNode.isUp && link.destinationNode.isUp; double linkInitialNodeInTraffic = (link.originNode == demand.ingressNode)? demand.offeredTraffic : 0; for (Link inLink : a_e.getIncomingLinks(layer)) linkInitialNodeInTraffic += layer.forwardingRules_x_de.get(d, inLink.index); if (linkInitialNodeOutRules > 1 + 1E-3) throw new RuntimeException ("Bad"); if (!linkUp && (x_de > 1E-3))throw new RuntimeException ("Bad. outTraffic: " + linkInitialNodeOutTraffic + " and link " + link + " is down. NetPlan: " + this); if (linkUp && (linkInitialNodeInTraffic > 1e-3)) if (Math.abs(f_de - x_de/linkInitialNodeInTraffic) > 1e-4) throw new RuntimeException ("Bad. demand index: " + d + ", link : " + link + " (isUp? )" + link.isUp + ", nodeInTraffic: " + linkInitialNodeInTraffic + ", x_de: " + x_de + ", f_de: " + f_de + ", f_de - x_de/nodeInTraffic: " + (f_de - x_de/linkInitialNodeInTraffic)); if (linkInitialNodeOutTraffic < 1e-3) if (x_de > 1e-3) throw new RuntimeException ("Bad"); } } } } /* Check the interlayer object */ Set<NetworkLayer> layersAccordingToInterLayer = interLayerCoupling.vertexSet(); if (!layersAccordingToInterLayer.containsAll(layers)) throw new RuntimeException ("Bad"); if (layersAccordingToInterLayer.size () != layers.size()) throw new RuntimeException ("Bad"); for (DemandLinkMapping mapping : interLayerCoupling.edgeSet()) { NetworkLayer linkLayer = mapping.getLinkSideLayer(); NetworkLayer demandLayer = mapping.getDemandSideLayer(); linkLayer.checkAttachedToNetPlanObject(this); demandLayer.checkAttachedToNetPlanObject(this); for (Entry<Demand,Link> e : mapping.getDemandMap().entrySet()) { e.getKey().checkAttachedToNetPlanObject(this); e.getValue().checkAttachedToNetPlanObject(this); } } if (layers.get (defaultLayer.index) != defaultLayer) throw new RuntimeException ("Bad"); } static double adjustToTolerance (double val) { final double PRECISION_FACTOR = Double.parseDouble(Configuration.getOption("precisionFactor")); return (Math.abs(val) < PRECISION_FACTOR)? 0 : val; } static DoubleMatrix1D adjustToTolerance (DoubleMatrix1D vals) { final double PRECISION_FACTOR = Double.parseDouble(Configuration.getOption("precisionFactor")); return vals.copy ().assign (new DoubleFunction () { public double apply (double x) { return Math.abs(x) < PRECISION_FACTOR ? 0 : x; } }); } static DoubleMatrix2D adjustToTolerance (DoubleMatrix2D vals) { final double PRECISION_FACTOR = Double.parseDouble(Configuration.getOption("precisionFactor")); return vals.copy ().assign (new DoubleFunction () { public double apply (double x) { return Math.abs(x) < PRECISION_FACTOR ? 0 : x; } }); } }
Solve a minor thing in the candidate 11 path creation method (remove an unused input parameter)
src/main/java/com/net2plan/interfaces/networkDesign/NetPlan.java
Solve a minor thing in the candidate 11 path creation method (remove an unused input parameter)
Java
bsd-2-clause
313aef4b565819739be5ee98b3418568b1f9901e
0
biovoxxel/imagej,TehSAUCE/imagej,biovoxxel/imagej,biovoxxel/imagej,TehSAUCE/imagej,TehSAUCE/imagej
/* * #%L * ImageJ software for multidimensional image processing and analysis. * %% * Copyright (C) 2009 - 2012 Board of Regents of the University of * Wisconsin-Madison, Broad Institute of MIT and Harvard, and Max Planck * Institute of Molecular Cell Biology and Genetics. * %% * 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 HOLDERS OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * The views and conclusions contained in the software and documentation are * those of the authors and should not be interpreted as representing official * policies, either expressed or implied, of any organization. * #L% */ package imagej.data.display; import imagej.ImageJ; import imagej.data.display.event.MouseCursorEvent; import imagej.data.display.event.PanZoomEvent; import imagej.data.display.event.ViewportResizeEvent; import imagej.event.EventService; import imagej.ext.MouseCursor; import imagej.log.LogService; import imagej.util.IntCoords; import imagej.util.IntRect; import imagej.util.RealCoords; import imagej.util.RealRect; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; /** * The DefaultImageCanvas maintains a viewport, a zoom scale and a center * coordinate that it uses to map viewport pixels to display coordinates. It * also maintains an abstract mouse cursor. * <p> * The canvas sends a {@link PanZoomEvent} whenever it is panned or zoomed. It * sends a {@link MouseCursorEvent} whenever the mouse cursor changes. * </p> * * @author Lee Kamentsky * @author Curtis Rueden * @author Barry DeZonia */ public class DefaultImageCanvas implements ImageCanvas { private static final int MIN_ALLOWED_VIEW_SIZE = 25; private static double maxZoom; private static double[] defaultZooms; static { final List<Double> midLevelZooms = new ArrayList<Double>(); midLevelZooms.add(1 / 32d); midLevelZooms.add(1 / 24d); midLevelZooms.add(1 / 16d); midLevelZooms.add(1 / 12d); midLevelZooms.add(1 / 8d); midLevelZooms.add(1 / 6d); midLevelZooms.add(1 / 4d); midLevelZooms.add(1 / 3d); midLevelZooms.add(1 / 2d); midLevelZooms.add(3 / 4d); midLevelZooms.add(1d); midLevelZooms.add(1.5d); midLevelZooms.add(2d); midLevelZooms.add(3d); midLevelZooms.add(4d); midLevelZooms.add(6d); midLevelZooms.add(8d); midLevelZooms.add(12d); midLevelZooms.add(16d); midLevelZooms.add(24d); midLevelZooms.add(32d); final int EXTRA_ZOOMS = 25; final List<Double> loZooms = new ArrayList<Double>(); double prevDenom = 1 / midLevelZooms.get(0); for (int i = 0; i < EXTRA_ZOOMS; i++) { final double newDenom = prevDenom + 16; loZooms.add(1 / newDenom); prevDenom = newDenom; } Collections.reverse(loZooms); final List<Double> hiZooms = new ArrayList<Double>(); double prevNumer = midLevelZooms.get(midLevelZooms.size() - 1); for (int i = 0; i < EXTRA_ZOOMS; i++) { final double newNumer = prevNumer + 16; hiZooms.add(newNumer / 1); prevNumer = newNumer; } final List<Double> combinedZoomLevels = new ArrayList<Double>(); combinedZoomLevels.addAll(loZooms); combinedZoomLevels.addAll(midLevelZooms); combinedZoomLevels.addAll(hiZooms); defaultZooms = new double[combinedZoomLevels.size()]; for (int i = 0; i < defaultZooms.length; i++) defaultZooms[i] = combinedZoomLevels.get(i); maxZoom = hiZooms.get(hiZooms.size() - 1); } /** The canvas's display. */ private final ImageDisplay display; /** The size of the viewport. */ private final IntCoords viewportSize; /** The standard zoom levels for the canvas. */ private final double[] zoomLevels; /** Initial scale factor, for resetting zoom. */ private double initialScale = 1; /** The current scale factor. */ private double scale = 1.0; private MouseCursor mouseCursor; private RealCoords panCenter; public DefaultImageCanvas(final ImageDisplay display) { this.display = display; mouseCursor = MouseCursor.DEFAULT; viewportSize = new IntCoords(100, 100); zoomLevels = validatedZoomLevels(defaultZooms); } // -- ImageCanvas methods -- @Override public ImageDisplay getDisplay() { return display; } @Override public int getViewportWidth() { return viewportSize.x; } @Override public int getViewportHeight() { return viewportSize.y; } @Override public void setViewportSize(final int width, final int height) { viewportSize.x = width; viewportSize.y = height; final EventService eventService = getEventService(); if (eventService != null) { eventService.publish(new ViewportResizeEvent(this)); } } @Override public boolean isInImage(final IntCoords point) { final RealCoords dataCoords = panelToDataCoords(point); return getDisplay().getPlaneExtents().contains(dataCoords); } @Override public RealCoords panelToDataCoords(final IntCoords panelCoords) { final double dataX = panelCoords.x / getZoomFactor() + getLeftImageX(); final double dataY = panelCoords.y / getZoomFactor() + getTopImageY(); return new RealCoords(dataX, dataY); } @Override public IntCoords dataToPanelCoords(final RealCoords dataCoords) { final int panelX = (int) Math.round(getZoomFactor() * (dataCoords.x - getLeftImageX())); final int panelY = (int) Math.round(getZoomFactor() * (dataCoords.y - getTopImageY())); return new IntCoords(panelX, panelY); } @Override public MouseCursor getCursor() { return mouseCursor; } @Override public void setCursor(final MouseCursor cursor) { mouseCursor = cursor; final EventService eventService = getEventService(); if (eventService != null) eventService.publish(new MouseCursorEvent(this)); } // -- Pannable methods -- @Override public RealCoords getPanCenter() { if (panCenter == null) { panReset(); } if (panCenter == null) throw new IllegalStateException(); return new RealCoords(panCenter.x, panCenter.y); } @Override public void setPanCenter(final RealCoords center) { if (panCenter == null) { panCenter = new RealCoords(center.x, center.y); } else { // NB: Reuse existing object to avoid allocating a new one. panCenter.x = center.x; panCenter.y = center.y; } publishPanZoomEvent(); } @Override public void setPanCenter(final IntCoords center) { setPanCenter(panelToDataCoords(center)); } @Override public void pan(final RealCoords delta) { final double centerX = getPanCenter().x + delta.x; final double centerY = getPanCenter().y + delta.y; setPanCenter(new RealCoords(centerX, centerY)); } @Override public void pan(final IntCoords delta) { final double centerX = getPanCenter().x + delta.x / getZoomFactor(); final double centerY = getPanCenter().y + delta.y / getZoomFactor(); setPanCenter(new RealCoords(centerX, centerY)); } @Override public void panReset() { final RealRect extents = getDisplay().getPlaneExtents(); final double centerX = extents.x + extents.width / 2d; final double centerY = extents.y + extents.height / 2d; setPanCenter(new RealCoords(centerX, centerY)); } // -- Zoomable methods -- @Override public void setZoom(final double factor) { final double desiredScale = factor == 0 ? initialScale : factor; if (scaleOutOfBounds(desiredScale) || desiredScale == getZoomFactor()) { return; } scale = factor; publishPanZoomEvent(); } @Override public void setZoom(final double factor, final RealCoords center) { final double desiredScale = factor == 0 ? initialScale : factor; if (scaleOutOfBounds(desiredScale)) return; scale = desiredScale; setPanCenter(center); } @Override public void setZoom(final double factor, final IntCoords center) { setZoom(factor, panelToDataCoords(center)); } @Override public void setZoomAndCenter(final double factor) { final double x = getViewportWidth() / getZoomFactor() / 2d; final double y = getViewportHeight() / getZoomFactor() / 2d; setZoom(factor, new RealCoords(x, y)); } @Override public void zoomIn() { final double newScale = nextLargerZoom(zoomLevels, getZoomFactor()); setZoom(newScale); } @Override public void zoomIn(final RealCoords center) { final double desiredScale = nextLargerZoom(zoomLevels, getZoomFactor()); setZoom(desiredScale, center); } @Override public void zoomIn(final IntCoords center) { final double desiredScale = nextLargerZoom(zoomLevels, getZoomFactor()); setZoom(desiredScale, center); } @Override public void zoomOut() { final double desiredScale = nextSmallerZoom(zoomLevels, getZoomFactor()); setZoom(desiredScale); } @Override public void zoomOut(final RealCoords center) { final double newScale = nextSmallerZoom(zoomLevels, getZoomFactor()); setZoom(newScale, center); } @Override public void zoomOut(final IntCoords center) { final double newScale = nextSmallerZoom(zoomLevels, getZoomFactor()); setZoom(newScale, center); } @Override public void zoomToFit(final IntRect viewportBox) { final IntCoords topLeft = viewportBox.getTopLeft(); final IntCoords bottomRight = viewportBox.getBottomRight(); final RealCoords dataTopLeft = panelToDataCoords(topLeft); final RealCoords dataBottomRight = panelToDataCoords(bottomRight); final double newCenterX = Math.abs(dataBottomRight.x + dataTopLeft.x) / 2d; final double newCenterY = Math.abs(dataBottomRight.y + dataTopLeft.y) / 2d; final double dataSizeX = Math.abs(dataBottomRight.x - dataTopLeft.x); final double dataSizeY = Math.abs(dataBottomRight.y - dataTopLeft.y); final double xZoom = getViewportWidth() / dataSizeX; final double yZoom = getViewportHeight() / dataSizeY; final double factor = Math.min(xZoom, yZoom); setZoom(factor, new RealCoords(newCenterX, newCenterY)); } @Override public void zoomToFit(final RealRect viewportBox) { final double newCenterX = (viewportBox.x + viewportBox.width / 2d); final double newCenterY = (viewportBox.y + viewportBox.height / 2d); final double minScale = Math.min(getViewportWidth() / viewportBox.width, getViewportHeight() / viewportBox.height); setZoom(minScale, new RealCoords(newCenterX, newCenterY)); } @Override public double getZoomFactor() { return this.scale; } @Override public double getInitialScale() { return initialScale; } @Override public void setInitialScale(final double zoomFactor) { if (zoomFactor <= 0) { throw new IllegalArgumentException("Initial scale must be > 0"); } this.initialScale = zoomFactor; } @Override public double getBestZoomLevel(final double fractionalScale) { final double[] levels = defaultZooms; final int zoomIndex = lookupZoomIndex(levels, fractionalScale); if (zoomIndex != -1) return levels[zoomIndex]; return nextSmallerZoom(levels, fractionalScale); } // -- Helper methods -- private void publishPanZoomEvent() { final ImageJ context = getDisplay().getContext(); if (context == null) return; final EventService eventService = getEventService(); if (eventService != null) eventService.publish(new PanZoomEvent(this)); } // -- Helper methods -- /** Gets the log to which messages should be sent. */ private LogService getLog() { final ImageJ context = display.getContext(); if (context == null) return null; return context.getService(LogService.class); } /** Gets the service to which events should be published. */ private EventService getEventService() { final ImageJ context = display.getContext(); if (context == null) return null; return context.getService(EventService.class); } /** * Gets the coordinate of the left edge of the viewport in <em>data</em> * space. */ private double getLeftImageX() { final double viewportImageWidth = getViewportWidth() / getZoomFactor(); return getPanCenter().x - viewportImageWidth / 2d; } /** * Gets the coordinate of the top edge of the viewport in <em>data</em> space. */ private double getTopImageY() { final double viewportImageHeight = getViewportHeight() / getZoomFactor(); return getPanCenter().y - viewportImageHeight / 2d; } /** Checks whether the given scale is out of bounds. */ private boolean scaleOutOfBounds(final double desiredScale) { if (desiredScale <= 0) { final LogService log = getLog(); if (log != null) log.warn("**** BAD SCALE: " + desiredScale + " ****"); return true; } if (desiredScale > maxZoom) return true; // check if trying to zoom out too far if (desiredScale < getZoomFactor()) { // get boundaries of the plane in panel coordinates final RealRect planeExtents = getDisplay().getPlaneExtents(); final IntCoords nearCornerPanel = dataToPanelCoords(new RealCoords(planeExtents.x, planeExtents.y)); final IntCoords farCornerPanel = dataToPanelCoords(new RealCoords(planeExtents.x + planeExtents.width, planeExtents.y + planeExtents.height)); // if boundaries take up less than min allowed pixels in either dimension final int panelX = farCornerPanel.x - nearCornerPanel.x; final int panelY = farCornerPanel.y - nearCornerPanel.y; if (panelX < MIN_ALLOWED_VIEW_SIZE && panelY < MIN_ALLOWED_VIEW_SIZE) { return true; } } return false; } private static double nextSmallerZoom(final double[] zoomLevels, final double currScale) { final int index = Arrays.binarySearch(zoomLevels, currScale); int nextIndex; if (index >= 0) nextIndex = index - 1; else nextIndex = -(index + 1) - 1; if (nextIndex < 0) nextIndex = 0; if (nextIndex > zoomLevels.length - 1) nextIndex = zoomLevels.length - 1; return zoomLevels[nextIndex]; } private static double nextLargerZoom(final double[] zoomLevels, final double currScale) { final int index = Arrays.binarySearch(zoomLevels, currScale); int nextIndex; if (index >= 0) nextIndex = index + 1; else nextIndex = -(index + 1); if (nextIndex < 0) nextIndex = 0; if (nextIndex > zoomLevels.length - 1) nextIndex = zoomLevels.length - 1; return zoomLevels[nextIndex]; } private static double[] validatedZoomLevels(final double[] levels) { final double[] validatedLevels = levels.clone(); Arrays.sort(validatedLevels); if (validatedLevels.length == 0) { throw new IllegalArgumentException("given zoom level array is empty"); } double prevEntry = validatedLevels[0]; if (prevEntry <= 0) { throw new IllegalArgumentException( "zoom level array contains nonpositive entries"); } for (int i = 1; i < validatedLevels.length; i++) { final double currEntry = validatedLevels[i]; if (currEntry == prevEntry) { throw new IllegalArgumentException( "zoom level array contains duplicate entries"); } prevEntry = currEntry; } return validatedLevels; } /** * Unfortunately, we can't rely on Java's binary search since we're using * doubles and rounding errors could cause problems. So we write our own that * searches zooms avoiding rounding problems. */ private static int lookupZoomIndex(final double[] levels, final double requestedZoom) { int lo = 0; int hi = levels.length - 1; do { final int mid = (lo + hi) / 2; final double possibleZoom = levels[mid]; if (Math.abs(requestedZoom - possibleZoom) < 0.00001) return mid; if (requestedZoom < possibleZoom) hi = mid - 1; else lo = mid + 1; } while (hi >= lo); return -1; } }
core/data/src/main/java/imagej/data/display/DefaultImageCanvas.java
/* * #%L * ImageJ software for multidimensional image processing and analysis. * %% * Copyright (C) 2009 - 2012 Board of Regents of the University of * Wisconsin-Madison, Broad Institute of MIT and Harvard, and Max Planck * Institute of Molecular Cell Biology and Genetics. * %% * 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 HOLDERS OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * The views and conclusions contained in the software and documentation are * those of the authors and should not be interpreted as representing official * policies, either expressed or implied, of any organization. * #L% */ package imagej.data.display; import imagej.ImageJ; import imagej.data.display.event.MouseCursorEvent; import imagej.data.display.event.PanZoomEvent; import imagej.data.display.event.ViewportResizeEvent; import imagej.event.EventService; import imagej.ext.MouseCursor; import imagej.log.LogService; import imagej.util.IntCoords; import imagej.util.IntRect; import imagej.util.RealCoords; import imagej.util.RealRect; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; /** * The DefaultImageCanvas maintains a viewport, a zoom scale and a center * coordinate that it uses to map viewport pixels to display coordinates. It * also maintains an abstract mouse cursor. * <p> * The canvas sends a {@link PanZoomEvent} whenever it is panned or zoomed. It * sends a {@link MouseCursorEvent} whenever the mouse cursor changes. * </p> * * @author Lee Kamentsky * @author Curtis Rueden * @author Barry DeZonia */ public class DefaultImageCanvas implements ImageCanvas { private static final int MIN_ALLOWED_VIEW_SIZE = 25; private static double maxZoom; private static double[] defaultZooms; static { final List<Double> midLevelZooms = new ArrayList<Double>(); midLevelZooms.add(1 / 32d); midLevelZooms.add(1 / 24d); midLevelZooms.add(1 / 16d); midLevelZooms.add(1 / 12d); midLevelZooms.add(1 / 8d); midLevelZooms.add(1 / 6d); midLevelZooms.add(1 / 4d); midLevelZooms.add(1 / 3d); midLevelZooms.add(1 / 2d); midLevelZooms.add(3 / 4d); midLevelZooms.add(1d); midLevelZooms.add(1.5d); midLevelZooms.add(2d); midLevelZooms.add(3d); midLevelZooms.add(4d); midLevelZooms.add(6d); midLevelZooms.add(8d); midLevelZooms.add(12d); midLevelZooms.add(16d); midLevelZooms.add(24d); midLevelZooms.add(32d); final int EXTRA_ZOOMS = 25; final List<Double> loZooms = new ArrayList<Double>(); double prevDenom = 1 / midLevelZooms.get(0); for (int i = 0; i < EXTRA_ZOOMS; i++) { final double newDenom = prevDenom + 16; loZooms.add(1 / newDenom); prevDenom = newDenom; } Collections.reverse(loZooms); final List<Double> hiZooms = new ArrayList<Double>(); double prevNumer = midLevelZooms.get(midLevelZooms.size() - 1); for (int i = 0; i < EXTRA_ZOOMS; i++) { final double newNumer = prevNumer + 16; hiZooms.add(newNumer / 1); prevNumer = newNumer; } final List<Double> combinedZoomLevels = new ArrayList<Double>(); combinedZoomLevels.addAll(loZooms); combinedZoomLevels.addAll(midLevelZooms); combinedZoomLevels.addAll(hiZooms); defaultZooms = new double[combinedZoomLevels.size()]; for (int i = 0; i < defaultZooms.length; i++) defaultZooms[i] = combinedZoomLevels.get(i); maxZoom = hiZooms.get(hiZooms.size() - 1); } /** The canvas's display. */ private final ImageDisplay display; /** The size of the viewport. */ private final IntCoords viewportSize; /** The standard zoom levels for the canvas. */ private final double[] zoomLevels; /** Initial scale factor, for resetting zoom. */ private double initialScale = 1; /** The current scale factor. */ private double scale = 1.0; private MouseCursor mouseCursor; private RealCoords panCenter; public DefaultImageCanvas(final ImageDisplay display) { this.display = display; mouseCursor = MouseCursor.DEFAULT; viewportSize = new IntCoords(100, 100); zoomLevels = validatedZoomLevels(defaultZooms); } // -- ImageCanvas methods -- @Override public ImageDisplay getDisplay() { return display; } @Override public int getViewportWidth() { return viewportSize.x; } @Override public int getViewportHeight() { return viewportSize.y; } @Override public void setViewportSize(final int width, final int height) { viewportSize.x = width; viewportSize.y = height; final EventService eventService = getEventService(); if (eventService != null) { eventService.publish(new ViewportResizeEvent(this)); } } @Override public boolean isInImage(final IntCoords point) { final RealCoords dataCoords = panelToDataCoords(point); return getDisplay().getPlaneExtents().contains(dataCoords); } @Override public RealCoords panelToDataCoords(final IntCoords panelCoords) { final double dataX = panelCoords.x / getZoomFactor() + getLeftImageX(); final double dataY = panelCoords.y / getZoomFactor() + getTopImageY(); return new RealCoords(dataX, dataY); } @Override public IntCoords dataToPanelCoords(final RealCoords dataCoords) { final int panelX = (int) Math.round(getZoomFactor() * (dataCoords.x - getLeftImageX())); final int panelY = (int) Math.round(getZoomFactor() * (dataCoords.y - getTopImageY())); return new IntCoords(panelX, panelY); } @Override public MouseCursor getCursor() { return mouseCursor; } @Override public void setCursor(final MouseCursor cursor) { mouseCursor = cursor; final EventService eventService = getEventService(); if (eventService != null) eventService.publish(new MouseCursorEvent(this)); } // -- Pannable methods -- @Override public RealCoords getPanCenter() { if (panCenter == null) { panReset(); } if (panCenter == null) throw new IllegalStateException(); return new RealCoords(panCenter.x, panCenter.y); } @Override public void setPanCenter(final RealCoords center) { if (panCenter == null) { panCenter = new RealCoords(center.x, center.y); } else { panCenter.x = center.x; panCenter.y = center.y; } publishPanZoomEvent(); } @Override public void setPanCenter(final IntCoords center) { setPanCenter(panelToDataCoords(center)); } @Override public void pan(final RealCoords delta) { final double centerX = getPanCenter().x + delta.x; final double centerY = getPanCenter().y + delta.y; setPanCenter(new RealCoords(centerX, centerY)); } @Override public void pan(final IntCoords delta) { final double centerX = getPanCenter().x + delta.x / getZoomFactor(); final double centerY = getPanCenter().y + delta.y / getZoomFactor(); setPanCenter(new RealCoords(centerX, centerY)); } @Override public void panReset() { final RealRect extents = getDisplay().getPlaneExtents(); final double centerX = extents.x + extents.width / 2d; final double centerY = extents.y + extents.height / 2d; setPanCenter(new RealCoords(centerX, centerY)); } // -- Zoomable methods -- @Override public void setZoom(final double factor) { final double desiredScale = factor == 0 ? initialScale : factor; if (scaleOutOfBounds(desiredScale) || desiredScale == getZoomFactor()) { return; } scale = factor; publishPanZoomEvent(); } @Override public void setZoom(final double factor, final RealCoords center) { final double desiredScale = factor == 0 ? initialScale : factor; if (scaleOutOfBounds(desiredScale)) return; if (panCenter == null) { panCenter = new RealCoords(center.x, center.y); } else { panCenter.x = center.x; panCenter.y = center.y; } scale = desiredScale; publishPanZoomEvent(); } @Override public void setZoom(final double factor, final IntCoords center) { setZoom(factor, panelToDataCoords(center)); } @Override public void setZoomAndCenter(final double factor) { final double x = getViewportWidth() / getZoomFactor() / 2d; final double y = getViewportHeight() / getZoomFactor() / 2d; setZoom(factor, new RealCoords(x, y)); } @Override public void zoomIn() { final double newScale = nextLargerZoom(zoomLevels, getZoomFactor()); setZoom(newScale); } @Override public void zoomIn(final RealCoords center) { final double desiredScale = nextLargerZoom(zoomLevels, getZoomFactor()); setZoom(desiredScale, center); } @Override public void zoomIn(final IntCoords center) { final double desiredScale = nextLargerZoom(zoomLevels, getZoomFactor()); setZoom(desiredScale, center); } @Override public void zoomOut() { final double desiredScale = nextSmallerZoom(zoomLevels, getZoomFactor()); setZoom(desiredScale); } @Override public void zoomOut(final RealCoords center) { final double newScale = nextSmallerZoom(zoomLevels, getZoomFactor()); setZoom(newScale, center); } @Override public void zoomOut(final IntCoords center) { final double newScale = nextSmallerZoom(zoomLevels, getZoomFactor()); setZoom(newScale, center); } @Override public void zoomToFit(final IntRect viewportBox) { final IntCoords topLeft = viewportBox.getTopLeft(); final IntCoords bottomRight = viewportBox.getBottomRight(); final RealCoords dataTopLeft = panelToDataCoords(topLeft); final RealCoords dataBottomRight = panelToDataCoords(bottomRight); final double newCenterX = Math.abs(dataBottomRight.x + dataTopLeft.x) / 2d; final double newCenterY = Math.abs(dataBottomRight.y + dataTopLeft.y) / 2d; final double dataSizeX = Math.abs(dataBottomRight.x - dataTopLeft.x); final double dataSizeY = Math.abs(dataBottomRight.y - dataTopLeft.y); final double xZoom = getViewportWidth() / dataSizeX; final double yZoom = getViewportHeight() / dataSizeY; final double factor = Math.min(xZoom, yZoom); setZoom(factor, new RealCoords(newCenterX, newCenterY)); } @Override public void zoomToFit(final RealRect viewportBox) { final double newCenterX = (viewportBox.x + viewportBox.width / 2d); final double newCenterY = (viewportBox.y + viewportBox.height / 2d); final double minScale = Math.min(getViewportWidth() / viewportBox.width, getViewportHeight() / viewportBox.height); setZoom(minScale, new RealCoords(newCenterX, newCenterY)); } @Override public double getZoomFactor() { return this.scale; } @Override public double getInitialScale() { return initialScale; } @Override public void setInitialScale(final double zoomFactor) { if (zoomFactor <= 0) { throw new IllegalArgumentException("Initial scale must be > 0"); } this.initialScale = zoomFactor; } @Override public double getBestZoomLevel(final double fractionalScale) { final double[] levels = defaultZooms; final int zoomIndex = lookupZoomIndex(levels, fractionalScale); if (zoomIndex != -1) return levels[zoomIndex]; return nextSmallerZoom(levels, fractionalScale); } // -- Helper methods -- private void publishPanZoomEvent() { final ImageJ context = getDisplay().getContext(); if (context == null) return; final EventService eventService = getEventService(); if (eventService != null) eventService.publish(new PanZoomEvent(this)); } // -- Helper methods -- /** Gets the log to which messages should be sent. */ private LogService getLog() { final ImageJ context = display.getContext(); if (context == null) return null; return context.getService(LogService.class); } /** Gets the service to which events should be published. */ private EventService getEventService() { final ImageJ context = display.getContext(); if (context == null) return null; return context.getService(EventService.class); } /** * Gets the coordinate of the left edge of the viewport in <em>data</em> * space. */ private double getLeftImageX() { final double viewportImageWidth = getViewportWidth() / getZoomFactor(); return getPanCenter().x - viewportImageWidth / 2d; } /** * Gets the coordinate of the top edge of the viewport in <em>data</em> space. */ private double getTopImageY() { final double viewportImageHeight = getViewportHeight() / getZoomFactor(); return getPanCenter().y - viewportImageHeight / 2d; } /** Checks whether the given scale is out of bounds. */ private boolean scaleOutOfBounds(final double desiredScale) { if (desiredScale <= 0) { final LogService log = getLog(); if (log != null) log.warn("**** BAD SCALE: " + desiredScale + " ****"); return true; } if (desiredScale > maxZoom) return true; // check if trying to zoom out too far if (desiredScale < getZoomFactor()) { // get boundaries of the plane in panel coordinates final RealRect planeExtents = getDisplay().getPlaneExtents(); final IntCoords nearCornerPanel = dataToPanelCoords(new RealCoords(planeExtents.x, planeExtents.y)); final IntCoords farCornerPanel = dataToPanelCoords(new RealCoords(planeExtents.x + planeExtents.width, planeExtents.y + planeExtents.height)); // if boundaries take up less than min allowed pixels in either dimension final int panelX = farCornerPanel.x - nearCornerPanel.x; final int panelY = farCornerPanel.y - nearCornerPanel.y; if (panelX < MIN_ALLOWED_VIEW_SIZE && panelY < MIN_ALLOWED_VIEW_SIZE) { return true; } } return false; } private static double nextSmallerZoom(final double[] zoomLevels, final double currScale) { final int index = Arrays.binarySearch(zoomLevels, currScale); int nextIndex; if (index >= 0) nextIndex = index - 1; else nextIndex = -(index + 1) - 1; if (nextIndex < 0) nextIndex = 0; if (nextIndex > zoomLevels.length - 1) nextIndex = zoomLevels.length - 1; return zoomLevels[nextIndex]; } private static double nextLargerZoom(final double[] zoomLevels, final double currScale) { final int index = Arrays.binarySearch(zoomLevels, currScale); int nextIndex; if (index >= 0) nextIndex = index + 1; else nextIndex = -(index + 1); if (nextIndex < 0) nextIndex = 0; if (nextIndex > zoomLevels.length - 1) nextIndex = zoomLevels.length - 1; return zoomLevels[nextIndex]; } private static double[] validatedZoomLevels(final double[] levels) { final double[] validatedLevels = levels.clone(); Arrays.sort(validatedLevels); if (validatedLevels.length == 0) { throw new IllegalArgumentException("given zoom level array is empty"); } double prevEntry = validatedLevels[0]; if (prevEntry <= 0) { throw new IllegalArgumentException( "zoom level array contains nonpositive entries"); } for (int i = 1; i < validatedLevels.length; i++) { final double currEntry = validatedLevels[i]; if (currEntry == prevEntry) { throw new IllegalArgumentException( "zoom level array contains duplicate entries"); } prevEntry = currEntry; } return validatedLevels; } /** * Unfortunately, we can't rely on Java's binary search since we're using * doubles and rounding errors could cause problems. So we write our own that * searches zooms avoiding rounding problems. */ private static int lookupZoomIndex(final double[] levels, final double requestedZoom) { int lo = 0; int hi = levels.length - 1; do { final int mid = (lo + hi) / 2; final double possibleZoom = levels[mid]; if (Math.abs(requestedZoom - possibleZoom) < 0.00001) return mid; if (requestedZoom < possibleZoom) hi = mid - 1; else lo = mid + 1; } while (hi >= lo); return -1; } }
Image canvas: eliminate duplicate code
core/data/src/main/java/imagej/data/display/DefaultImageCanvas.java
Image canvas: eliminate duplicate code
Java
bsd-3-clause
808d783707a7ba6aaaf759d89dde1f4cc19866b5
0
datadryad/dans-bagit,datadryad/dans-bagit
package org.datadryad.dansbagit; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.apache.log4j.Logger; import java.io.*; import java.security.DigestInputStream; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.text.SimpleDateFormat; import java.util.*; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; /** * Main class which manages interactions with a Dryad/DANS formatted Bag * * This allows the BagIt packages to be constructed from files on disk, or for a * zipped BagIt to be read and opened. * * The DANS Bag format is as follows: * * <pre> * base directory/ * | bagit.txt * | bitstream-description.txt * | bitstream-format.txt * | bitstream-size.txt * | manifest-md5.txt * | tagmanifest-md5.txt * \--- metadata * | dataset.xml * | files.xml * \--- data/ * | metadata.xml * \--- [Data File DOI] * | metadata.xml * \--- [DSpace Bundle Name] * | [DSpace Bitstreams] *</pre> */ public class DANSBag { private static Logger log = Logger.getLogger(DANSBag.class); /** Buffer size to be used when chunking through input streams */ private static final int BUFFER = 8192; /** * Inner class to provide a reference to a file in the Bag. Since the file in the bag * may have different types, different sources for its input stream, and different tag * properties, this allows us to provide a consistent wrapper for internal use. */ class BagFileReference { public ZipEntry zipEntry = null; private File file = null; public String filename = null; public String fullPath = null; public String internalPath = null; public String description = null; public String format = null; public long size = -1; public String md5 = null; public String sha1 = null; public String dataFileIdent = null; public String bundle = null; public File getFile() { if (this.file == null) { this.file = new File(fullPath); } return this.file; } } private File zipFile = null; private File workingDir = null; private String name = null; private List<BagFileReference> fileRefs = new ArrayList<BagFileReference>(); private DDM ddm = null; private DIM dim = null; private Map<String, DIM> subDim = new HashMap<String, DIM>(); /** * Create a BagIt with the given name, using the provided zip as input or output, and with * the given working directory for temporary storage * * @param name name to use for the bag. This will form the top level directory inside the zip * @param zipPath path to read in or output zip content * @param workingDir directory used for temporary storage */ public DANSBag(String name, String zipPath, String workingDir) { this(name, new File(zipPath), new File(workingDir)); } /** * Create a BagIt with the given name, using the provided zip as input or output, and with * the given working directory for temporary storage * * @param name name to use for the bag. This will form the top level directory inside the zip * @param zipFile path to read in or output zip content * @param workingDir directory used for temporary storage */ public DANSBag(String name, File zipFile, File workingDir) { this.zipFile = zipFile; this.workingDir = workingDir; this.name = name; log.debug("Creating DANSBag object around zipfile " + zipFile.getAbsolutePath() + " using working directory " + workingDir.getAbsolutePath() + " with name " + name); if (zipFile.exists()) { log.debug("Zipfile " + zipFile.getAbsolutePath() + " exists, loading data from there"); // load the bag this.loadBag(zipFile); } } /** * Load state from the given zip file * * Not yet implemented * * @param file */ public void loadBag(File file) { // TODO } /** * Get the full path to the working directory * * @return path to the working directory */ public String getWorkingDir() { return this.workingDir.getAbsolutePath(); } /** * Get the MD5 of the zip. The zip must exist for this to happen, so you either need to have * created this object around a zip file, or have called writeFile first. If you try to call * it otherwise, you will get a RuntimeException * * @return the MD5 hex string for the zip file * @throws IOException if there's a problem reading the file */ public String getMD5() throws IOException { if (!this.zipFile.exists()) { throw new RuntimeException("You must writeFile before you can calculate the md5"); } try { FileInputStream fis = new FileInputStream(this.zipFile); String md5 = Files.md5Hex(fis); fis.close(); return md5; // if we could use DigestUtils (which we can't because DSpace) this would be quicker and cleaner this way // String md5 = DigestUtils.md5Hex(fis); } catch(NoSuchAlgorithmException e) { // this shouldn't happen throw new RuntimeException(e); } } /** * Get the name of the zip file. You can only do this once the zip file exists, otherwise you will get a RuntimeException * * @return the name of the zip file */ public String getZipName() { if (!this.zipFile.exists()) { throw new RuntimeException("You must writeFile before you can ask questions about the zip"); } return this.zipFile.getName(); } /** * Get the full path to the zip file. You can only do this once the zip file exists, otherwise you will get a RuntimeException * * @return the full path to the zip file */ public String getZipPath() { if (!this.zipFile.exists()) { throw new RuntimeException("You must writeFile before you can ask questions about the zip"); } return this.zipFile.getAbsolutePath(); } /** * Get an input stream for the entire zip file. You can only do this once the zip file exists, otherwise you will get a RuntimeException * * @return an input stream from which you can retrieve the entire zip file * * @throws Exception */ public InputStream getInputStream() { if (!this.zipFile.exists()) { throw new RuntimeException("You must writeFile before you can read the input stream"); } try { return new FileInputStream(this.zipFile); } catch (FileNotFoundException e) { // this can't happen, as we've already checked throw new RuntimeException(e); } } /** * Get an iterator which will allow you to iterate over input streams for defined size chunks of the zip file. * * You can only do this once the zip file exists, otherwise you will get a RuntimeException * * @param size the size (in bytes) of the chunks (all except the final chunk will be this size) * @param md5 whether to calculate the md5 of each chunk as it is read * @return a file segment iterator which can be used to retrieve input streams for subsequent chunks * @throws Exception */ public FileSegmentIterator getSegmentIterator(long size, boolean md5) { if (!this.zipFile.exists()) { throw new RuntimeException("You must writeFile before you can read the segments"); } try { return new FileSegmentIterator(this.zipFile, size, md5); } catch (IOException e) { // shouldn't happen, as we have checked the file's existence already throw new RuntimeException(e); } } /** * How big is the zip file. You can only do this once the zip file exists, otherwise you will get a RuntimeException * * @return size of zip file in bytes */ public long size() { if (!this.zipFile.exists()) { throw new RuntimeException("You must writeFile before you can determine the size"); } return this.zipFile.length(); } /** * Add a bitstream to the bag. This will stage the file in the working directory. * * @param is input stream where the bitstream can be read from * @param filename the filename * @param format the mimetype of the file * @param description a description of the file * @param dataFileIdent an identifier for the data file to which this bitstream belongs * @param bundle the DSpace bundle the bitstream came from * @throws IOException */ public void addBitstream(InputStream is, String filename, String format, String description, String dataFileIdent, String bundle) throws IOException { log.info("Adding bitstream to DANSBag: filename= " + filename + "; format= " + format + "; data_file=" + dataFileIdent + "; bundle=" + bundle); // escape the dataFileIdent String dataFilename = Files.sanitizeFilename(dataFileIdent); log.debug("Sanitised dataFileIdent from " + dataFileIdent + " to " + dataFilename); // get the correct folder/filename for the bitstream String internalDir = "data" + File.separator + dataFilename + File.separator + bundle; String internalFile = internalDir + File.separator + filename; String targetDir = this.workingDir.getAbsolutePath() + File.separator + internalDir; String filePath = targetDir + File.separator + filename; log.info("Bistream will be temporarily staged at " + filePath); log.info("Bitstream will be written to internal zip path " + internalFile); // ensure that the target directory exists (new File(targetDir)).mkdirs(); // wrap the input stream in something that can get the MD5 as we read it MessageDigest mdmd5 = null; MessageDigest mdsha1 = null; try { mdmd5 = MessageDigest.getInstance("MD5"); mdsha1 = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } DigestInputStream inner = new DigestInputStream(is, mdmd5); DigestInputStream dis = new DigestInputStream(inner, mdsha1); // write the input stream to the working directory, in the appropriate folder OutputStream os = new FileOutputStream(filePath); IOUtils.copy(dis, os); // add the bitstream information to our internal data structure BagFileReference bfr = new BagFileReference(); bfr.filename = filename; bfr.fullPath = filePath; bfr.internalPath = internalFile; bfr.md5 = Files.digestToString(mdmd5); bfr.sha1 = Files.digestToString(mdsha1); bfr.description = description; bfr.format = format; bfr.size = (new File(filePath)).length(); bfr.dataFileIdent = dataFileIdent; bfr.bundle = bundle; this.fileRefs.add(bfr); } /** * Set the DDM metdata object for this bag * * @param ddm */ public void setDDM(DDM ddm) { this.ddm = ddm; } /** * Set the dataset DIM metadata for this bag * * @param dim */ public void setDatasetDIM(DIM dim) { this.dim = dim; } /** * Set the data file DIM metadata for the given data file identifier * * @param dim * @param dataFileIdent the identifier for the data file */ public void addDatafileDIM(DIM dim, String dataFileIdent) { this.subDim.put(dataFileIdent, dim); } /** * Write the in-memory information and contents of the working directory to the zip file. * * You can only do this once, and it will refuse to run again if the zip file is already present. If you want to * run it again in the same thread you'll need to call cleanupZip first. Also, you shouldn't need to do that - only * call this when you have finished assembling the bag. */ public void writeToFile() { try { // if this bag was initialised from a zip file, we can't write back to it - just too // complicated. if (this.zipFile.exists()) { log.error("Attempt to write bag when zip already exists"); throw new RuntimeException("Cannot re-write a modified bag file. You should either create a new bag file from the source files, or read in the old zip file and pass the components in here."); } log.info("Writing bag to file " + this.zipFile.getAbsolutePath()); String base = Files.sanitizeFilename(this.name); // prepare our zipped output stream FileOutputStream dest = new FileOutputStream(this.zipFile); ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(dest)); String descriptions = ""; String formats = ""; String sizes = ""; String md5Manifest = ""; String sha1Manifest = ""; String tagmanifest = ""; DANSFiles dfs = new DANSFiles(); // write the bitstreams, and gather their metadata for the tag files as we go through for (BagFileReference bfr : this.fileRefs) { // add the filename to the files.xml metadata dfs.addFileMetadata(bfr.internalPath, "dcterms:title", bfr.filename); // update description tag file contents if (bfr.description != null && !"".equals(bfr.description)) { descriptions = descriptions + bfr.description + "\t" + bfr.internalPath + "\n"; dfs.addFileMetadata(bfr.internalPath, "dcterms:description", bfr.description); } // update format tag file contents if (bfr.format != null && !"".equals(bfr.format)) { formats = formats + bfr.format + "\t" + bfr.internalPath + "\n"; dfs.addFileMetadata(bfr.internalPath, "dcterms:format", bfr.format); } // update size tag file contents if (bfr.size != -1) { sizes = sizes + Long.toString(bfr.size) + "\t" + bfr.internalPath + "\n"; dfs.addFileMetadata(bfr.internalPath, "dcterms:extent", Long.toString(bfr.size)); } // update the manifests if (bfr.md5 != null && !"".equals(bfr.md5)) { md5Manifest = md5Manifest + bfr.md5 + "\t" + bfr.internalPath + "\n"; //dfs.addFileMetadata(bfr.internalPath, "premis:messageDigestAlgorithm", "MD5"); //dfs.addFileMetadata(bfr.internalPath, "premis:messageDigest", bfr.md5); } if (bfr.sha1 != null && !"".equals(bfr.sha1)) { sha1Manifest = sha1Manifest + bfr.sha1 + "\t" + bfr.internalPath + "\n"; //dfs.addFileMetadata(bfr.internalPath, "premis:messageDigestAlgorithm", "MD5"); //dfs.addFileMetadata(bfr.internalPath, "premis:messageDigest", bfr.md5); } this.writeToZip(bfr.getFile(), base + "/" + bfr.internalPath, out); } // write the primary dim file if (this.dim != null) { Map<String, String> dimChecksums = this.writeToZip(this.dim.toXML(), base + "/data/metadata.xml", out); md5Manifest = md5Manifest + dimChecksums.get("md5") + "\t" + "data/metadata.xml" + "\n"; sha1Manifest = sha1Manifest + dimChecksums.get("sha-1") + "\t" + "data/metadata.xml" + "\n"; dfs.addFileMetadata("data/metadata.xml", "dcterms:title", "data/metadata.xml"); dfs.addFileMetadata("data/metadata.xml", "dcterms:format", "text/xml"); } // write the datafile dim files for (String ident : this.subDim.keySet()) { String dataDir = Files.sanitizeFilename(ident); String zipPath = "data/" + dataDir + "/metadata.xml"; DIM dim = this.subDim.get(ident); Map<String, String> subDimChecksums = this.writeToZip(dim.toXML(), base + "/" + zipPath, out); md5Manifest = md5Manifest + subDimChecksums.get("md5") + "\t" + zipPath + "\n"; sha1Manifest = sha1Manifest + subDimChecksums.get("sha-1") + "\t" + zipPath + "\n"; dfs.addFileMetadata(zipPath, "dcterms:title", zipPath); dfs.addFileMetadata(zipPath, "dcterms:format", "text/xml"); } // write the DANS files.xml document Map<String, String> filesChecksums = this.writeToZip(dfs.toXML(), base + "/metadata/files.xml", out); tagmanifest = tagmanifest + filesChecksums.get("md5") + "\t" + "metadata/files.xml" + "\n"; // write the DANS dataset.xml document if (this.ddm != null) { Map<String, String> datasetChecksums = this.writeToZip(this.ddm.toXML(), base + "/metadata/dataset.xml", out); tagmanifest = tagmanifest + datasetChecksums.get("md5") + "\t" + "metadata/dataset.xml" + "\n"; } // write the custom tag files if (!"".equals(descriptions)) { Map<String, String> checksums = this.writeToZip(descriptions, base + "/bitstream-description.txt", out); tagmanifest = tagmanifest + checksums.get("md5") + "\tbitstream-description.txt" + "\n"; } if (!"".equals(formats)) { Map<String, String> checksums = this.writeToZip(formats, base + "/bitstream-format.txt", out); tagmanifest = tagmanifest + checksums.get("md5") + "\tbitstream-format.txt" + "\n"; } if (!"".equals(sizes)) { Map<String, String> checksums = this.writeToZip(sizes, base + "/bitstream-size.txt", out); tagmanifest = tagmanifest + checksums.get("md5") + "\tbitstream-size.txt" + "\n"; } // write the checksum manifests if (!"".equals(md5Manifest)) { Map<String, String> manifestChecksums = this.writeToZip(md5Manifest, base + "/manifest-md5.txt", out); tagmanifest = tagmanifest + manifestChecksums.get("md5") + "\tmanifest-md5.txt" + "\n"; } if (!"".equals(sha1Manifest)) { Map<String, String> manifestChecksums = this.writeToZip(sha1Manifest, base + "/manifest-sha1.txt", out); tagmanifest = tagmanifest + manifestChecksums.get("md5") + "\tmanifest-sha1.txt" + "\n"; } // write the bagit.txt String bagitfile = "BagIt-Version: 0.97\nTag-File-Character-Encoding: UTF-8"; Map<String, String> bagitChecksums = this.writeToZip(bagitfile, base + "/bagit.txt", out); tagmanifest = tagmanifest + bagitChecksums.get("md5") + "\tbagit.txt" + "\n"; // write the bag-info.txt Date now = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-dd'T'HH:mm:ss.SSSX"); String createdDate = sdf.format(now); String baginfofile = "Created: " + createdDate; Map<String, String> baginfoChecksums = this.writeToZip(baginfofile, base + "/bag-info.txt", out); tagmanifest = tagmanifest + baginfoChecksums.get("md5") + "\tbag-info.txt" + "\n"; // finally write the tag manifest if (!"".equals(tagmanifest)) { this.writeToZip(tagmanifest, base + "/tagmanifest-md5.txt", out); } out.close(); } // we need to conform to the old interface, so can only throw RuntimeExceptions catch (IOException e) { throw new RuntimeException(e); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } } /** * Clean out any cached data in the working directory * * @throws IOException */ public void cleanupWorkingDir() throws IOException { if (this.workingDir.exists()) { log.debug("Cleaning up working directory " + this.workingDir.getAbsolutePath()); FileUtils.deleteDirectory(this.workingDir); } } /** * Delete the zip file */ public void cleanupZip() { if (this.zipFile.exists()) { log.debug("Cleaning up zip file " + this.zipFile.getAbsolutePath()); this.zipFile.delete(); } } /** * Write the file referenced by the file handle to the given path inside the given zip output stream * * @param file The file reference * @param path The path within the zip file to store a copy of the file * @param out The ZipOutputStream to write the file to * @return The MD5 digest of the file * @throws IOException * @throws NoSuchAlgorithmException */ private Map<String, String> writeToZip(File file, String path, ZipOutputStream out) throws IOException, NoSuchAlgorithmException { FileInputStream fi = new FileInputStream(file); return this.writeToZip(fi, path, out); } /** * Write a text file containing the supplied string to the given path inside the given zip output stream * * @param str The string to write into a file * @param path The path within the zip file to store the resulting text file * @param out The ZipOutputStream to write the file to * @return The MD5 digest of the resulting text file * @throws IOException * @throws NoSuchAlgorithmException */ private Map<String, String> writeToZip(String str, String path, ZipOutputStream out) throws IOException, NoSuchAlgorithmException { ByteArrayInputStream bais = new ByteArrayInputStream(str.getBytes()); return this.writeToZip(bais, path, out); } /** * Write the data from the input stream to the given path inside the given zip output stream * @param fi InputStream to source data from * @param path The path within the zip file to store the resulting file * @param out The ZipOutputStream to write the file to * @return The MD5 digest of the resulting text file * @throws IOException * @throws NoSuchAlgorithmException */ private Map<String, String> writeToZip(InputStream fi, String path, ZipOutputStream out) throws IOException, NoSuchAlgorithmException { MessageDigest mdmd5 = MessageDigest.getInstance("MD5"); MessageDigest mdsha1 = MessageDigest.getInstance("SHA-1"); BufferedInputStream origin = new BufferedInputStream(fi, BUFFER); DigestInputStream inner = new DigestInputStream(origin, mdmd5); DigestInputStream dis = new DigestInputStream(inner, mdsha1); ZipEntry entry = new ZipEntry(path); out.putNextEntry(entry); int count; byte data[] = new byte[BUFFER]; while((count = dis.read(data, 0, BUFFER)) != -1) { out.write(data, 0, count); } origin.close(); String md5hex = Files.digestToString(mdmd5); String sha1hex = Files.digestToString(mdsha1); Map<String, String> ret = new HashMap<String, String>(); ret.put("md5", md5hex); ret.put("sha-1", sha1hex); return ret; } }
src/main/java/org/datadryad/dansbagit/DANSBag.java
package org.datadryad.dansbagit; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.apache.log4j.Logger; import java.io.*; import java.security.DigestInputStream; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.text.SimpleDateFormat; import java.util.*; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; /** * Main class which manages interactions with a Dryad/DANS formatted Bag * * This allows the BagIt packages to be constructed from files on disk, or for a * zipped BagIt to be read and opened. * * The DANS Bag format is as follows: * * <pre> * base directory/ * | bagit.txt * | bitstream-description.txt * | bitstream-format.txt * | bitstream-size.txt * | manifest-md5.txt * | tagmanifest-md5.txt * \--- metadata * | dataset.xml * | files.xml * \--- data/ * | metadata.xml * \--- [Data File DOI] * | metadata.xml * \--- [DSpace Bundle Name] * | [DSpace Bitstreams] *</pre> */ public class DANSBag { private static Logger log = Logger.getLogger(DANSBag.class); /** Buffer size to be used when chunking through input streams */ private static final int BUFFER = 8192; /** * Inner class to provide a reference to a file in the Bag. Since the file in the bag * may have different types, different sources for its input stream, and different tag * properties, this allows us to provide a consistent wrapper for internal use. */ class BagFileReference { public ZipEntry zipEntry = null; private File file = null; public String filename = null; public String fullPath = null; public String internalPath = null; public String description = null; public String format = null; public long size = -1; public String md5 = null; public String sha1 = null; public String dataFileIdent = null; public String bundle = null; public File getFile() { if (this.file == null) { this.file = new File(fullPath); } return this.file; } } private File zipFile = null; private File workingDir = null; private String name = null; private List<BagFileReference> fileRefs = new ArrayList<BagFileReference>(); private DDM ddm = null; private DIM dim = null; private Map<String, DIM> subDim = new HashMap<String, DIM>(); /** * Create a BagIt with the given name, using the provided zip as input or output, and with * the given working directory for temporary storage * * @param name name to use for the bag. This will form the top level directory inside the zip * @param zipPath path to read in or output zip content * @param workingDir directory used for temporary storage */ public DANSBag(String name, String zipPath, String workingDir) { this(name, new File(zipPath), new File(workingDir)); } /** * Create a BagIt with the given name, using the provided zip as input or output, and with * the given working directory for temporary storage * * @param name name to use for the bag. This will form the top level directory inside the zip * @param zipFile path to read in or output zip content * @param workingDir directory used for temporary storage */ public DANSBag(String name, File zipFile, File workingDir) { this.zipFile = zipFile; this.workingDir = workingDir; this.name = name; log.debug("Creating DANSBag object around zipfile " + zipFile.getAbsolutePath() + " using working directory " + workingDir.getAbsolutePath() + " with name " + name); if (zipFile.exists()) { log.debug("Zipfile " + zipFile.getAbsolutePath() + " exists, loading data from there"); // load the bag this.loadBag(zipFile); } } /** * Load state from the given zip file * * Not yet implemented * * @param file */ public void loadBag(File file) { // TODO } /** * Get the full path to the working directory * * @return path to the working directory */ public String getWorkingDir() { return this.workingDir.getAbsolutePath(); } /** * Get the MD5 of the zip. The zip must exist for this to happen, so you either need to have * created this object around a zip file, or have called writeFile first. If you try to call * it otherwise, you will get a RuntimeException * * @return the MD5 hex string for the zip file * @throws IOException if there's a problem reading the file */ public String getMD5() throws IOException { if (!this.zipFile.exists()) { throw new RuntimeException("You must writeFile before you can calculate the md5"); } try { FileInputStream fis = new FileInputStream(this.zipFile); String md5 = Files.md5Hex(fis); fis.close(); return md5; // if we could use DigestUtils (which we can't because DSpace) this would be quicker and cleaner this way // String md5 = DigestUtils.md5Hex(fis); } catch(NoSuchAlgorithmException e) { // this shouldn't happen throw new RuntimeException(e); } } /** * Get the name of the zip file. You can only do this once the zip file exists, otherwise you will get a RuntimeException * * @return the name of the zip file */ public String getZipName() { if (!this.zipFile.exists()) { throw new RuntimeException("You must writeFile before you can ask questions about the zip"); } return this.zipFile.getName(); } /** * Get the full path to the zip file. You can only do this once the zip file exists, otherwise you will get a RuntimeException * * @return the full path to the zip file */ public String getZipPath() { if (!this.zipFile.exists()) { throw new RuntimeException("You must writeFile before you can ask questions about the zip"); } return this.zipFile.getAbsolutePath(); } /** * Get an input stream for the entire zip file. You can only do this once the zip file exists, otherwise you will get a RuntimeException * * @return an input stream from which you can retrieve the entire zip file * * @throws Exception */ public InputStream getInputStream() { if (!this.zipFile.exists()) { throw new RuntimeException("You must writeFile before you can read the input stream"); } try { return new FileInputStream(this.zipFile); } catch (FileNotFoundException e) { // this can't happen, as we've already checked throw new RuntimeException(e); } } /** * Get an iterator which will allow you to iterate over input streams for defined size chunks of the zip file. * * You can only do this once the zip file exists, otherwise you will get a RuntimeException * * @param size the size (in bytes) of the chunks (all except the final chunk will be this size) * @param md5 whether to calculate the md5 of each chunk as it is read * @return a file segment iterator which can be used to retrieve input streams for subsequent chunks * @throws Exception */ public FileSegmentIterator getSegmentIterator(long size, boolean md5) { if (!this.zipFile.exists()) { throw new RuntimeException("You must writeFile before you can read the segments"); } try { return new FileSegmentIterator(this.zipFile, size, md5); } catch (IOException e) { // shouldn't happen, as we have checked the file's existence already throw new RuntimeException(e); } } /** * How big is the zip file. You can only do this once the zip file exists, otherwise you will get a RuntimeException * * @return size of zip file in bytes */ public long size() { if (!this.zipFile.exists()) { throw new RuntimeException("You must writeFile before you can determine the size"); } return this.zipFile.length(); } /** * Add a bitstream to the bag. This will stage the file in the working directory. * * @param is input stream where the bitstream can be read from * @param filename the filename * @param format the mimetype of the file * @param description a description of the file * @param dataFileIdent an identifier for the data file to which this bitstream belongs * @param bundle the DSpace bundle the bitstream came from * @throws IOException */ public void addBitstream(InputStream is, String filename, String format, String description, String dataFileIdent, String bundle) throws IOException { log.info("Adding bitstream to DANSBag: filename= " + filename + "; format= " + format + "; data_file=" + dataFileIdent + "; bundle=" + bundle); // escape the dataFileIdent String dataFilename = Files.sanitizeFilename(dataFileIdent); log.debug("Sanitised dataFileIdent from " + dataFileIdent + " to " + dataFilename); // get the correct folder/filename for the bitstream String internalDir = "data" + File.separator + dataFilename + File.separator + bundle; String internalFile = internalDir + File.separator + filename; String targetDir = this.workingDir.getAbsolutePath() + File.separator + internalDir; String filePath = targetDir + File.separator + filename; log.info("Bistream will be temporarily staged at " + filePath); log.info("Bitstream will be written to internal zip path " + internalFile); // ensure that the target directory exists (new File(targetDir)).mkdirs(); // wrap the input stream in something that can get the MD5 as we read it MessageDigest mdmd5 = null; MessageDigest mdsha1 = null; try { mdmd5 = MessageDigest.getInstance("MD5"); mdsha1 = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } DigestInputStream inner = new DigestInputStream(is, mdmd5); DigestInputStream dis = new DigestInputStream(inner, mdsha1); // write the input stream to the working directory, in the appropriate folder OutputStream os = new FileOutputStream(filePath); IOUtils.copy(dis, os); // add the bitstream information to our internal data structure BagFileReference bfr = new BagFileReference(); bfr.filename = filename; bfr.fullPath = filePath; bfr.internalPath = internalFile; bfr.md5 = Files.digestToString(mdmd5); bfr.sha1 = Files.digestToString(mdsha1); bfr.description = description; bfr.format = format; bfr.size = (new File(filePath)).length(); bfr.dataFileIdent = dataFileIdent; bfr.bundle = bundle; this.fileRefs.add(bfr); } /** * Set the DDM metdata object for this bag * * @param ddm */ public void setDDM(DDM ddm) { this.ddm = ddm; } /** * Set the dataset DIM metadata for this bag * * @param dim */ public void setDatasetDIM(DIM dim) { this.dim = dim; } /** * Set the data file DIM metadata for the given data file identifier * * @param dim * @param dataFileIdent the identifier for the data file */ public void addDatafileDIM(DIM dim, String dataFileIdent) { this.subDim.put(dataFileIdent, dim); } /** * Write the in-memory information and contents of the working directory to the zip file. * * You can only do this once, and it will refuse to run again if the zip file is already present. If you want to * run it again in the same thread you'll need to call cleanupZip first. Also, you shouldn't need to do that - only * call this when you have finished assembling the bag. */ public void writeToFile() { try { // if this bag was initialised from a zip file, we can't write back to it - just too // complicated. if (this.zipFile.exists()) { log.error("Attempt to write bag when zip already exists"); throw new RuntimeException("Cannot re-write a modified bag file. You should either create a new bag file from the source files, or read in the old zip file and pass the components in here."); } log.info("Writing bag to file " + this.zipFile.getAbsolutePath()); String base = Files.sanitizeFilename(this.name); // prepare our zipped output stream FileOutputStream dest = new FileOutputStream(this.zipFile); ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(dest)); String descriptions = ""; String formats = ""; String sizes = ""; String md5Manifest = ""; String sha1Manifest = ""; String tagmanifest = ""; DANSFiles dfs = new DANSFiles(); // write the bitstreams, and gather their metadata for the tag files as we go through for (BagFileReference bfr : this.fileRefs) { // add the filename to the files.xml metadata dfs.addFileMetadata(bfr.internalPath, "dcterms:title", bfr.filename); // update description tag file contents if (bfr.description != null && !"".equals(bfr.description)) { descriptions = descriptions + bfr.description + "\t" + bfr.internalPath + "\n"; dfs.addFileMetadata(bfr.internalPath, "dcterms:description", bfr.description); } // update format tag file contents if (bfr.format != null && !"".equals(bfr.format)) { formats = formats + bfr.format + "\t" + bfr.internalPath + "\n"; dfs.addFileMetadata(bfr.internalPath, "dcterms:format", bfr.format); } // update size tag file contents if (bfr.size != -1) { sizes = sizes + Long.toString(bfr.size) + "\t" + bfr.internalPath + "\n"; dfs.addFileMetadata(bfr.internalPath, "dcterms:extent", Long.toString(bfr.size)); } // update the manifests if (bfr.md5 != null && !"".equals(bfr.md5)) { md5Manifest = md5Manifest + bfr.md5 + "\t" + bfr.internalPath + "\n"; //dfs.addFileMetadata(bfr.internalPath, "premis:messageDigestAlgorithm", "MD5"); //dfs.addFileMetadata(bfr.internalPath, "premis:messageDigest", bfr.md5); } if (bfr.sha1 != null && !"".equals(bfr.sha1)) { sha1Manifest = sha1Manifest + bfr.sha1 + "\t" + bfr.internalPath + "\n"; //dfs.addFileMetadata(bfr.internalPath, "premis:messageDigestAlgorithm", "MD5"); //dfs.addFileMetadata(bfr.internalPath, "premis:messageDigest", bfr.md5); } this.writeToZip(bfr.getFile(), base + "/" + bfr.internalPath, out); } // write the DANS files.xml document Map<String, String> filesChecksums = this.writeToZip(dfs.toXML(), base + "/metadata/files.xml", out); tagmanifest = tagmanifest + filesChecksums.get("md5") + "\t" + "metadata/files.xml" + "\n"; // write the DANS dataset.xml document if (this.ddm != null) { Map<String, String> datasetChecksums = this.writeToZip(this.ddm.toXML(), base + "/metadata/dataset.xml", out); tagmanifest = tagmanifest + datasetChecksums.get("md5") + "\t" + "metadata/dataset.xml" + "\n"; } // write the primary dim file if (this.dim != null) { Map<String, String> dimChecksums = this.writeToZip(this.dim.toXML(), base + "/data/metadata.xml", out); md5Manifest = md5Manifest + dimChecksums.get("md5") + "\t" + "data/metadata.xml" + "\n"; sha1Manifest = sha1Manifest + dimChecksums.get("sha-1") + "\t" + "data/metadata.xml" + "\n"; } // write the datafile dim files for (String ident : this.subDim.keySet()) { String dataDir = Files.sanitizeFilename(ident); String zipPath = "data/" + dataDir + "/metadata.xml"; DIM dim = this.subDim.get(ident); Map<String, String> subDimChecksums = this.writeToZip(dim.toXML(), base + "/" + zipPath, out); md5Manifest = md5Manifest + subDimChecksums.get("md5") + "\t" + zipPath + "\n"; sha1Manifest = sha1Manifest + subDimChecksums.get("sha-1") + "\t" + zipPath + "\n"; } // write the custom tag files if (!"".equals(descriptions)) { Map<String, String> checksums = this.writeToZip(descriptions, base + "/bitstream-description.txt", out); tagmanifest = tagmanifest + checksums.get("md5") + "\tbitstream-description.txt" + "\n"; } if (!"".equals(formats)) { Map<String, String> checksums = this.writeToZip(formats, base + "/bitstream-format.txt", out); tagmanifest = tagmanifest + checksums.get("md5") + "\tbitstream-format.txt" + "\n"; } if (!"".equals(sizes)) { Map<String, String> checksums = this.writeToZip(sizes, base + "/bitstream-size.txt", out); tagmanifest = tagmanifest + checksums.get("md5") + "\tbitstream-size.txt" + "\n"; } // write the checksum manifests if (!"".equals(md5Manifest)) { Map<String, String> manifestChecksums = this.writeToZip(md5Manifest, base + "/manifest-md5.txt", out); tagmanifest = tagmanifest + manifestChecksums.get("md5") + "\tmanifest-md5.txt" + "\n"; } if (!"".equals(sha1Manifest)) { Map<String, String> manifestChecksums = this.writeToZip(sha1Manifest, base + "/manifest-sha1.txt", out); tagmanifest = tagmanifest + manifestChecksums.get("md5") + "\tmanifest-sha1.txt" + "\n"; } // write the bagit.txt String bagitfile = "BagIt-Version: 0.97\nTag-File-Character-Encoding: UTF-8"; Map<String, String> bagitChecksums = this.writeToZip(bagitfile, base + "/bagit.txt", out); tagmanifest = tagmanifest + bagitChecksums.get("md5") + "\tbagit.txt" + "\n"; // write the bag-info.txt Date now = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-dd'T'HH:mm:ssX"); String createdDate = sdf.format(now); String baginfofile = "Created: " + createdDate; Map<String, String> baginfoChecksums = this.writeToZip(baginfofile, base + "/bag-info.txt", out); tagmanifest = tagmanifest + baginfoChecksums.get("md5") + "\tbag-info.txt" + "\n"; // finally write the tag manifest if (!"".equals(tagmanifest)) { this.writeToZip(tagmanifest, base + "/tagmanifest-md5.txt", out); } out.close(); } // we need to conform to the old interface, so can only throw RuntimeExceptions catch (IOException e) { throw new RuntimeException(e); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } } /** * Clean out any cached data in the working directory * * @throws IOException */ public void cleanupWorkingDir() throws IOException { if (this.workingDir.exists()) { log.debug("Cleaning up working directory " + this.workingDir.getAbsolutePath()); FileUtils.deleteDirectory(this.workingDir); } } /** * Delete the zip file */ public void cleanupZip() { if (this.zipFile.exists()) { log.debug("Cleaning up zip file " + this.zipFile.getAbsolutePath()); this.zipFile.delete(); } } /** * Write the file referenced by the file handle to the given path inside the given zip output stream * * @param file The file reference * @param path The path within the zip file to store a copy of the file * @param out The ZipOutputStream to write the file to * @return The MD5 digest of the file * @throws IOException * @throws NoSuchAlgorithmException */ private Map<String, String> writeToZip(File file, String path, ZipOutputStream out) throws IOException, NoSuchAlgorithmException { FileInputStream fi = new FileInputStream(file); return this.writeToZip(fi, path, out); } /** * Write a text file containing the supplied string to the given path inside the given zip output stream * * @param str The string to write into a file * @param path The path within the zip file to store the resulting text file * @param out The ZipOutputStream to write the file to * @return The MD5 digest of the resulting text file * @throws IOException * @throws NoSuchAlgorithmException */ private Map<String, String> writeToZip(String str, String path, ZipOutputStream out) throws IOException, NoSuchAlgorithmException { ByteArrayInputStream bais = new ByteArrayInputStream(str.getBytes()); return this.writeToZip(bais, path, out); } /** * Write the data from the input stream to the given path inside the given zip output stream * @param fi InputStream to source data from * @param path The path within the zip file to store the resulting file * @param out The ZipOutputStream to write the file to * @return The MD5 digest of the resulting text file * @throws IOException * @throws NoSuchAlgorithmException */ private Map<String, String> writeToZip(InputStream fi, String path, ZipOutputStream out) throws IOException, NoSuchAlgorithmException { MessageDigest mdmd5 = MessageDigest.getInstance("MD5"); MessageDigest mdsha1 = MessageDigest.getInstance("SHA-1"); BufferedInputStream origin = new BufferedInputStream(fi, BUFFER); DigestInputStream inner = new DigestInputStream(origin, mdmd5); DigestInputStream dis = new DigestInputStream(inner, mdsha1); ZipEntry entry = new ZipEntry(path); out.putNextEntry(entry); int count; byte data[] = new byte[BUFFER]; while((count = dis.read(data, 0, BUFFER)) != -1) { out.write(data, 0, count); } origin.close(); String md5hex = Files.digestToString(mdmd5); String sha1hex = Files.digestToString(mdsha1); Map<String, String> ret = new HashMap<String, String>(); ret.put("md5", md5hex); ret.put("sha-1", sha1hex); return ret; } }
add metadata dim files to files.xml registry
src/main/java/org/datadryad/dansbagit/DANSBag.java
add metadata dim files to files.xml registry
Java
bsd-3-clause
02af42e84d5b89e63c63db9a9a27d9002312560d
0
Clunker5/tregmine-2.0,EmilHernvall/tregmine,EmilHernvall/tregmine,EmilHernvall/tregmine,Clunker5/tregmine-2.0
package info.tregmine.inventoryspy; //import net.minecraft.server.Item; import org.bukkit.ChatColor; import org.bukkit.GameMode; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.block.Chest; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.block.Action; import org.bukkit.event.player.PlayerDropItemEvent; import org.bukkit.event.player.PlayerGameModeChangeEvent; import org.bukkit.event.player.PlayerInteractEvent; //import org.bukkit.event.player.PlayerInventoryEvent; import org.bukkit.event.player.PlayerPickupItemEvent; import org.bukkit.inventory.Inventory; public class SpyPlayerListener implements Listener { private final Main plugin; public SpyPlayerListener(Main instance) { this.plugin = instance; plugin.getServer(); } @EventHandler public void onPlayerGameModeChange(PlayerGameModeChangeEvent event) { event.getPlayer().getInventory().clear(); } @EventHandler public void onPlayerInteract(PlayerInteractEvent event) { if ((event.getAction() == Action.RIGHT_CLICK_BLOCK || event.getAction() == Action.LEFT_CLICK_BLOCK)) { if(event.getClickedBlock().getState() instanceof Chest) { Chest chest = (Chest) event.getClickedBlock().getState(); Inventory invent = chest.getBlockInventory(); Location loc = event.getClickedBlock().getLocation(); // this.plugin.log.info("" + event.getClickedBlock().getData()); for (int i = 0; i < invent.getSize(); i++) { if (invent.getItem(i) != null) { this.plugin.log.info("CHEST: " + "(" + loc.getBlockX() + "," + loc.getBlockY() + "," + loc.getBlockZ() + ")" + "(" + i + ")" + "(" + event.getPlayer().getName() + ")" + invent.getItem(i).getType().toString()+ "(" + invent.getItem(i).getType().getId() + ")" + ":" + invent.getItem(i).getData().toString() + " :: " + invent.getItem(i).getAmount()); } } } if (event.getClickedBlock().getType() == Material.CHEST && event.getPlayer().getGameMode() == GameMode.CREATIVE) { // event.getPlayer().sendMessage("error"); event.setCancelled(true); return; } } } // @EventHandler // public void onInventoryOpen (PlayerInventoryEvent event) { // event.getPlayer().sendMessage("INV"); // this.plugin.log.info(event.getInventory().getItem(0).getType().name()); // } @EventHandler public void onPlayerDropItem (PlayerDropItemEvent event) { if (event.getPlayer().getGameMode() == GameMode.CREATIVE) { event.setCancelled(true); return; } info.tregmine.api.TregminePlayer tregminePlayer = this.plugin.tregmine.tregminePlayer.get(event.getPlayer().getName()); this.plugin.whoDropedItem.put(event.getItemDrop().hashCode(), tregminePlayer.getName()); } @EventHandler public void onPlayerPickupItem (PlayerPickupItemEvent event){ if (event.getPlayer().getGameMode() == GameMode.CREATIVE) { event.setCancelled(true); return; } if (event.getItem().getItemStack().getType() == Material.MOB_SPAWNER) { event.setCancelled(true); return; } if (this.plugin.whoDropedItem.containsKey(event.getItem().hashCode())) { if (event.isCancelled()) { return; } String from = this.plugin.whoDropedItem.get(event.getItem().hashCode()); if (from != null && !event.getPlayer().getName().matches(from)) { info.tregmine.api.TregminePlayer tregminePlayerFrom = this.plugin.tregmine.tregminePlayer.get(from); info.tregmine.api.TregminePlayer tregminePlayerTo = this.plugin.tregmine.tregminePlayer.get(event.getPlayer().getName()); this.plugin.log.info (event.getItem().getItemStack().getAmount() + ":" + event.getItem().getItemStack().getType().toString() + " " + tregminePlayerFrom.getChatName() + " ==> " + tregminePlayerTo.getChatName() ); if (!tregminePlayerFrom.getMetaBoolean("invis") && ! tregminePlayerTo.getMetaBoolean("invis")) { event.getPlayer().sendMessage(ChatColor.YELLOW + "You got " + event.getItem().getItemStack().getAmount() + " " + event.getItem().getItemStack().getType().toString().toLowerCase() + ChatColor.YELLOW + " from " + tregminePlayerFrom.getChatName() ); this.plugin.getServer().getPlayer(from).sendMessage(ChatColor.YELLOW + "You gave " + event.getItem().getItemStack().getAmount() + " " + event.getItem().getItemStack().getType().toString().toLowerCase() + " to " + tregminePlayerTo.getChatName() ); } } this.plugin.whoDropedItem.put(event.getItem().hashCode(), null); } } }
InventorySpy/src/info/tregmine/inventoryspy/SpyPlayerListener.java
package info.tregmine.inventoryspy; //import net.minecraft.server.Item; import org.bukkit.ChatColor; import org.bukkit.GameMode; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.block.Chest; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.block.Action; import org.bukkit.event.player.PlayerDropItemEvent; import org.bukkit.event.player.PlayerGameModeChangeEvent; import org.bukkit.event.player.PlayerInteractEvent; //import org.bukkit.event.player.PlayerInventoryEvent; import org.bukkit.event.player.PlayerPickupItemEvent; import org.bukkit.inventory.Inventory; public class SpyPlayerListener implements Listener { private final Main plugin; public SpyPlayerListener(Main instance) { this.plugin = instance; plugin.getServer(); } @EventHandler public void onPlayerGameModeChange(PlayerGameModeChangeEvent event) { event.getPlayer().getInventory().clear(); } @EventHandler public void onPlayerInteract(PlayerInteractEvent event) { if ((event.getAction() == Action.RIGHT_CLICK_BLOCK || event.getAction() == Action.LEFT_CLICK_BLOCK)) { if(event.getClickedBlock().getState() instanceof Chest) { Chest chest = (Chest) event.getClickedBlock().getState(); Inventory invent = chest.getBlockInventory(); Location loc = event.getClickedBlock().getLocation(); this.plugin.log.info("" + event.getClickedBlock().getData()); for (int i = 0; i < invent.getSize(); i++) { if (invent.getItem(i) != null) { this.plugin.log.info("CHEST: " + "(" + loc.getBlockX() + "," + loc.getBlockY() + "," + loc.getBlockZ() + ")" + "(" + i + ")" + "(" + event.getPlayer().getName() + ")" + invent.getItem(i).getType().toString() + ":" + invent.getItem(i).getType().toString() + " :: " + invent.getItem(i).getAmount()); } } } if (event.getClickedBlock().getType() == Material.CHEST && event.getPlayer().getGameMode() == GameMode.CREATIVE) { // event.getPlayer().sendMessage("error"); event.setCancelled(true); return; } } } // @EventHandler // public void onInventoryOpen (PlayerInventoryEvent event) { // event.getPlayer().sendMessage("INV"); // this.plugin.log.info(event.getInventory().getItem(0).getType().name()); // } @EventHandler public void onPlayerDropItem (PlayerDropItemEvent event) { if (event.getPlayer().getGameMode() == GameMode.CREATIVE) { event.setCancelled(true); return; } info.tregmine.api.TregminePlayer tregminePlayer = this.plugin.tregmine.tregminePlayer.get(event.getPlayer().getName()); this.plugin.whoDropedItem.put(event.getItemDrop().hashCode(), tregminePlayer.getName()); } @EventHandler public void onPlayerPickupItem (PlayerPickupItemEvent event){ if (event.getPlayer().getGameMode() == GameMode.CREATIVE) { event.setCancelled(true); return; } if (event.getItem().getItemStack().getType() == Material.MOB_SPAWNER) { event.setCancelled(true); return; } if (this.plugin.whoDropedItem.containsKey(event.getItem().hashCode())) { if (event.isCancelled()) { return; } String from = this.plugin.whoDropedItem.get(event.getItem().hashCode()); if (from != null && !event.getPlayer().getName().matches(from)) { info.tregmine.api.TregminePlayer tregminePlayerFrom = this.plugin.tregmine.tregminePlayer.get(from); info.tregmine.api.TregminePlayer tregminePlayerTo = this.plugin.tregmine.tregminePlayer.get(event.getPlayer().getName()); this.plugin.log.info (event.getItem().getItemStack().getAmount() + ":" + event.getItem().getItemStack().getType().toString() + " " + tregminePlayerFrom.getChatName() + " ==> " + tregminePlayerTo.getChatName() ); if (!tregminePlayerFrom.getMetaBoolean("invis") && ! tregminePlayerTo.getMetaBoolean("invis")) { event.getPlayer().sendMessage(ChatColor.YELLOW + "You got " + event.getItem().getItemStack().getAmount() + " " + event.getItem().getItemStack().getType().toString().toLowerCase() + ChatColor.YELLOW + " from " + tregminePlayerFrom.getChatName() ); this.plugin.getServer().getPlayer(from).sendMessage(ChatColor.YELLOW + "You gave " + event.getItem().getItemStack().getAmount() + " " + event.getItem().getItemStack().getType().toString().toLowerCase() + " to " + tregminePlayerTo.getChatName() ); } } this.plugin.whoDropedItem.put(event.getItem().hashCode(), null); } } }
extended chest log
InventorySpy/src/info/tregmine/inventoryspy/SpyPlayerListener.java
extended chest log
Java
bsd-3-clause
10672c4e1b3e5a821b190f70da6ad490eb394c95
0
krishagni/openspecimen,krishagni/openspecimen,krishagni/openspecimen
package com.krishagni.catissueplus.core.de.ui; import java.io.Writer; import java.util.Map; import java.util.Properties; import edu.common.dynamicextensions.domain.nui.AbstractLookupControl; public class UserControl extends AbstractLookupControl { private static final long serialVersionUID = 1L; private static final String LU_TABLE = "USER_VIEW"; private static final String ALT_KEY = "email_address"; private static final Properties LU_PV_SOURCE_PROPS = initPvSourceProps(); @Override public String getCtrlType() { return "userField"; } @Override public void getProps(Map<String, Object> props) { props.put("apiUrl", "rest/ng/users"); props.put("dataType", getDataType()); } public void serializeToXml(Writer writer, Properties props) { super.serializeToXml("userField", writer, props); } @Override public String getTableName() { return LU_TABLE; } @Override public Properties getPvSourceProps() { return LU_PV_SOURCE_PROPS; } @Override public String getAltKeyColumn() { return ALT_KEY; } private static Properties initPvSourceProps() { Properties props = new Properties(); props.put("apiUrl", "rest/ng/users"); props.put("searchTermName", "searchString"); props.put("resultFormat", "{{firstName}} {{lastName}}"); props.put("respField", "users"); return props; } }
WEB-INF/src/com/krishagni/catissueplus/core/de/ui/UserControl.java
package com.krishagni.catissueplus.core.de.ui; import java.io.Writer; import java.util.Map; import java.util.Properties; import edu.common.dynamicextensions.domain.nui.AbstractLookupControl; public class UserControl extends AbstractLookupControl { private static final long serialVersionUID = 1L; private static final String LU_TABLE = "USER_VIEW"; private static final String ALT_KEY = "email_address"; private static final Properties LU_PV_SOURCE_PROPS = initPvSourceProps(); @Override public String getCtrlType() { return "userField"; } @Override public void getProps(Map<String, Object> props) { props.put("apiUrl", "rest/ng/users"); props.put("dataType", getDataType()); } public void serializeToXml(Writer writer, Properties props) { super.serializeToXml("userField", writer, props); } @Override public String getTableName() { return LU_TABLE; } @Override public Properties getPvSourceProps() { return LU_PV_SOURCE_PROPS; } @Override public String getAltKeyColumn() { return ALT_KEY; } private static Properties initPvSourceProps() { Properties props = new Properties(); props.put("apiUrl", "rest/ng/users"); props.put("searchTermName", "searchString"); props.put("resultFormat", "{{lastName}}, {{firstName}}"); props.put("respField", "users"); return props; } }
OPSMN-2545 Issue: Name field in USER_VIEW is formed by concatenating first_name and last_name of user. But resultFormat of UserControl concats last_name and first_name. Fix: Fixed by changing the resultFormat of UserControl to concat first_name and last_name.
WEB-INF/src/com/krishagni/catissueplus/core/de/ui/UserControl.java
OPSMN-2545
Java
apache-2.0
72905e8b7938630fcec55752213c4c8171296bdb
0
soarcn/COCO-Accessory
adapter/src/androidTest/java/com/cocosw/adapter/TestAdapter.java
package com.cocosw.adapter; import android.app.Activity; import android.database.Cursor; /** * Project: Accessory * Created by LiaoKai(soarcn) on 2015/1/17. */ public class TestAdapter extends SingleTypeCursorAdapter { public TestAdapter(Activity activity, Cursor cursor, int flags, int layoutResourceId) { super(activity, cursor, flags, layoutResourceId); } @Override protected int[] getChildViewIds() { return new int[0]; } }
remove useless class
adapter/src/androidTest/java/com/cocosw/adapter/TestAdapter.java
remove useless class
Java
apache-2.0
4934f3968013ee55311367a01434d08339346feb
0
ThiagoGarciaAlves/encog-java-core,Crespo911/encog-java-core,spradnyesh/encog-java-core,danilodesousacubas/encog-java-core,SpenceSouth/encog-java-core,SpenceSouth/encog-java-core,ThiagoGarciaAlves/encog-java-core,Crespo911/encog-java-core,spradnyesh/encog-java-core,danilodesousacubas/encog-java-core,krzysztof-magosa/encog-java-core,krzysztof-magosa/encog-java-core
src/main/java/org/encog/neural/neat/training/opp/NEATMutate.java
package org.encog.neural.neat.training.opp; import java.util.Random; import org.encog.EncogError; import org.encog.engine.network.activation.ActivationFunction; import org.encog.mathutil.randomize.RandomChoice; import org.encog.mathutil.randomize.RangeRandomizer; import org.encog.ml.ea.genome.Genome; import org.encog.ml.ea.opp.EvolutionaryOperator; import org.encog.ml.ea.train.EvolutionaryAlgorithm; import org.encog.neural.neat.NEATNeuronType; import org.encog.neural.neat.NEATPopulation; import org.encog.neural.neat.training.NEATGenome; import org.encog.neural.neat.training.NEATInnovation; import org.encog.neural.neat.training.NEATLinkGene; import org.encog.neural.neat.training.NEATNeuronGene; import org.encog.neural.neat.training.NEATTraining; public class NEATMutate implements EvolutionaryOperator { private NEATTraining owner; private RandomChoice mutateChoices; private double mutateRate = 0.2; private double probNewMutate = 0.1; private double maxPertubation = 0.5; private int maxTries = 5; public NEATMutate() { this.mutateChoices = new RandomChoice(new double[] { 0.988, 0.001, 0.01, 0.001 }); //this.mutateChoices = new RandomChoice(new double[] { 0.75, 0.1, 0.1, 0.05 }); } @Override public void performOperation(Random rnd, Genome[] parents, int parentIndex, Genome[] offspring, int offspringIndex) { if (parents[0] != offspring[0]) { throw new EncogError( "This mutation only works when the offspring and parents are the same. That is, it only mutates itself."); } NEATGenome genome = (NEATGenome) parents[0]; int option = this.mutateChoices.generate(rnd); switch (option) { case 0: // mutate weight mutateWeights(genome); break; case 1: // add node if (genome.getNeuronsChromosome().size() < this.owner .getMaxIndividualSize()) { addNeuron(genome); } break; case 2: // add connection // now there's the chance a link may be added addLink(genome); break; case 3: // remove connection removeLink(genome); break; } } /** * Mutate the genome by adding a link to this genome. * * @param mutationRate * The mutation rate. * @param chanceOfLooped * The chance of a self-connected neuron. * @param numTrysToFindLoop * The number of tries to find a loop. * @param numTrysToAddLink * The number of tries to add a link. */ private void addLink(NEATGenome target) { int countTrysToAddLink = this.maxTries; // the link will be between these two neurons long neuron1ID = -1; long neuron2ID = -1; // try to add a link while ((countTrysToAddLink--) > 0) { final NEATNeuronGene neuron1 = chooseRandomNeuron(target, true); final NEATNeuronGene neuron2 = chooseRandomNeuron(target, false); if( neuron1==null || neuron2==null ) { return; } if (!isDuplicateLink(target, neuron1.getId(), neuron2.getId()) // no duplicates && (neuron2.getNeuronType() != NEATNeuronType.Bias) // do not go to a bias neuron && (neuron1.getNeuronType() != NEATNeuronType.Output) // do not go from an output neuron && (neuron2.getNeuronType() != NEATNeuronType.Input)) { // do not go to an input neuron neuron1ID = neuron1.getId(); neuron2ID = neuron2.getId(); break; } } // did we fail to find a link if ((neuron1ID < 0) || (neuron2ID < 0)) { return; } double r = ((NEATPopulation)target.getPopulation()).getWeightRange(); createLink(target, neuron1ID, neuron2ID, RangeRandomizer.randomize(-r,r)); } private void createLink(NEATGenome target, long neuron1ID, long neuron2ID, double weight) { // check to see if this innovation has already been tried NEATInnovation innovation = owner.getInnovations().findInnovation(neuron1ID, neuron2ID); // now create this link final NEATLinkGene linkGene = new NEATLinkGene(neuron1ID, neuron2ID, true, innovation.getInnovationID(), weight); target.getLinksChromosome().add(linkGene); } /** * Mutate the genome by adding a neuron. * * @param mutationRate * The mutation rate. * @param numTrysToFindOldLink * The number of tries to find a link to split. */ public void addNeuron(NEATGenome target) { int countTrysToFindOldLink = this.maxTries; NEATPopulation pop = ((NEATPopulation)target.getPopulation()); // the link to split NEATLinkGene splitLink = null; final int sizeBias = owner.getInputCount() + owner.getOutputCount() + 10; // if there are not at least int upperLimit; if (target.getLinksChromosome().size() < sizeBias) { upperLimit = target.getNumGenes() - 1 - (int) Math.sqrt(target.getNumGenes()); } else { upperLimit = target.getNumGenes() - 1; } while ((countTrysToFindOldLink--) > 0) { // choose a link, use the square root to prefer the older links final int i = RangeRandomizer.randomInt(0, upperLimit); final NEATLinkGene link = (NEATLinkGene) target .getLinksChromosome().get(i); // get the from neuron final long fromNeuron = link.getFromNeuronID(); if ((link.isEnabled()) && (((NEATNeuronGene) target.getNeuronsChromosome().get( getElementPos(target, fromNeuron))).getNeuronType() != NEATNeuronType.Bias)) { splitLink = link; break; } } if (splitLink == null) { return; } splitLink.setEnabled(false); final long from = splitLink.getFromNeuronID(); final long to = splitLink.getToNeuronID(); NEATInnovation innovation = owner.getInnovations().findInnovationSplit(from, to); // add the splitting neuron ActivationFunction af = this.owner.getNEATPopulation().getActivationFunctions().pick(new Random()); target.getNeuronsChromosome().add( new NEATNeuronGene(NEATNeuronType.Hidden, af, innovation .getNeuronID(), innovation.getInnovationID())); // add the other two sides of the link createLink(target, from, innovation.getNeuronID(), splitLink.getWeight()); createLink(target, innovation.getNeuronID(), to, pop.getWeightRange()); } /** * Choose a random neuron. * * @param includeInput * Should the input and bias neurons be included. * @return The random neuron. */ private NEATNeuronGene chooseRandomNeuron(NEATGenome target, final boolean choosingFrom) { int start; if (choosingFrom) { start = 0; } else { start = owner.getInputCount() + 1; } // if this network will not "cycle" then output neurons cannot be source // neurons if (!choosingFrom) { int ac = ((NEATPopulation) target.getPopulation()) .getActivationCycles(); if (ac == 1) { start += target.getOutputCount(); } } int end = target .getNeuronsChromosome().size() - 1; // no neurons to pick! if( start>end ) { return null; } final int neuronPos = RangeRandomizer.randomInt(start, end); final NEATNeuronGene neuronGene = (NEATNeuronGene) target .getNeuronsChromosome().get(neuronPos); return neuronGene; } /** * Get the specified neuron's index. * * @param neuronID * The neuron id to check for. * @return The index. */ private int getElementPos(NEATGenome target, final long neuronID) { for (int i = 0; i < target.getNeuronsChromosome().size(); i++) { final NEATNeuronGene neuronGene = (NEATNeuronGene) target .getNeuronsChromosome().get(i); if (neuronGene.getId() == neuronID) { return i; } } return -1; } /** * Determine if this is a duplicate link. * * @param fromNeuronID * The from neuron id. * @param toNeuronID * The to neuron id. * @return True if this is a duplicate link. */ public boolean isDuplicateLink(NEATGenome target, final long fromNeuronID, final long toNeuronID) { for (final NEATLinkGene linkGene : target.getLinksChromosome()) { if ((linkGene.getFromNeuronID() == fromNeuronID) && (linkGene.getToNeuronID() == toNeuronID)) { return true; } } return false; } /** * Mutate the weights. * * @param mutateRate * The mutation rate. * @param probNewMutate * The probability of a whole new weight. * @param maxPertubation * The max perturbation. */ public void mutateWeights(NEATGenome target) { double weightRange = ((NEATPopulation)target.getPopulation()).getWeightRange(); for (final NEATLinkGene linkGene : target.getLinksChromosome()) { if (Math.random() < mutateRate) { if (Math.random() < probNewMutate) { linkGene.setWeight(RangeRandomizer.randomize(-weightRange, weightRange)); } else { double w = linkGene.getWeight() + RangeRandomizer.randomize(-1, 1) * maxPertubation; w = NEATPopulation.clampWeight(w,weightRange); linkGene.setWeight(w); } } } } private boolean isNeuronNeeded(NEATGenome target, long neuronID) { // do not remove bias or input neurons or output for (NEATNeuronGene gene : target.getNeuronsChromosome()) { if (gene.getId() == neuronID) { NEATNeuronGene neuron = (NEATNeuronGene) gene; if (neuron.getNeuronType() == NEATNeuronType.Input || neuron.getNeuronType() == NEATNeuronType.Bias || neuron.getNeuronType() == NEATNeuronType.Output) { return true; } } } for (NEATLinkGene gene : target.getLinksChromosome()) { NEATLinkGene linkGene = (NEATLinkGene) gene; if (linkGene.getFromNeuronID() == neuronID) { return true; } if (linkGene.getToNeuronID() == neuronID) { return true; } } return false; } private void removeNeuron(NEATGenome target, long neuronID) { for (NEATNeuronGene gene : target.getNeuronsChromosome()) { if (gene.getId() == neuronID) { target.getNeuronsChromosome().remove(gene); return; } } } public void removeLink(NEATGenome target) { if (target.getLinksChromosome().size() < 5) { // don't remove from small genomes return; } // determine the target and remove int index = RangeRandomizer.randomInt(0, target.getLinksChromosome() .size() - 1); NEATLinkGene targetGene = (NEATLinkGene) target.getLinksChromosome() .get(index); target.getLinksChromosome().remove(index); // if this orphaned any nodes, then kill them too! if (!isNeuronNeeded(target, targetGene.getFromNeuronID())) { removeNeuron(target, targetGene.getFromNeuronID()); } if (!isNeuronNeeded(target, targetGene.getToNeuronID())) { removeNeuron(target, targetGene.getToNeuronID()); } } /** * @return the mutateChoices */ public RandomChoice getMutateChoices() { return mutateChoices; } /** * @param mutateChoices the mutateChoices to set */ public void setMutateChoices(RandomChoice mutateChoices) { this.mutateChoices = mutateChoices; } /** * @return the mutateRate */ public double getMutateRate() { return mutateRate; } /** * @param mutateRate the mutateRate to set */ public void setMutateRate(double mutateRate) { this.mutateRate = mutateRate; } /** * @return the probNewMutate */ public double getProbNewMutate() { return probNewMutate; } /** * @param probNewMutate the probNewMutate to set */ public void setProbNewMutate(double probNewMutate) { this.probNewMutate = probNewMutate; } /** * @return the maxPertubation */ public double getMaxPertubation() { return maxPertubation; } /** * @param maxPertubation the maxPertubation to set */ public void setMaxPertubation(double maxPertubation) { this.maxPertubation = maxPertubation; } /** * @return the maxTries */ public int getMaxTries() { return maxTries; } /** * @param maxTries the maxTries to set */ public void setMaxTries(int maxTries) { this.maxTries = maxTries; } @Override public int offspringProduced() { return 1; } @Override public int parentsNeeded() { return 1; } @Override public void init(EvolutionaryAlgorithm theOwner) { if (!(theOwner instanceof NEATTraining)) { throw new EncogError( "This operator only works with a NEATTraining trainer."); } this.owner = (NEATTraining) theOwner; } }
Removed old class
src/main/java/org/encog/neural/neat/training/opp/NEATMutate.java
Removed old class
Java
mit
c18e778b7a1bcfa23216012c458f35c57cbc528c
0
evosec/fotilo
package de.evosec.fotilo; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import android.app.Activity; import android.app.ProgressDialog; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.hardware.Camera; import android.media.MediaActionSound; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.provider.MediaStore; import android.support.v4.app.Fragment; import android.view.Display; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.FrameLayout; import android.widget.ImageButton; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; /** * A simple {@link Fragment} subclass. Activities that contain this fragment * must implement the {@link CamFragment.OnFragmentInteractionListener} * interface to handle interaction events. Use the * {@link CamFragment#newInstance} factory method to create an instance of this * fragment. */ public class CamFragment extends Fragment implements View.OnClickListener, Camera.PictureCallback { private static final Logger LOG = LoggerFactory.getLogger(CamFragment.class); private static final int REVIEW_PICTURES_ACTIVITY_REQUEST = 123; private static int MEDIA_TYPE_IMAGE = 1; private int maxPictures; private int picturesTaken; private ArrayList<String> pictures; private Intent resultIntent; private Bundle resultBundle; private Camera camera; private Preview preview; private DrawingView drawingView; private RadioGroup flashmodes; private int maxZoomLevel; private int currentZoomLevel; private ProgressDialog progress; private boolean safeToTakePicture = false; public CamFragment() { // Required empty public constructor } /** * Use this factory method to create a new instance of this fragment using * the provided parameters. * * @return A new instance of fragment CamFragment. */ public static CamFragment newInstance() { return new CamFragment(); } @Override public void onPictureTaken(byte[] data, Camera camera) { // wenn maxPictures noch nicht erreicht if (picturesTaken < maxPictures || maxPictures == 0) { File pictureFile = getOutputMediaFile(MEDIA_TYPE_IMAGE); if (pictureFile == null) { LOG.debug( "Konnte Daei nicht erstellen, Berechtigungen überprüfen"); return; } FileOutputStream fos = null; try { fos = new FileOutputStream(pictureFile); fos.write(data); fos.close(); final Uri imageUri = getImageContentUri(getContext(), pictureFile); pictures.add(imageUri.toString()); showLastPicture(imageUri); picturesTaken++; if (maxPictures > 0) { Toast.makeText(getContext(), "Picture " + picturesTaken + " / " + maxPictures, Toast.LENGTH_SHORT).show(); } else { LOG.debug("Picture " + picturesTaken + " / " + maxPictures); } displayPicturesTaken(); // set Result resultBundle.putStringArrayList("pictures", pictures); resultIntent.putExtra("data", resultBundle); sendNewPictureBroadcast(imageUri); camera.startPreview(); safeToTakePicture = true; } catch (FileNotFoundException e) { LOG.debug("File not found: " + e); } catch (IOException e) { LOG.debug("Error accessing file: " + e); } finally { if (fos != null) { try { fos.close(); } catch (IOException e) { LOG.debug("" + e); } } progress.dismiss(); } } // wenn maxPictures erreicht, Bildpfade zurückgeben if (picturesTaken == maxPictures) { LOG.debug("maxPictures erreicht"); getActivity().setResult(Activity.RESULT_OK, resultIntent); getActivity().finish(); } } private void displayPicturesTaken() { TextView txtpicturesTaken = (TextView) getActivity().findViewById(R.id.picturesTaken); txtpicturesTaken.setText("Bilder: " + picturesTaken); } private void showLastPicture(Uri imageUri) { ImageButton pictureReview = (ImageButton) getActivity().findViewById(R.id.pictureReview); pictureReview.setOnClickListener(this); pictureReview.setVisibility(View.VISIBLE); new ShowThumbnailTask(pictureReview, getActivity().getContentResolver()) .execute(imageUri); } private void sendNewPictureBroadcast(Uri imageUri) { Intent intent = new Intent("com.android.camera.NEW_PICTURE"); try { intent.setData(imageUri); } catch (Exception e) { LOG.debug("" + e); } getActivity().sendBroadcast(intent); } private static Uri getImageContentUri(Context context, File imageFile) { String filePath = imageFile.getAbsolutePath(); Cursor cursor = context.getContentResolver().query( MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new String[] {MediaStore.Images.Media._ID}, MediaStore.Images.Media.DATA + "=? ", new String[] {filePath}, null); if (cursor != null && cursor.moveToFirst()) { int id = cursor .getInt(cursor.getColumnIndex(MediaStore.MediaColumns._ID)); Uri baseUri = Uri.parse("content://media/external/images/media"); return Uri.withAppendedPath(baseUri, "" + id); } else { if (imageFile.exists()) { ContentValues values = new ContentValues(); values.put(MediaStore.Images.Media.DATA, filePath); return context.getContentResolver().insert( MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values); } else { return null; } } } private static File getOutputMediaFile(int type) { File storageDir = new File(Environment.getExternalStoragePublicDirectory( Environment.DIRECTORY_PICTURES), "MyCam"); // Wenn Verzeichnis nicht existiert, erstellen if (!storageDir.exists() && !storageDir.mkdirs()) { LOG.debug("Konnte Bilderverzeichnis nicht erstellen!"); return null; } // Dateinamen erzeugen String timeStmp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); File mediaFile; if (type == MEDIA_TYPE_IMAGE) { mediaFile = new File(storageDir.getPath() + File.separator + "IMG_" + timeStmp + ".jpg"); } else { return null; } return mediaFile; } private void initFlashmodes() { flashmodes = (RadioGroup) getView().findViewById(R.id.radioGroup_Flashmodes); List<String> supportedFlashModes = camera.getParameters().getSupportedFlashModes(); if (supportedFlashModes != null) { for (String flashMode : supportedFlashModes) { switch (flashMode) { case Camera.Parameters.FLASH_MODE_AUTO: getView().findViewById(R.id.radio_flashmode_auto) .setVisibility(View.VISIBLE); break; case Camera.Parameters.FLASH_MODE_ON: getView().findViewById(R.id.radio_flashmode_on) .setVisibility(View.VISIBLE); break; case Camera.Parameters.FLASH_MODE_OFF: getView().findViewById(R.id.radio_flashmode_off) .setVisibility(View.VISIBLE); break; case Camera.Parameters.FLASH_MODE_RED_EYE: getView().findViewById(R.id.radio_flashmode_redEye) .setVisibility(View.VISIBLE); break; default: break; } } setDefaultFlashmode(); updateFlashModeIcon(); initSelectedFlashmode(); } else { flashmodes.setVisibility(View.INVISIBLE); } } private void initSelectedFlashmode() { if (camera.getParameters().getSupportedFlashModes() != null) { switch (camera.getParameters().getFlashMode()) { case Camera.Parameters.FLASH_MODE_AUTO: ((RadioButton) getView() .findViewById(R.id.radio_flashmode_auto)).setChecked(true); break; case Camera.Parameters.FLASH_MODE_ON: ((RadioButton) getView().findViewById(R.id.radio_flashmode_on)) .setChecked(true); break; case Camera.Parameters.FLASH_MODE_OFF: ((RadioButton) getView().findViewById(R.id.radio_flashmode_off)) .setChecked(true); break; case Camera.Parameters.FLASH_MODE_RED_EYE: ((RadioButton) getView() .findViewById(R.id.radio_flashmode_redEye)) .setChecked(true); break; default: break; } } } public void onRadioButtonClicked(View view) { String flashMode = ""; switch (view.getId()) { case R.id.radio_flashmode_auto: flashMode = Camera.Parameters.FLASH_MODE_AUTO; break; case R.id.radio_flashmode_on: flashMode = Camera.Parameters.FLASH_MODE_ON; break; case R.id.radio_flashmode_off: flashMode = Camera.Parameters.FLASH_MODE_OFF; break; case R.id.radio_flashmode_redEye: flashMode = Camera.Parameters.FLASH_MODE_RED_EYE; break; default: break; } Camera.Parameters params = camera.getParameters(); params.setFlashMode(flashMode); camera.setParameters(params); updateFlashModeIcon(); flashmodes.setVisibility(View.INVISIBLE); Toast.makeText(getContext(), "Flashmode = " + flashMode, Toast.LENGTH_SHORT).show(); } private void setDefaultFlashmode() { Camera.Parameters params = camera.getParameters(); if (camera.getParameters().getSupportedFlashModes() .contains(Camera.Parameters.FLASH_MODE_AUTO)) { params.setFlashMode(Camera.Parameters.FLASH_MODE_AUTO); camera.setParameters(params); } } private void findOptimalPictureSize() { // Ausgewählte Auflösung von rufender Activity einstellen Intent i = getActivity().getIntent(); Camera.Parameters params = camera.getParameters(); int w = 0; int h = 0; double ratio = 0; w = i.getIntExtra("width", w); h = i.getIntExtra("height", h); ratio = i.getDoubleExtra("aspectratio", ratio); LOG.debug("w = " + w + "; h = " + h + "; ratio = " + ratio); Camera.Size bestSize = null; if (w > 0 && h > 0) { // Mindestauflösung setzen findOptimalPictureSizeBySize(w, h); } else if (ratio > 0) { bestSize = getLargestResolutionByAspectRatio( camera.getParameters().getSupportedPictureSizes(), ratio); if (bestSize.width == camera.getParameters().getPreviewSize().width && bestSize.height == camera.getParameters() .getPreviewSize().height) { // Errormeldung keine Auflösung mit passendem Seitenverhältnis // gefunden String error = "Fehler: Keine Auflösung mit diesem Seitenverhältnis verfügbar!"; Toast.makeText(getContext(), error, Toast.LENGTH_SHORT).show(); resultBundle.putString("error", error); resultIntent.putExtra("data", resultBundle); getActivity().setResult(Activity.RESULT_CANCELED, resultIntent); getActivity().finish(); return; } configurePictureSize(bestSize, params); LOG.debug(bestSize.width + " x " + bestSize.height); } else { // keine Auflösung vorgegeben: höchste 4:3 Auflösung wählen configureLargestFourToThreeRatioPictureSize(); } } public void configurePictureSize(Camera.Size size, Camera.Parameters params) { params.setPictureSize(size.width, size.height); camera.setParameters(params); scalePreviewSize(); } public void scalePreviewSize() { Camera.Size pictureSize = camera.getParameters().getPictureSize(); Camera.Size previewSize = camera.getParameters().getPreviewSize(); LOG.debug( "PictureSize = " + pictureSize.width + " x " + pictureSize.height); double pictureRatio = (double) pictureSize.width / (double) pictureSize.height; previewSize = getLargestResolutionByAspectRatio( camera.getParameters().getSupportedPreviewSizes(), pictureRatio); LOG.debug( "PreviewSize = " + previewSize.width + " x " + previewSize.height); configurePreviewSize(previewSize); } public Camera.Size getLargestResolutionByAspectRatio( List<Camera.Size> sizes, double aspectRatio) { Camera.Size largestSize = camera.getParameters().getPreviewSize(); largestSize.width = 0; largestSize.height = 0; for (Camera.Size size : sizes) { double ratio = (double) size.width / (double) size.height; if (Math.abs(ratio - aspectRatio) < 0.00000001 && size.width >= largestSize.width && size.height >= largestSize.height) { largestSize = size; } } return largestSize; } public void configurePreviewSize(Camera.Size size) { Display display = getActivity().getWindowManager().getDefaultDisplay(); Camera.Parameters params = camera.getParameters(); int screenWidth = display.getWidth(); int screenHeight = display.getHeight(); Camera.Size bestPreviewSize = size; params.setPreviewSize(bestPreviewSize.width, bestPreviewSize.height); camera.setParameters(params); preview.getLayoutParams().width = bestPreviewSize.width; preview.getLayoutParams().height = bestPreviewSize.height; FrameLayout frameLayout = (FrameLayout) getView().findViewById(R.id.preview); RelativeLayout.LayoutParams layoutPreviewParams = (RelativeLayout.LayoutParams) frameLayout.getLayoutParams(); layoutPreviewParams.width = bestPreviewSize.width; layoutPreviewParams.height = bestPreviewSize.height; layoutPreviewParams.addRule(RelativeLayout.CENTER_IN_PARENT); frameLayout.setLayoutParams(layoutPreviewParams); LOG.debug("screenSize = " + screenWidth + " x " + screenHeight); LOG.debug("PreviewSize = " + bestPreviewSize.width + " x " + bestPreviewSize.height); } private void configureLargestFourToThreeRatioPictureSize() { Camera.Parameters params = camera.getParameters(); List<Camera.Size> supportedPictureSizes = params.getSupportedPictureSizes(); Camera.Size bestSize = params.getPictureSize(); bestSize.width = 0; bestSize.height = 0; double fourToThreeRatio = 4.0 / 3.0; for (Camera.Size supportedSize : supportedPictureSizes) { if (Math .abs((double) supportedSize.width / supportedSize.height - fourToThreeRatio) == 0 && supportedSize.width >= bestSize.width && supportedSize.height >= bestSize.height) { bestSize = supportedSize; } } params.setPictureSize(bestSize.width, bestSize.height); camera.setParameters(params); configurePictureSize(bestSize, params); LOG.debug(bestSize.width + " x " + bestSize.height); } private void findOptimalPictureSizeBySize(int w, int h) { Camera.Parameters params = camera.getParameters(); double tempDiff = 0; double diff = Integer.MAX_VALUE; Camera.Size bestSize = null; for (Camera.Size supportedSize : params.getSupportedPictureSizes()) { // nächst größere Auflösung suchen if (supportedSize.width >= w && supportedSize.height >= h) { // Pythagoras tempDiff = Math .sqrt(Math.pow((double) supportedSize.width - w, 2) + Math.pow((double) supportedSize.height - h, 2)); // minimalste Differenz suchen if (tempDiff < diff) { diff = tempDiff; bestSize = supportedSize; } } } // beste Auflösung setzen if (bestSize != null) { configurePictureSize(bestSize, params); LOG.debug(bestSize.width + " x " + bestSize.height + " px"); } else { // Fehlermeldung zurückgeben String error = "Fehler: Auflösung zu hoch!"; Toast.makeText(getContext(), error, Toast.LENGTH_SHORT).show(); resultBundle.putString("error", error); resultIntent.putExtra("data", resultBundle); getActivity().setResult(Activity.RESULT_CANCELED, resultIntent); getActivity().finish(); } } public void onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { resultIntent.putExtra("data", resultBundle); getActivity().setResult(Activity.RESULT_CANCELED, resultIntent); getActivity().finish(); } else if (keyCode == KeyEvent.KEYCODE_CAMERA) { if (safeToTakePicture) { takePicture(); } } else if (keyCode == KeyEvent.KEYCODE_ZOOM_IN) { zoomIn(); } else if (keyCode == KeyEvent.KEYCODE_ZOOM_OUT) { zoomOut(); } } private void takePicture() { // Anwender signalisieren, dass ein Bild aufgenommen wird progress = ProgressDialog.show(getActivity(), "Speichern", "Bild wird gespeichert..."); MediaActionSound sound = new MediaActionSound(); sound.play(MediaActionSound.SHUTTER_CLICK); camera.takePicture(null, null, this); safeToTakePicture = false; } private void initPreview() { drawingView = (DrawingView) getView().findViewById(R.id.drawingView); preview = new Preview(getContext(), camera, drawingView); FrameLayout frameLayout = (FrameLayout) getView().findViewById(R.id.preview); frameLayout.addView(preview); safeToTakePicture = true; } private void zoomIn() { if (camera != null) { Camera.Parameters params = camera.getParameters(); if (this.currentZoomLevel < this.maxZoomLevel) { currentZoomLevel++; params.setZoom(this.currentZoomLevel); camera.setParameters(params); viewCurrentZoom(); } } } private void zoomOut() { if (camera != null) { Camera.Parameters params = camera.getParameters(); if (this.currentZoomLevel > 0) { currentZoomLevel--; params.setZoom(this.currentZoomLevel); camera.setParameters(params); viewCurrentZoom(); } } } private void viewCurrentZoom() { TextView txtCurrentZoom = (TextView) getView().findViewById(R.id.txtCurrentZoom); txtCurrentZoom.setVisibility(View.VISIBLE); txtCurrentZoom.setText( "Zoom: " + this.currentZoomLevel + " / " + this.maxZoomLevel); } private void updateFlashModeIcon() { ImageButton btnFlashmode = (ImageButton) getView().findViewById(R.id.btn_flashmode); if (camera.getParameters().getSupportedFlashModes() != null) { switch (camera.getParameters().getFlashMode()) { case Camera.Parameters.FLASH_MODE_AUTO: btnFlashmode .setImageResource(R.drawable.ic_flash_auto_black_24dp); break; case Camera.Parameters.FLASH_MODE_ON: btnFlashmode .setImageResource(R.drawable.ic_flash_on_black_24dp); break; case Camera.Parameters.FLASH_MODE_OFF: btnFlashmode .setImageResource(R.drawable.ic_flash_off_black_24dp); break; case Camera.Parameters.FLASH_MODE_RED_EYE: btnFlashmode .setImageResource(R.drawable.ic_remove_red_eye_black_24dp); break; default: break; } } else { btnFlashmode.setVisibility(View.INVISIBLE); } } private void releaseCamera() { if (camera != null) { camera.stopPreview(); camera.setPreviewCallback(null); if (preview != null) { preview.getHolder().removeCallback(preview); } camera.release(); camera = null; if (preview != null && preview.getCamera() != null) { preview.setCamera(camera); } LOG.debug("camera released"); } } @Override public void onPause() { LOG.debug("onPause()"); super.onPause(); releaseCamera(); } @Override public void onDestroyView() { LOG.debug("onDestroyView()"); super.onDestroyView(); releaseCamera(); } @Override public void onResume() { super.onResume(); Intent i = getActivity().getIntent(); this.maxPictures = i.getIntExtra("maxPictures", maxPictures); LOG.debug("onResume() maxPictures = " + maxPictures); if (camera == null) { camera = getCameraInstance(); if (preview != null && preview.getCamera() == null) { preview.setCamera(camera); } } } public static Camera getCameraInstance() { Camera c = null; try { c = Camera.open(); } catch (Exception ex) { // Camera in use or does not exist LOG.debug("Error: keine Kamera bekommen: " + ex); } if (c != null) { LOG.debug("camera opened"); LOG.debug("Camera = " + c.toString()); } return c; } @Override public void onCreate(Bundle savedInstanceState) { LOG.debug("onCreate()"); super.onCreate(savedInstanceState); resultIntent = new Intent(); resultBundle = new Bundle(); Intent i = getActivity().getIntent(); // max. Anzahl Bilder von rufender Activity auslesen this.maxPictures = i.getIntExtra("maxPictures", maxPictures); LOG.debug("onCreate() maxPictures = " + maxPictures); this.picturesTaken = 0; this.pictures = new ArrayList<String>(); camera = getCameraInstance(); if (preview != null && preview.getCamera() == null) { preview.setCamera(camera); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { LOG.debug("onCreateView()"); LOG.debug("CamFragment"); View view = inflater.inflate(R.layout.fragment_cam, container, false); ImageButton btnFlashmode = (ImageButton) view.findViewById(R.id.btn_flashmode); btnFlashmode.setOnClickListener(this); ImageButton btnCapture = (ImageButton) view.findViewById(R.id.btn_capture); btnCapture.setOnClickListener(this); ImageButton btnZoomin = (ImageButton) view.findViewById(R.id.btnZoomIn); btnZoomin.setOnClickListener(this); ImageButton btnZoomOut = (ImageButton) view.findViewById(R.id.btnZoomOut); btnZoomOut.setOnClickListener(this); Button radioFlashmodeAuto = (Button) view.findViewById(R.id.radio_flashmode_auto); radioFlashmodeAuto.setOnClickListener(this); Button radioFlashmodeOn = (Button) view.findViewById(R.id.radio_flashmode_on); radioFlashmodeOn.setOnClickListener(this); Button radioFlashmodeOff = (Button) view.findViewById(R.id.radio_flashmode_off); radioFlashmodeOff.setOnClickListener(this); Button radioFlashmodeRedEye = (Button) view.findViewById(R.id.radio_flashmode_redEye); radioFlashmodeRedEye.setOnClickListener(this); return view; } @Override public void onStart() { LOG.debug("onStart()"); super.onStart(); if (camera == null) { camera = getCameraInstance(); if (preview != null && preview.getCamera() == null) { preview.setCamera(camera); } } if (camera.getParameters().isZoomSupported()) { ImageButton btnZoomin = (ImageButton) getView().findViewById(R.id.btnZoomIn); ImageButton btnZoomOut = (ImageButton) getView().findViewById(R.id.btnZoomOut); btnZoomin.setVisibility(View.VISIBLE); btnZoomOut.setVisibility(View.VISIBLE); this.maxZoomLevel = camera.getParameters().getMaxZoom(); this.currentZoomLevel = 0; viewCurrentZoom(); } updateFlashModeIcon(); initPreview(); findOptimalPictureSize(); initFlashmodes(); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.btn_flashmode: flashmodes.setVisibility(View.VISIBLE); break; case R.id.btn_capture: if (safeToTakePicture) { takePicture(); } break; case R.id.btnZoomIn: zoomIn(); break; case R.id.btnZoomOut: zoomOut(); break; case R.id.radio_flashmode_auto: case R.id.radio_flashmode_off: case R.id.radio_flashmode_on: case R.id.radio_flashmode_redEye: this.onRadioButtonClicked(v); break; case R.id.pictureReview: startReviewPicturesActivity(); break; default: break; } } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); if (savedInstanceState != null) { this.pictures = savedInstanceState.getStringArrayList("pictures"); this.maxPictures = savedInstanceState.getInt("maxPictures"); this.picturesTaken = this.pictures.size(); if (picturesTaken > 0) { showLastPicture( Uri.parse(this.pictures.get(picturesTaken - 1))); } displayPicturesTaken(); } } @Override public void onSaveInstanceState(Bundle outState) { outState.putStringArrayList("pictures", pictures); outState.putInt("maxPictures", maxPictures); outState.putInt("picturesTaken", picturesTaken); super.onSaveInstanceState(outState); } private void startReviewPicturesActivity() { Bundle bundle = new Bundle(); Intent intent = new Intent(getActivity(), ReviewPicturesActivity.class); bundle.putStringArrayList("pictures", pictures); intent.putExtra("data", bundle); startActivityForResult(intent, REVIEW_PICTURES_ACTIVITY_REQUEST); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { case REVIEW_PICTURES_ACTIVITY_REQUEST: if (resultCode == Activity.RESULT_OK || resultCode == Activity.RESULT_FIRST_USER) { Bundle bundle = data.getBundleExtra("data"); this.pictures = bundle.getStringArrayList("pictures"); this.picturesTaken = this.pictures.size(); if (pictures.isEmpty()) { showLastPicture( Uri.parse(this.pictures.get(pictures.size() - 1))); } displayPicturesTaken(); if (resultCode == Activity.RESULT_FIRST_USER) { resultIntent.putExtra("data", resultBundle); getActivity().setResult(Activity.RESULT_CANCELED, resultIntent); getActivity().finish(); } } break; default: break; } } private Context getContext() { return getActivity(); } /** * This interface must be implemented by activities that contain this * fragment to allow an interaction in this fragment to be communicated to * the activity and potentially other fragments contained in that activity. * See the Android Training lesson <a href= * "http://developer.android.com/training/basics/fragments/communicating.html" * >Communicating with Other Fragments</a> for more information. */ public interface OnFragmentInteractionListener { void onFragmentInteraction(Uri uri); } }
src/de/evosec/fotilo/CamFragment.java
package de.evosec.fotilo; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import android.app.Activity; import android.app.ProgressDialog; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.hardware.Camera; import android.media.MediaActionSound; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.provider.MediaStore; import android.support.v4.app.Fragment; import android.view.Display; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.FrameLayout; import android.widget.ImageButton; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; /** * A simple {@link Fragment} subclass. Activities that contain this fragment * must implement the {@link CamFragment.OnFragmentInteractionListener} * interface to handle interaction events. Use the * {@link CamFragment#newInstance} factory method to create an instance of this * fragment. */ public class CamFragment extends Fragment implements View.OnClickListener, Camera.PictureCallback { private static final Logger LOG = LoggerFactory.getLogger(CamFragment.class); private static final int REVIEW_PICTURES_ACTIVITY_REQUEST = 123; private static int MEDIA_TYPE_IMAGE = 1; private int maxPictures; private int picturesTaken; private ArrayList<String> pictures; private Intent resultIntent; private Bundle resultBundle; private Camera camera; private Preview preview; private DrawingView drawingView; private RadioGroup flashmodes; private int maxZoomLevel; private int currentZoomLevel; private ProgressDialog progress; private boolean safeToTakePicture = false; public CamFragment() { // Required empty public constructor } /** * Use this factory method to create a new instance of this fragment using * the provided parameters. * * @return A new instance of fragment CamFragment. */ public static CamFragment newInstance() { return new CamFragment(); } @Override public void onPictureTaken(byte[] data, Camera camera) { // wenn maxPictures noch nicht erreicht if (picturesTaken < maxPictures || maxPictures == 0) { File pictureFile = getOutputMediaFile(MEDIA_TYPE_IMAGE); if (pictureFile == null) { LOG.debug( "Konnte Daei nicht erstellen, Berechtigungen überprüfen"); return; } FileOutputStream fos = null; try { fos = new FileOutputStream(pictureFile); fos.write(data); fos.close(); final Uri imageUri = getImageContentUri(getContext(), pictureFile); pictures.add(imageUri.toString()); showLastPicture(imageUri); picturesTaken++; if (maxPictures > 0) { Toast.makeText(getContext(), "Picture " + picturesTaken + " / " + maxPictures, Toast.LENGTH_SHORT).show(); } else { LOG.debug("Picture " + picturesTaken + " / " + maxPictures); } displayPicturesTaken(); // set Result resultBundle.putStringArrayList("pictures", pictures); resultIntent.putExtra("data", resultBundle); sendNewPictureBroadcast(imageUri); camera.startPreview(); safeToTakePicture = true; } catch (FileNotFoundException e) { LOG.debug("File not found: " + e); } catch (IOException e) { LOG.debug("Error accessing file: " + e); } finally { if (fos != null) { try { fos.close(); } catch (IOException e) { LOG.debug("" + e); } } progress.dismiss(); } } // wenn maxPictures erreicht, Bildpfade zurückgeben if (picturesTaken == maxPictures) { LOG.debug("maxPictures erreicht"); getActivity().setResult(Activity.RESULT_OK, resultIntent); getActivity().finish(); } } private void displayPicturesTaken() { TextView txtpicturesTaken = (TextView) getActivity().findViewById(R.id.picturesTaken); txtpicturesTaken.setText("Bilder: " + picturesTaken); } private void showLastPicture(Uri imageUri) { ImageButton pictureReview = (ImageButton) getActivity().findViewById(R.id.pictureReview); pictureReview.setOnClickListener(this); pictureReview.setVisibility(View.VISIBLE); new ShowThumbnailTask(pictureReview, getActivity().getContentResolver()) .execute(imageUri); } private void sendNewPictureBroadcast(Uri imageUri) { Intent intent = new Intent("com.android.camera.NEW_PICTURE"); try { intent.setData(imageUri); } catch (Exception e) { LOG.debug("" + e); } getActivity().sendBroadcast(intent); } private static Uri getImageContentUri(Context context, File imageFile) { String filePath = imageFile.getAbsolutePath(); Cursor cursor = context.getContentResolver().query( MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new String[] {MediaStore.Images.Media._ID}, MediaStore.Images.Media.DATA + "=? ", new String[] {filePath}, null); if (cursor != null && cursor.moveToFirst()) { int id = cursor .getInt(cursor.getColumnIndex(MediaStore.MediaColumns._ID)); Uri baseUri = Uri.parse("content://media/external/images/media"); return Uri.withAppendedPath(baseUri, "" + id); } else { if (imageFile.exists()) { ContentValues values = new ContentValues(); values.put(MediaStore.Images.Media.DATA, filePath); return context.getContentResolver().insert( MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values); } else { return null; } } } private static File getOutputMediaFile(int type) { File storageDir = new File(Environment.getExternalStoragePublicDirectory( Environment.DIRECTORY_PICTURES), "MyCam"); // Wenn Verzeichnis nicht existiert, erstellen if (!storageDir.exists() && !storageDir.mkdirs()) { LOG.debug("Konnte Bilderverzeichnis nicht erstellen!"); return null; } // Dateinamen erzeugen String timeStmp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date()); File mediaFile; if (type == MEDIA_TYPE_IMAGE) { mediaFile = new File(storageDir.getPath() + File.separator + "IMG_" + timeStmp + ".jpg"); } else { return null; } return mediaFile; } private void initFlashmodes() { flashmodes = (RadioGroup) getView().findViewById(R.id.radioGroup_Flashmodes); List<String> supportedFlashModes = camera.getParameters().getSupportedFlashModes(); if (supportedFlashModes != null) { for (String flashMode : supportedFlashModes) { switch (flashMode) { case Camera.Parameters.FLASH_MODE_AUTO: getView().findViewById(R.id.radio_flashmode_auto) .setVisibility(View.VISIBLE); break; case Camera.Parameters.FLASH_MODE_ON: getView().findViewById(R.id.radio_flashmode_on) .setVisibility(View.VISIBLE); break; case Camera.Parameters.FLASH_MODE_OFF: getView().findViewById(R.id.radio_flashmode_off) .setVisibility(View.VISIBLE); break; case Camera.Parameters.FLASH_MODE_RED_EYE: getView().findViewById(R.id.radio_flashmode_redEye) .setVisibility(View.VISIBLE); break; default: break; } } setDefaultFlashmode(); updateFlashModeIcon(); initSelectedFlashmode(); } else { flashmodes.setVisibility(View.INVISIBLE); } } private void initSelectedFlashmode() { if (camera.getParameters().getSupportedFlashModes() != null) { switch (camera.getParameters().getFlashMode()) { case Camera.Parameters.FLASH_MODE_AUTO: ((RadioButton) getView() .findViewById(R.id.radio_flashmode_auto)).setChecked(true); break; case Camera.Parameters.FLASH_MODE_ON: ((RadioButton) getView().findViewById(R.id.radio_flashmode_on)) .setChecked(true); break; case Camera.Parameters.FLASH_MODE_OFF: ((RadioButton) getView().findViewById(R.id.radio_flashmode_off)) .setChecked(true); break; case Camera.Parameters.FLASH_MODE_RED_EYE: ((RadioButton) getView() .findViewById(R.id.radio_flashmode_redEye)) .setChecked(true); break; default: break; } } } public void onRadioButtonClicked(View view) { String flashMode = ""; switch (view.getId()) { case R.id.radio_flashmode_auto: flashMode = Camera.Parameters.FLASH_MODE_AUTO; break; case R.id.radio_flashmode_on: flashMode = Camera.Parameters.FLASH_MODE_ON; break; case R.id.radio_flashmode_off: flashMode = Camera.Parameters.FLASH_MODE_OFF; break; case R.id.radio_flashmode_redEye: flashMode = Camera.Parameters.FLASH_MODE_RED_EYE; break; default: break; } Camera.Parameters params = camera.getParameters(); params.setFlashMode(flashMode); camera.setParameters(params); updateFlashModeIcon(); flashmodes.setVisibility(View.INVISIBLE); Toast.makeText(getContext(), "Flashmode = " + flashMode, Toast.LENGTH_SHORT).show(); } private void setDefaultFlashmode() { Camera.Parameters params = camera.getParameters(); if (camera.getParameters().getSupportedFlashModes() .contains(Camera.Parameters.FLASH_MODE_AUTO)) { params.setFlashMode(Camera.Parameters.FLASH_MODE_AUTO); camera.setParameters(params); } } private void findOptimalPictureSize() { // Ausgewählte Auflösung von rufender Activity einstellen Intent i = getActivity().getIntent(); Camera.Parameters params = camera.getParameters(); int w = 0; int h = 0; double ratio = 0; w = i.getIntExtra("width", w); h = i.getIntExtra("height", h); ratio = i.getDoubleExtra("aspectratio", ratio); LOG.debug("w = " + w + "; h = " + h + "; ratio = " + ratio); Camera.Size bestSize = null; if (w > 0 && h > 0) { // Mindestauflösung setzen findOptimalPictureSizeBySize(w, h); } else if (ratio > 0) { bestSize = getLargestResolutionByAspectRatio( camera.getParameters().getSupportedPictureSizes(), ratio); if (bestSize.width == camera.getParameters().getPreviewSize().width && bestSize.height == camera.getParameters() .getPreviewSize().height) { // Errormeldung keine Auflösung mit passendem Seitenverhältnis // gefunden String error = "Fehler: Keine Auflösung mit diesem Seitenverhältnis verfügbar!"; Toast.makeText(getContext(), error, Toast.LENGTH_SHORT).show(); resultBundle.putString("error", error); resultIntent.putExtra("data", resultBundle); getActivity().setResult(Activity.RESULT_CANCELED, resultIntent); getActivity().finish(); return; } configurePictureSize(bestSize, params); LOG.debug(bestSize.width + " x " + bestSize.height); } else { // keine Auflösung vorgegeben: höchste 4:3 Auflösung wählen configureLargestFourToThreeRatioPictureSize(); } } public void configurePictureSize(Camera.Size size, Camera.Parameters params) { params.setPictureSize(size.width, size.height); camera.setParameters(params); scalePreviewSize(); } public void scalePreviewSize() { Camera.Size pictureSize = camera.getParameters().getPictureSize(); Camera.Size previewSize = camera.getParameters().getPreviewSize(); LOG.debug( "PictureSize = " + pictureSize.width + " x " + pictureSize.height); double pictureRatio = (double) pictureSize.width / (double) pictureSize.height; previewSize = getLargestResolutionByAspectRatio( camera.getParameters().getSupportedPreviewSizes(), pictureRatio); LOG.debug( "PreviewSize = " + previewSize.width + " x " + previewSize.height); configurePreviewSize(previewSize); } public Camera.Size getLargestResolutionByAspectRatio( List<Camera.Size> sizes, double aspectRatio) { Camera.Size largestSize = camera.getParameters().getPreviewSize(); largestSize.width = 0; largestSize.height = 0; for (Camera.Size size : sizes) { double ratio = (double) size.width / (double) size.height; if (Math.abs(ratio - aspectRatio) < 0.00000001 && size.width >= largestSize.width && size.height >= largestSize.height) { largestSize = size; } } return largestSize; } public void configurePreviewSize(Camera.Size size) { Display display = getActivity().getWindowManager().getDefaultDisplay(); Camera.Parameters params = camera.getParameters(); int screenWidth = display.getWidth(); int screenHeight = display.getHeight(); Camera.Size bestPreviewSize = size; params.setPreviewSize(bestPreviewSize.width, bestPreviewSize.height); camera.setParameters(params); preview.getLayoutParams().width = bestPreviewSize.width; preview.getLayoutParams().height = bestPreviewSize.height; FrameLayout frameLayout = (FrameLayout) getView().findViewById(R.id.preview); RelativeLayout.LayoutParams layoutPreviewParams = (RelativeLayout.LayoutParams) frameLayout.getLayoutParams(); layoutPreviewParams.width = bestPreviewSize.width; layoutPreviewParams.height = bestPreviewSize.height; layoutPreviewParams.addRule(RelativeLayout.CENTER_IN_PARENT); frameLayout.setLayoutParams(layoutPreviewParams); LOG.debug("screenSize = " + screenWidth + " x " + screenHeight); LOG.debug("PreviewSize = " + bestPreviewSize.width + " x " + bestPreviewSize.height); } private void configureLargestFourToThreeRatioPictureSize() { Camera.Parameters params = camera.getParameters(); List<Camera.Size> supportedPictureSizes = params.getSupportedPictureSizes(); Camera.Size bestSize = params.getPictureSize(); bestSize.width = 0; bestSize.height = 0; double fourToThreeRatio = 4.0 / 3.0; for (Camera.Size supportedSize : supportedPictureSizes) { if (Math .abs((double) supportedSize.width / supportedSize.height - fourToThreeRatio) == 0 && supportedSize.width >= bestSize.width && supportedSize.height >= bestSize.height) { bestSize = supportedSize; } } params.setPictureSize(bestSize.width, bestSize.height); camera.setParameters(params); configurePictureSize(bestSize, params); LOG.debug(bestSize.width + " x " + bestSize.height); } private void findOptimalPictureSizeBySize(int w, int h) { Camera.Parameters params = camera.getParameters(); double tempDiff = 0; double diff = Integer.MAX_VALUE; Camera.Size bestSize = null; for (Camera.Size supportedSize : params.getSupportedPictureSizes()) { // nächst größere Auflösung suchen if (supportedSize.width >= w && supportedSize.height >= h) { // Pythagoras tempDiff = Math .sqrt(Math.pow((double) supportedSize.width - w, 2) + Math.pow((double) supportedSize.height - h, 2)); // minimalste Differenz suchen if (tempDiff < diff) { diff = tempDiff; bestSize = supportedSize; } } } // beste Auflösung setzen if (bestSize != null) { configurePictureSize(bestSize, params); LOG.debug(bestSize.width + " x " + bestSize.height + " px"); } else { // Fehlermeldung zurückgeben String error = "Fehler: Auflösung zu hoch!"; Toast.makeText(getContext(), error, Toast.LENGTH_SHORT).show(); resultBundle.putString("error", error); resultIntent.putExtra("data", resultBundle); getActivity().setResult(Activity.RESULT_CANCELED, resultIntent); getActivity().finish(); } } public void onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { resultIntent.putExtra("data", resultBundle); getActivity().setResult(Activity.RESULT_CANCELED, resultIntent); getActivity().finish(); } else if (keyCode == KeyEvent.KEYCODE_CAMERA) { if (safeToTakePicture) { takePicture(); } } else if (keyCode == KeyEvent.KEYCODE_ZOOM_IN) { zoomIn(); } else if (keyCode == KeyEvent.KEYCODE_ZOOM_OUT) { zoomOut(); } } private void takePicture() { // Anwender signalisieren, dass ein Bild aufgenommen wird progress = ProgressDialog.show(getActivity(), "Speichern", "Bild wird gespeichert..."); MediaActionSound sound = new MediaActionSound(); sound.play(MediaActionSound.SHUTTER_CLICK); camera.takePicture(null, null, this); safeToTakePicture = false; } private void initPreview() { drawingView = (DrawingView) getView().findViewById(R.id.drawingView); preview = new Preview(getContext(), camera, drawingView); FrameLayout frameLayout = (FrameLayout) getView().findViewById(R.id.preview); frameLayout.addView(preview); safeToTakePicture = true; } private void zoomIn() { if (camera != null) { Camera.Parameters params = camera.getParameters(); if (this.currentZoomLevel < this.maxZoomLevel) { currentZoomLevel++; params.setZoom(this.currentZoomLevel); camera.setParameters(params); viewCurrentZoom(); } } } private void zoomOut() { if (camera != null) { Camera.Parameters params = camera.getParameters(); if (this.currentZoomLevel > 0) { currentZoomLevel--; params.setZoom(this.currentZoomLevel); camera.setParameters(params); viewCurrentZoom(); } } } private void viewCurrentZoom() { TextView txtCurrentZoom = (TextView) getView().findViewById(R.id.txtCurrentZoom); txtCurrentZoom.setVisibility(View.VISIBLE); txtCurrentZoom.setText( "Zoom: " + this.currentZoomLevel + " / " + this.maxZoomLevel); } private void updateFlashModeIcon() { ImageButton btnFlashmode = (ImageButton) getView().findViewById(R.id.btn_flashmode); if (camera.getParameters().getSupportedFlashModes() != null) { switch (camera.getParameters().getFlashMode()) { case Camera.Parameters.FLASH_MODE_AUTO: btnFlashmode .setImageResource(R.drawable.ic_flash_auto_black_24dp); break; case Camera.Parameters.FLASH_MODE_ON: btnFlashmode .setImageResource(R.drawable.ic_flash_on_black_24dp); break; case Camera.Parameters.FLASH_MODE_OFF: btnFlashmode .setImageResource(R.drawable.ic_flash_off_black_24dp); break; case Camera.Parameters.FLASH_MODE_RED_EYE: btnFlashmode .setImageResource(R.drawable.ic_remove_red_eye_black_24dp); break; default: break; } } else { btnFlashmode.setVisibility(View.INVISIBLE); } } private void releaseCamera() { if (camera != null) { camera.stopPreview(); camera.setPreviewCallback(null); if (preview != null) { preview.getHolder().removeCallback(preview); } camera.release(); camera = null; if (preview != null && preview.getCamera() != null) { preview.setCamera(camera); } LOG.debug("camera released"); } } @Override public void onPause() { LOG.debug("onPause()"); super.onPause(); releaseCamera(); } @Override public void onDestroyView() { LOG.debug("onDestroyView()"); super.onDestroyView(); releaseCamera(); } @Override public void onResume() { super.onResume(); Intent i = getActivity().getIntent(); this.maxPictures = i.getIntExtra("maxPictures", maxPictures); LOG.debug("onResume() maxPictures = " + maxPictures); if (camera == null) { camera = getCameraInstance(); if (preview != null && preview.getCamera() == null) { preview.setCamera(camera); } } } public static Camera getCameraInstance() { Camera c = null; try { c = Camera.open(); } catch (Exception ex) { // Camera in use or does not exist LOG.debug("Error: keine Kamera bekommen: " + ex); } if (c != null) { LOG.debug("camera opened"); LOG.debug("Camera = " + c.toString()); } return c; } @Override public void onCreate(Bundle savedInstanceState) { LOG.debug("onCreate()"); super.onCreate(savedInstanceState); resultIntent = new Intent(); resultBundle = new Bundle(); Intent i = getActivity().getIntent(); // max. Anzahl Bilder von rufender Activity auslesen this.maxPictures = i.getIntExtra("maxPictures", maxPictures); LOG.debug("onCreate() maxPictures = " + maxPictures); this.picturesTaken = 0; this.pictures = new ArrayList<String>(); camera = getCameraInstance(); if (preview != null && preview.getCamera() == null) { preview.setCamera(camera); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { LOG.debug("onCreateView()"); LOG.debug("CamFragment"); View view = inflater.inflate(R.layout.fragment_cam, container, false); ImageButton btnFlashmode = (ImageButton) view.findViewById(R.id.btn_flashmode); btnFlashmode.setOnClickListener(this); ImageButton btnCapture = (ImageButton) view.findViewById(R.id.btn_capture); btnCapture.setOnClickListener(this); ImageButton btnZoomin = (ImageButton) view.findViewById(R.id.btnZoomIn); btnZoomin.setOnClickListener(this); ImageButton btnZoomOut = (ImageButton) view.findViewById(R.id.btnZoomOut); btnZoomOut.setOnClickListener(this); Button radioFlashmodeAuto = (Button) view.findViewById(R.id.radio_flashmode_auto); radioFlashmodeAuto.setOnClickListener(this); Button radioFlashmodeOn = (Button) view.findViewById(R.id.radio_flashmode_on); radioFlashmodeOn.setOnClickListener(this); Button radioFlashmodeOff = (Button) view.findViewById(R.id.radio_flashmode_off); radioFlashmodeOff.setOnClickListener(this); Button radioFlashmodeRedEye = (Button) view.findViewById(R.id.radio_flashmode_redEye); radioFlashmodeRedEye.setOnClickListener(this); return view; } @Override public void onStart() { LOG.debug("onStart()"); super.onStart(); if (camera == null) { camera = getCameraInstance(); if (preview != null && preview.getCamera() == null) { preview.setCamera(camera); } } if (camera.getParameters().isZoomSupported()) { ImageButton btnZoomin = (ImageButton) getView().findViewById(R.id.btnZoomIn); ImageButton btnZoomOut = (ImageButton) getView().findViewById(R.id.btnZoomOut); btnZoomin.setVisibility(View.VISIBLE); btnZoomOut.setVisibility(View.VISIBLE); this.maxZoomLevel = camera.getParameters().getMaxZoom(); this.currentZoomLevel = 0; viewCurrentZoom(); } updateFlashModeIcon(); initPreview(); findOptimalPictureSize(); initFlashmodes(); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.btn_flashmode: flashmodes.setVisibility(View.VISIBLE); break; case R.id.btn_capture: if (safeToTakePicture) { takePicture(); } break; case R.id.btnZoomIn: zoomIn(); break; case R.id.btnZoomOut: zoomOut(); break; case R.id.radio_flashmode_auto: case R.id.radio_flashmode_off: case R.id.radio_flashmode_on: case R.id.radio_flashmode_redEye: this.onRadioButtonClicked(v); break; case R.id.pictureReview: startReviewPicturesActivity(); break; default: break; } } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); if (savedInstanceState != null) { this.pictures = savedInstanceState.getStringArrayList("pictures"); this.maxPictures = savedInstanceState.getInt("maxPictures"); this.picturesTaken = this.pictures.size(); if (picturesTaken > 0) { showLastPicture( Uri.parse(this.pictures.get(picturesTaken - 1))); } displayPicturesTaken(); } } @Override public void onSaveInstanceState(Bundle outState) { outState.putStringArrayList("pictures", pictures); outState.putInt("maxPictures", maxPictures); outState.putInt("picturesTaken", picturesTaken); super.onSaveInstanceState(outState); } private void startReviewPicturesActivity() { Bundle bundle = new Bundle(); Intent intent = new Intent(getActivity(), ReviewPicturesActivity.class); bundle.putStringArrayList("pictures", pictures); intent.putExtra("data", bundle); startActivityForResult(intent, REVIEW_PICTURES_ACTIVITY_REQUEST); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { case REVIEW_PICTURES_ACTIVITY_REQUEST: if (resultCode == Activity.RESULT_OK || resultCode == Activity.RESULT_FIRST_USER) { Bundle bundle = data.getBundleExtra("data"); this.pictures = bundle.getStringArrayList("pictures"); this.picturesTaken = this.pictures.size(); if (pictures.isEmpty()) { showLastPicture( Uri.parse(this.pictures.get(pictures.size() - 1))); } displayPicturesTaken(); if (resultCode == Activity.RESULT_FIRST_USER) { resultIntent.putExtra("data", resultBundle); getActivity().setResult(Activity.RESULT_CANCELED, resultIntent); getActivity().finish(); } } break; default: break; } } /** * This interface must be implemented by activities that contain this * fragment to allow an interaction in this fragment to be communicated to * the activity and potentially other fragments contained in that activity. * See the Android Training lesson <a href= * "http://developer.android.com/training/basics/fragments/communicating.html" * >Communicating with Other Fragments</a> for more information. */ public interface OnFragmentInteractionListener { void onFragmentInteraction(Uri uri); } }
Add getContext() that calls getActivity()
src/de/evosec/fotilo/CamFragment.java
Add getContext() that calls getActivity()
Java
mit
b70492b56b29e52d2e35c2521ee98d2050b675a5
0
DeviceConnect/DeviceConnect-Android,DeviceConnect/DeviceConnect-Android,TakayukiHoshi1984/DeviceConnect-Android,DeviceConnect/DeviceConnect-Android,DeviceConnect/DeviceConnect-Android,DeviceConnect/DeviceConnect-Android,TakayukiHoshi1984/DeviceConnect-Android,TakayukiHoshi1984/DeviceConnect-Android,TakayukiHoshi1984/DeviceConnect-Android,TakayukiHoshi1984/DeviceConnect-Android
/* DConnectMessageService.java Copyright (c) 2014 NTT DOCOMO,INC. Released under the MIT license http://opensource.org/licenses/mit-license.php */ package org.deviceconnect.android.message; import android.app.Service; import android.content.Context; import android.content.Intent; import android.content.res.AssetManager; import android.os.Binder; import android.os.Bundle; import android.os.IBinder; import org.deviceconnect.android.BuildConfig; import org.deviceconnect.android.compat.AuthorizationRequestConverter; import org.deviceconnect.android.compat.LowerCaseConverter; import org.deviceconnect.android.compat.MessageConverter; import org.deviceconnect.android.compat.ServiceDiscoveryRequestConverter; import org.deviceconnect.android.event.Event; import org.deviceconnect.android.event.EventManager; import org.deviceconnect.android.event.cache.EventCacheController; import org.deviceconnect.android.event.cache.MemoryCacheController; import org.deviceconnect.android.localoauth.CheckAccessTokenResult; import org.deviceconnect.android.localoauth.DevicePluginXmlProfile; import org.deviceconnect.android.localoauth.DevicePluginXmlUtil; import org.deviceconnect.android.localoauth.LocalOAuth2Main; import org.deviceconnect.android.logger.AndroidHandler; import org.deviceconnect.android.profile.AuthorizationProfile; import org.deviceconnect.android.profile.DConnectProfile; import org.deviceconnect.android.profile.DConnectProfileProvider; import org.deviceconnect.android.profile.ServiceDiscoveryProfile; import org.deviceconnect.android.profile.SystemProfile; import org.deviceconnect.android.profile.spec.DConnectPluginSpec; import org.deviceconnect.android.profile.spec.DConnectProfileSpec; import org.deviceconnect.android.service.DConnectService; import org.deviceconnect.android.service.DConnectServiceManager; import org.deviceconnect.android.service.DConnectServiceProvider; import org.deviceconnect.message.DConnectMessage; import org.deviceconnect.message.intent.message.IntentDConnectMessage; import org.deviceconnect.profile.AuthorizationProfileConstants; import org.deviceconnect.profile.ServiceDiscoveryProfileConstants; import org.deviceconnect.profile.SystemProfileConstants; import org.json.JSONException; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import java.util.logging.SimpleFormatter; /** * Device Connectメッセージサービス. * * <p> * Device Connectリクエストメッセージを受信し、Device Connectレスポンスメッセージを送信するサービスである。 * {@link DConnectMessageServiceProvider}から呼び出されるサービスとし、UIレイヤーから明示的な呼び出しは行わない。 * @author NTT DOCOMO, INC. */ public abstract class DConnectMessageService extends Service implements DConnectProfileProvider { /** * LocalOAuthで無視するプロファイル群. */ private static final String[] IGNORE_PROFILES = { AuthorizationProfileConstants.PROFILE_NAME.toLowerCase(), SystemProfileConstants.PROFILE_NAME.toLowerCase(), ServiceDiscoveryProfileConstants.PROFILE_NAME.toLowerCase() }; /** プロファイル仕様定義ファイルの拡張子. */ private static final String SPEC_FILE_EXTENSION = ".json"; /** * ロガー. */ private Logger mLogger = Logger.getLogger("org.deviceconnect.dplugin"); /** * プロファイルインスタンスマップ. */ private Map<String, DConnectProfile> mProfileMap = new HashMap<>(); /** * Local OAuth使用フラグ. * デフォルトではtrueにしておくこと。 */ private boolean mUseLocalOAuth = true; private DConnectServiceProvider mServiceProvider; private final MessageConverter[] mRequestConverters = { new ServiceDiscoveryRequestConverter(), new AuthorizationRequestConverter(), new LowerCaseConverter() }; /** * SystemProfileを取得する. * SystemProfileは必須実装となるため、本メソッドでSystemProfileのインスタンスを渡すこと。 * このメソッドで返却したSystemProfileは自動で登録される。 * * @return SystemProfileのインスタンス */ protected abstract SystemProfile getSystemProfile(); /** * EventCacheControllerのインスタンスを返す. * * <p> * デフォルトではMemoryCacheControllerを使用する. * 変更したい場合は本メソッドをオーバーライドすること. * </p> * * @return EventCacheControllerのインスタンス */ protected EventCacheController getEventCacheController() { return new MemoryCacheController(); } public final DConnectServiceProvider getServiceProvider() { return mServiceProvider; } protected final void setServiceProvider(final DConnectServiceProvider provider) { mServiceProvider = provider; } protected final DConnectPluginSpec getPluginSpec() { return mPluginSpec; } private DConnectPluginSpec mPluginSpec; private final IBinder mLocalBinder = new LocalBinder(); @Override public void onCreate() { super.onCreate(); setLogLevel(); EventManager.INSTANCE.setController(getEventCacheController()); mPluginSpec = loadPluginSpec(); DConnectServiceManager serviceManager = new DConnectServiceManager(); serviceManager.setPluginSpec(mPluginSpec); serviceManager.setContext(getContext()); mServiceProvider = serviceManager; // LocalOAuthの初期化 LocalOAuth2Main.initialize(this); // 認証プロファイルの追加 addProfile(new AuthorizationProfile(this)); // 必須プロファイルの追加 addProfile(new ServiceDiscoveryProfile(mServiceProvider)); addProfile(getSystemProfile()); } private void setLogLevel() { if (BuildConfig.DEBUG) { AndroidHandler handler = new AndroidHandler(mLogger.getName()); handler.setFormatter(new SimpleFormatter()); handler.setLevel(Level.ALL); mLogger.addHandler(handler); mLogger.setLevel(Level.ALL); } else { mLogger.setLevel(Level.OFF); } } private DConnectPluginSpec loadPluginSpec() { final Map<String, DevicePluginXmlProfile> supportedProfiles = DevicePluginXmlUtil.getSupportProfiles(this, getPackageName()); final Set<String> profileNames = supportedProfiles.keySet(); final DConnectPluginSpec pluginSpec = new DConnectPluginSpec(); for (String profileName : profileNames) { String key = profileName.toLowerCase(); try { AssetManager assets = getAssets(); String path = findProfileSpecPath(assets, profileName); pluginSpec.addProfileSpec(key, getAssets().open(path)); mLogger.info("Loaded a profile spec: " + profileName); } catch (IOException e) { throw new RuntimeException("Failed to load a profile spec: " + profileName, e); } catch (JSONException e) { throw new RuntimeException("Failed to load a profile spec: " + profileName, e); } } return pluginSpec; } private static String findProfileSpecPath(final AssetManager assets, final String profileName) throws IOException { String[] fileNames = assets.list("api"); if (fileNames == null) { return null; } for (String fileFullName : fileNames) { if (!fileFullName.endsWith(SPEC_FILE_EXTENSION)) { continue; } String fileName = fileFullName.substring(0, fileFullName.length() - SPEC_FILE_EXTENSION.length()); if (fileName.equalsIgnoreCase(profileName)) { return "api/" + fileFullName; } } throw new FileNotFoundException("A spec file is not found: " + profileName); } @Override public void onDestroy() { super.onDestroy(); // LocalOAuthの後始末 LocalOAuth2Main.destroy(); } @Override public IBinder onBind(final Intent intent) { return mLocalBinder; } @Override public int onStartCommand(final Intent intent, final int flags, final int startId) { super.onStartCommand(intent, flags, startId); if (intent == null) { mLogger.warning("request intent is null."); return START_STICKY; } String action = intent.getAction(); if (action == null) { mLogger.warning("request action is null. "); return START_STICKY; } if (checkRequestAction(action)) { convertRequest(intent); onRequest(intent, MessageUtils.createResponseIntent(intent)); } if (checkManagerUninstall(intent)) { onManagerUninstalled(); } if (checkManagerTerminate(action)) { onManagerTerminated(); } if (checkManagerEventTransmitDisconnect(action)) { onManagerEventTransmitDisconnected(intent.getStringExtra(IntentDConnectMessage.EXTRA_ORIGIN)); } if (checkDevicePluginReset(action)) { onDevicePluginReset(); } return START_STICKY; } /** * 指定されたアクションがDevice Connectのアクションかチェックします. * @param action チェックするアクション * @return Device Connectのアクションの場合はtrue、それ以外はfalse */ private boolean checkRequestAction(String action) { return IntentDConnectMessage.ACTION_GET.equals(action) || IntentDConnectMessage.ACTION_POST.equals(action) || IntentDConnectMessage.ACTION_PUT.equals(action) || IntentDConnectMessage.ACTION_DELETE.equals(action); } private void convertRequest(final Intent request) { for (MessageConverter converter : mRequestConverters) { converter.convert(request); } } /** * Device Connect Managerがアンインストールされたかをチェックします. * @param intent intentパラメータ * @return アンインストール時はtrue、それ以外はfalse */ private boolean checkManagerUninstall(final Intent intent) { return Intent.ACTION_PACKAGE_FULLY_REMOVED.equals(intent.getAction()) && intent.getExtras().getBoolean(Intent.EXTRA_DATA_REMOVED) && intent.getDataString().contains("package:org.deviceconnect.android.manager"); } /** * Device Connect Manager 正常終了通知を受信したかをチェックします. * @param action チェックするアクション * @return Manager 正常終了検知でtrue、それ以外はfalse */ private boolean checkManagerTerminate(String action) { return IntentDConnectMessage.ACTION_MANAGER_TERMINATED.equals(action); } /** * Device Connect Manager のEvent 送信経路切断通知を受信したかチェックします. * @param action チェックするアクション * @return 検知受信でtrue、それ以外はfalse */ private boolean checkManagerEventTransmitDisconnect(String action) { return IntentDConnectMessage.ACTION_EVENT_TRANSMIT_DISCONNECT.equals(action); } /** * Device Plug-inへのReset要求を受信したかチェックします. * @param action チェックするアクション * @return Reset要求受信でtrue、それ以外はfalse */ private boolean checkDevicePluginReset(String action) { return IntentDConnectMessage.ACTION_DEVICEPLUGIN_RESET.equals(action); } /** * 受信したリクエストをプロファイルに振り分ける. * * @param request リクエストパラメータ * @param response レスポンスパラメータ */ protected void onRequest(final Intent request, final Intent response) { if (BuildConfig.DEBUG) { mLogger.info("request: " + request); mLogger.info("request extras: " + request.getExtras()); } // プロファイル名の取得 String profileName = request.getStringExtra(DConnectMessage.EXTRA_PROFILE); if (profileName == null) { MessageUtils.setNotSupportProfileError(response); sendResponse(response); return; } boolean send = true; if (isUseLocalOAuth()) { // アクセストークン String accessToken = request.getStringExtra(AuthorizationProfile.PARAM_ACCESS_TOKEN); // LocalOAuth処理 CheckAccessTokenResult result = LocalOAuth2Main.checkAccessToken(accessToken, profileName, IGNORE_PROFILES); if (result.checkResult()) { send = executeRequest(profileName, request, response); } else { if (accessToken == null) { MessageUtils.setEmptyAccessTokenError(response); } else if (!result.isExistAccessToken()) { MessageUtils.setNotFoundClientId(response); } else if (!result.isExistClientId()) { MessageUtils.setNotFoundClientId(response); } else if (!result.isExistScope()) { MessageUtils.setScopeError(response); } else if (!result.isNotExpired()) { MessageUtils.setExpiredAccessTokenError(response); } else { MessageUtils.setAuthorizationError(response); } } } else { send = executeRequest(profileName, request, response); } if (send) { sendResponse(response); } } protected boolean executeRequest(final String profileName, final Intent request, final Intent response) { DConnectProfile profile = getProfile(profileName); if (profile == null) { String serviceId = DConnectProfile.getServiceID(request); DConnectService service = getServiceProvider().getService(serviceId); if (service != null) { return service.onRequest(request, response); } else { MessageUtils.setNotFoundServiceError(response); return true; } } else { return profile.onRequest(request, response); } } /** * {@inheritDoc} */ @Override public List<DConnectProfile> getProfileList() { return new ArrayList<>(mProfileMap.values()); } /** * {@inheritDoc} */ @Override public DConnectProfile getProfile(final String name) { if (name == null) { return null; } //XXXX パスの大文字小文字の無視 return mProfileMap.get(name.toLowerCase()); } /** * {@inheritDoc} */ @Override public void addProfile(final DConnectProfile profile) { if (profile == null) { return; } String profileName = profile.getProfileName().toLowerCase(); profile.setContext(this); DConnectProfileSpec profileSpec = mPluginSpec.findProfileSpec(profileName); if (profileSpec != null) { profile.setProfileSpec(profileSpec); } //XXXX パスの大文字小文字の無視 mProfileMap.put(profileName, profile); } /** * {@inheritDoc} */ @Override public void removeProfile(final DConnectProfile profile) { if (profile == null) { return; } //XXXX パスの大文字小文字の無視 mProfileMap.remove(profile.getProfileName().toLowerCase()); } /** * コンテキストの取得する. * * @return コンテキスト */ public final Context getContext() { return this; } /** * Device Connect Managerにレスポンスを返却するためのメソッド. * @param response レスポンス * @return 送信成功の場合true、それ以外はfalse */ public final boolean sendResponse(final Intent response) { // TODO チェックが必要な追加すること。 if (response == null) { throw new IllegalArgumentException("response is null."); } if (BuildConfig.DEBUG) { mLogger.info("sendResponse: " + response); mLogger.info("sendResponse Extra: " + response.getExtras()); } getContext().sendBroadcast(response); return true; } /** * Device Connectにイベントを送信する. * * @param event イベントパラメータ * @param accessToken 送り先のアクセストークン * @return 送信成功の場合true、アクセストークンエラーの場合はfalseを返す。 */ public final boolean sendEvent(final Intent event, final String accessToken) { // TODO 返り値をもっと詳細なものにするか要検討 if (event == null) { throw new IllegalArgumentException("Event is null."); } if (isUseLocalOAuth()) { CheckAccessTokenResult result = LocalOAuth2Main.checkAccessToken(accessToken, event.getStringExtra(DConnectMessage.EXTRA_PROFILE), IGNORE_PROFILES); if (!result.checkResult()) { return false; } } if (BuildConfig.DEBUG) { mLogger.info("sendEvent: " + event); mLogger.info("sendEvent Extra: " + event.getExtras()); } getContext().sendBroadcast(event); return true; } /** * Device Connectにイベントを送信する. * * @param event イベントパラメータ * @param bundle パラメータ * @return 送信成功の場合true、アクセストークンエラーの場合はfalseを返す。 */ public final boolean sendEvent(final Event event, final Bundle bundle) { Intent intent = EventManager.createEventMessage(event); Bundle original = intent.getExtras(); original.putAll(bundle); intent.putExtras(original); return sendEvent(intent, event.getAccessToken()); } /** * Local OAuth使用フラグを設定する. * * このフラグをfalseに設定することで、LocalOAuthの機能をOFFにすることができる。 * デフォルトでは、trueになっているので、LocalOAuthが有効になっている。 * * @param use フラグ */ protected void setUseLocalOAuth(final boolean use) { mUseLocalOAuth = use; } /** * Local OAuth使用フラグを取得する. * * @return 使用する場合にはtrue、それ以外はfalse */ public boolean isUseLocalOAuth() { return mUseLocalOAuth; } public boolean isIgnoredProfile(final String profileName) { for (String name : IGNORE_PROFILES) { if (name.equalsIgnoreCase(profileName)) { // MEMO パスの大文字小文字を無視 return true; } } return false; } /** * Device Connect Managerがアンインストールされた時に呼ばれる処理部. */ protected void onManagerUninstalled() { mLogger.info("SDK : onManagerUninstalled"); } /** * Device Connect Managerの正常終了通知を受信した時に呼ばれる処理部. */ protected void onManagerTerminated() { mLogger.info("SDK : on ManagerTerminated"); } /** * Device Connect ManagerのEvent送信経路切断通知を受信した時に呼ばれる処理部. * @param origin オリジン */ protected void onManagerEventTransmitDisconnected(final String origin) { mLogger.info("SDK : onManagerEventTransmitDisconnected"); } /** * Device Plug-inへのReset要求を受信した時に呼ばれる処理部. */ protected void onDevicePluginReset() { mLogger.info("SDK : onDevicePluginReset"); } public class LocalBinder extends Binder { public DConnectMessageService getMessageService() { return DConnectMessageService.this; } } }
dConnectDevicePlugin/dConnectDevicePluginSDK/dconnect-device-plugin-sdk/src/main/java/org/deviceconnect/android/message/DConnectMessageService.java
/* DConnectMessageService.java Copyright (c) 2014 NTT DOCOMO,INC. Released under the MIT license http://opensource.org/licenses/mit-license.php */ package org.deviceconnect.android.message; import android.app.Service; import android.content.Context; import android.content.Intent; import android.content.res.AssetManager; import android.os.Binder; import android.os.Bundle; import android.os.IBinder; import org.deviceconnect.android.BuildConfig; import org.deviceconnect.android.compat.AuthorizationRequestConverter; import org.deviceconnect.android.compat.LowerCaseConverter; import org.deviceconnect.android.compat.MessageConverter; import org.deviceconnect.android.compat.ServiceDiscoveryRequestConverter; import org.deviceconnect.android.event.Event; import org.deviceconnect.android.event.EventManager; import org.deviceconnect.android.event.cache.EventCacheController; import org.deviceconnect.android.event.cache.MemoryCacheController; import org.deviceconnect.android.localoauth.CheckAccessTokenResult; import org.deviceconnect.android.localoauth.DevicePluginXmlProfile; import org.deviceconnect.android.localoauth.DevicePluginXmlUtil; import org.deviceconnect.android.localoauth.LocalOAuth2Main; import org.deviceconnect.android.profile.AuthorizationProfile; import org.deviceconnect.android.profile.DConnectProfile; import org.deviceconnect.android.profile.DConnectProfileProvider; import org.deviceconnect.android.profile.ServiceDiscoveryProfile; import org.deviceconnect.android.profile.SystemProfile; import org.deviceconnect.android.profile.spec.DConnectPluginSpec; import org.deviceconnect.android.profile.spec.DConnectProfileSpec; import org.deviceconnect.android.service.DConnectService; import org.deviceconnect.android.service.DConnectServiceManager; import org.deviceconnect.android.service.DConnectServiceProvider; import org.deviceconnect.message.DConnectMessage; import org.deviceconnect.message.intent.message.IntentDConnectMessage; import org.deviceconnect.profile.AuthorizationProfileConstants; import org.deviceconnect.profile.ServiceDiscoveryProfileConstants; import org.deviceconnect.profile.SystemProfileConstants; import org.json.JSONException; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.logging.Logger; /** * Device Connectメッセージサービス. * * <p> * Device Connectリクエストメッセージを受信し、Device Connectレスポンスメッセージを送信するサービスである。 * {@link DConnectMessageServiceProvider}から呼び出されるサービスとし、UIレイヤーから明示的な呼び出しは行わない。 * @author NTT DOCOMO, INC. */ public abstract class DConnectMessageService extends Service implements DConnectProfileProvider { /** * LocalOAuthで無視するプロファイル群. */ private static final String[] IGNORE_PROFILES = { AuthorizationProfileConstants.PROFILE_NAME.toLowerCase(), SystemProfileConstants.PROFILE_NAME.toLowerCase(), ServiceDiscoveryProfileConstants.PROFILE_NAME.toLowerCase() }; /** プロファイル仕様定義ファイルの拡張子. */ private static final String SPEC_FILE_EXTENSION = ".json"; /** * ロガー. */ private Logger mLogger = Logger.getLogger("org.deviceconnect.dplugin"); /** * プロファイルインスタンスマップ. */ private Map<String, DConnectProfile> mProfileMap = new HashMap<>(); /** * Local OAuth使用フラグ. * デフォルトではtrueにしておくこと。 */ private boolean mUseLocalOAuth = true; private DConnectServiceProvider mServiceProvider; private final MessageConverter[] mRequestConverters = { new ServiceDiscoveryRequestConverter(), new AuthorizationRequestConverter(), new LowerCaseConverter() }; /** * SystemProfileを取得する. * SystemProfileは必須実装となるため、本メソッドでSystemProfileのインスタンスを渡すこと。 * このメソッドで返却したSystemProfileは自動で登録される。 * * @return SystemProfileのインスタンス */ protected abstract SystemProfile getSystemProfile(); /** * EventCacheControllerのインスタンスを返す. * * <p> * デフォルトではMemoryCacheControllerを使用する. * 変更したい場合は本メソッドをオーバーライドすること. * </p> * * @return EventCacheControllerのインスタンス */ protected EventCacheController getEventCacheController() { return new MemoryCacheController(); } public final DConnectServiceProvider getServiceProvider() { return mServiceProvider; } protected final void setServiceProvider(final DConnectServiceProvider provider) { mServiceProvider = provider; } protected final DConnectPluginSpec getPluginSpec() { return mPluginSpec; } private DConnectPluginSpec mPluginSpec; private final IBinder mLocalBinder = new LocalBinder(); @Override public void onCreate() { super.onCreate(); EventManager.INSTANCE.setController(getEventCacheController()); mPluginSpec = loadPluginSpec(); DConnectServiceManager serviceManager = new DConnectServiceManager(); serviceManager.setPluginSpec(mPluginSpec); serviceManager.setContext(getContext()); mServiceProvider = serviceManager; // LocalOAuthの初期化 LocalOAuth2Main.initialize(this); // 認証プロファイルの追加 addProfile(new AuthorizationProfile(this)); // 必須プロファイルの追加 addProfile(new ServiceDiscoveryProfile(mServiceProvider)); addProfile(getSystemProfile()); } private DConnectPluginSpec loadPluginSpec() { final Map<String, DevicePluginXmlProfile> supportedProfiles = DevicePluginXmlUtil.getSupportProfiles(this, getPackageName()); final Set<String> profileNames = supportedProfiles.keySet(); final DConnectPluginSpec pluginSpec = new DConnectPluginSpec(); for (String profileName : profileNames) { String key = profileName.toLowerCase(); try { AssetManager assets = getAssets(); String path = findProfileSpecPath(assets, profileName); pluginSpec.addProfileSpec(key, getAssets().open(path)); mLogger.info("Loaded a profile spec: " + profileName); } catch (IOException e) { throw new RuntimeException("Failed to load a profile spec: " + profileName, e); } catch (JSONException e) { throw new RuntimeException("Failed to load a profile spec: " + profileName, e); } } return pluginSpec; } private static String findProfileSpecPath(final AssetManager assets, final String profileName) throws IOException { String[] fileNames = assets.list("api"); if (fileNames == null) { return null; } for (String fileFullName : fileNames) { if (!fileFullName.endsWith(SPEC_FILE_EXTENSION)) { continue; } String fileName = fileFullName.substring(0, fileFullName.length() - SPEC_FILE_EXTENSION.length()); if (fileName.equalsIgnoreCase(profileName)) { return "api/" + fileFullName; } } throw new FileNotFoundException("A spec file is not found: " + profileName); } @Override public void onDestroy() { super.onDestroy(); // LocalOAuthの後始末 LocalOAuth2Main.destroy(); } @Override public IBinder onBind(final Intent intent) { return mLocalBinder; } @Override public int onStartCommand(final Intent intent, final int flags, final int startId) { super.onStartCommand(intent, flags, startId); if (intent == null) { mLogger.warning("request intent is null."); return START_STICKY; } String action = intent.getAction(); if (action == null) { mLogger.warning("request action is null. "); return START_STICKY; } if (checkRequestAction(action)) { convertRequest(intent); onRequest(intent, MessageUtils.createResponseIntent(intent)); } if (checkManagerUninstall(intent)) { onManagerUninstalled(); } if (checkManagerTerminate(action)) { onManagerTerminated(); } if (checkManagerEventTransmitDisconnect(action)) { onManagerEventTransmitDisconnected(intent.getStringExtra(IntentDConnectMessage.EXTRA_ORIGIN)); } if (checkDevicePluginReset(action)) { onDevicePluginReset(); } return START_STICKY; } /** * 指定されたアクションがDevice Connectのアクションかチェックします. * @param action チェックするアクション * @return Device Connectのアクションの場合はtrue、それ以外はfalse */ private boolean checkRequestAction(String action) { return IntentDConnectMessage.ACTION_GET.equals(action) || IntentDConnectMessage.ACTION_POST.equals(action) || IntentDConnectMessage.ACTION_PUT.equals(action) || IntentDConnectMessage.ACTION_DELETE.equals(action); } private void convertRequest(final Intent request) { for (MessageConverter converter : mRequestConverters) { converter.convert(request); } } /** * Device Connect Managerがアンインストールされたかをチェックします. * @param intent intentパラメータ * @return アンインストール時はtrue、それ以外はfalse */ private boolean checkManagerUninstall(final Intent intent) { return Intent.ACTION_PACKAGE_FULLY_REMOVED.equals(intent.getAction()) && intent.getExtras().getBoolean(Intent.EXTRA_DATA_REMOVED) && intent.getDataString().contains("package:org.deviceconnect.android.manager"); } /** * Device Connect Manager 正常終了通知を受信したかをチェックします. * @param action チェックするアクション * @return Manager 正常終了検知でtrue、それ以外はfalse */ private boolean checkManagerTerminate(String action) { return IntentDConnectMessage.ACTION_MANAGER_TERMINATED.equals(action); } /** * Device Connect Manager のEvent 送信経路切断通知を受信したかチェックします. * @param action チェックするアクション * @return 検知受信でtrue、それ以外はfalse */ private boolean checkManagerEventTransmitDisconnect(String action) { return IntentDConnectMessage.ACTION_EVENT_TRANSMIT_DISCONNECT.equals(action); } /** * Device Plug-inへのReset要求を受信したかチェックします. * @param action チェックするアクション * @return Reset要求受信でtrue、それ以外はfalse */ private boolean checkDevicePluginReset(String action) { return IntentDConnectMessage.ACTION_DEVICEPLUGIN_RESET.equals(action); } /** * 受信したリクエストをプロファイルに振り分ける. * * @param request リクエストパラメータ * @param response レスポンスパラメータ */ protected void onRequest(final Intent request, final Intent response) { if (BuildConfig.DEBUG) { mLogger.info("request: " + request); mLogger.info("request extras: " + request.getExtras()); } // プロファイル名の取得 String profileName = request.getStringExtra(DConnectMessage.EXTRA_PROFILE); if (profileName == null) { MessageUtils.setNotSupportProfileError(response); sendResponse(response); return; } boolean send = true; if (isUseLocalOAuth()) { // アクセストークン String accessToken = request.getStringExtra(AuthorizationProfile.PARAM_ACCESS_TOKEN); // LocalOAuth処理 CheckAccessTokenResult result = LocalOAuth2Main.checkAccessToken(accessToken, profileName, IGNORE_PROFILES); if (result.checkResult()) { send = executeRequest(profileName, request, response); } else { if (accessToken == null) { MessageUtils.setEmptyAccessTokenError(response); } else if (!result.isExistAccessToken()) { MessageUtils.setNotFoundClientId(response); } else if (!result.isExistClientId()) { MessageUtils.setNotFoundClientId(response); } else if (!result.isExistScope()) { MessageUtils.setScopeError(response); } else if (!result.isNotExpired()) { MessageUtils.setExpiredAccessTokenError(response); } else { MessageUtils.setAuthorizationError(response); } } } else { send = executeRequest(profileName, request, response); } if (send) { sendResponse(response); } } protected boolean executeRequest(final String profileName, final Intent request, final Intent response) { DConnectProfile profile = getProfile(profileName); if (profile == null) { String serviceId = DConnectProfile.getServiceID(request); DConnectService service = getServiceProvider().getService(serviceId); if (service != null) { return service.onRequest(request, response); } else { MessageUtils.setNotFoundServiceError(response); return true; } } else { return profile.onRequest(request, response); } } /** * {@inheritDoc} */ @Override public List<DConnectProfile> getProfileList() { return new ArrayList<>(mProfileMap.values()); } /** * {@inheritDoc} */ @Override public DConnectProfile getProfile(final String name) { if (name == null) { return null; } //XXXX パスの大文字小文字の無視 return mProfileMap.get(name.toLowerCase()); } /** * {@inheritDoc} */ @Override public void addProfile(final DConnectProfile profile) { if (profile == null) { return; } String profileName = profile.getProfileName().toLowerCase(); profile.setContext(this); DConnectProfileSpec profileSpec = mPluginSpec.findProfileSpec(profileName); if (profileSpec != null) { profile.setProfileSpec(profileSpec); } //XXXX パスの大文字小文字の無視 mProfileMap.put(profileName, profile); } /** * {@inheritDoc} */ @Override public void removeProfile(final DConnectProfile profile) { if (profile == null) { return; } //XXXX パスの大文字小文字の無視 mProfileMap.remove(profile.getProfileName().toLowerCase()); } /** * コンテキストの取得する. * * @return コンテキスト */ public final Context getContext() { return this; } /** * Device Connect Managerにレスポンスを返却するためのメソッド. * @param response レスポンス * @return 送信成功の場合true、それ以外はfalse */ public final boolean sendResponse(final Intent response) { // TODO チェックが必要な追加すること。 if (response == null) { throw new IllegalArgumentException("response is null."); } if (BuildConfig.DEBUG) { mLogger.info("sendResponse: " + response); mLogger.info("sendResponse Extra: " + response.getExtras()); } getContext().sendBroadcast(response); return true; } /** * Device Connectにイベントを送信する. * * @param event イベントパラメータ * @param accessToken 送り先のアクセストークン * @return 送信成功の場合true、アクセストークンエラーの場合はfalseを返す。 */ public final boolean sendEvent(final Intent event, final String accessToken) { // TODO 返り値をもっと詳細なものにするか要検討 if (event == null) { throw new IllegalArgumentException("Event is null."); } if (isUseLocalOAuth()) { CheckAccessTokenResult result = LocalOAuth2Main.checkAccessToken(accessToken, event.getStringExtra(DConnectMessage.EXTRA_PROFILE), IGNORE_PROFILES); if (!result.checkResult()) { return false; } } if (BuildConfig.DEBUG) { mLogger.info("sendEvent: " + event); mLogger.info("sendEvent Extra: " + event.getExtras()); } getContext().sendBroadcast(event); return true; } /** * Device Connectにイベントを送信する. * * @param event イベントパラメータ * @param bundle パラメータ * @return 送信成功の場合true、アクセストークンエラーの場合はfalseを返す。 */ public final boolean sendEvent(final Event event, final Bundle bundle) { Intent intent = EventManager.createEventMessage(event); Bundle original = intent.getExtras(); original.putAll(bundle); intent.putExtras(original); return sendEvent(intent, event.getAccessToken()); } /** * Local OAuth使用フラグを設定する. * * このフラグをfalseに設定することで、LocalOAuthの機能をOFFにすることができる。 * デフォルトでは、trueになっているので、LocalOAuthが有効になっている。 * * @param use フラグ */ protected void setUseLocalOAuth(final boolean use) { mUseLocalOAuth = use; } /** * Local OAuth使用フラグを取得する. * * @return 使用する場合にはtrue、それ以外はfalse */ public boolean isUseLocalOAuth() { return mUseLocalOAuth; } public boolean isIgnoredProfile(final String profileName) { for (String name : IGNORE_PROFILES) { if (name.equalsIgnoreCase(profileName)) { // MEMO パスの大文字小文字を無視 return true; } } return false; } /** * Device Connect Managerがアンインストールされた時に呼ばれる処理部. */ protected void onManagerUninstalled() { mLogger.info("SDK : onManagerUninstalled"); } /** * Device Connect Managerの正常終了通知を受信した時に呼ばれる処理部. */ protected void onManagerTerminated() { mLogger.info("SDK : on ManagerTerminated"); } /** * Device Connect ManagerのEvent送信経路切断通知を受信した時に呼ばれる処理部. * @param origin オリジン */ protected void onManagerEventTransmitDisconnected(final String origin) { mLogger.info("SDK : onManagerEventTransmitDisconnected"); } /** * Device Plug-inへのReset要求を受信した時に呼ばれる処理部. */ protected void onDevicePluginReset() { mLogger.info("SDK : onDevicePluginReset"); } public class LocalBinder extends Binder { public DConnectMessageService getMessageService() { return DConnectMessageService.this; } } }
リリースビルド時にデバイスプラグインSDKのデバッグログをOFF。
dConnectDevicePlugin/dConnectDevicePluginSDK/dconnect-device-plugin-sdk/src/main/java/org/deviceconnect/android/message/DConnectMessageService.java
リリースビルド時にデバイスプラグインSDKのデバッグログをOFF。
Java
mit
0878ccd9a73739aa931047fee5784dd9a73bb33c
0
lare96/luna
package io.luna.game.model; import io.luna.game.GameService; /** * Manages global state as well as the various types in the * {@code io.luna.game.model} package and subpackages. * * @author lare96 <http://github.org/lare96> */ public final class World { // TODO: Manage global state in the Luna class? /** * The main game logic service. */ private static GameService service = new GameService(); /** * A private constructor to discourage external instantiation. */ private World() {} /** * Gets the main game logic service. * * @return the logic service. */ public static GameService getService() { return service; } }
src/main/io/luna/game/model/World.java
package io.luna.game.model; import io.luna.game.GameService; /** * Manages global state as well as the various types in the * {@code io.luna.game.model} package and subpackages. * * @author lare96 <http://github.org/lare96> */ public final class World { /** * The main game logic service. */ private static GameService service = new GameService(); /** * A private constructor to discourage external instantiation. */ private World() {} /** * Gets the main game logic service. * * @return the logic service. */ public static GameService getService() { return service; } }
TODO for the World.
src/main/io/luna/game/model/World.java
TODO for the World.
Java
mit
941155d21558101f5a6ae034ff26a58ab27c3140
0
y20k/transistor,meonwax/transistor
/** * PlayerService.java * Implements the app's playback background service * The player service does xyz * * This file is part of * TRANSISTOR - Radio App for Android * * Copyright (c) 2015 - Y20K.org * Licensed under the MIT-License * http://opensource.org/licenses/MIT */ package org.y20k.transistor; import android.app.NotificationManager; import android.app.Service; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.media.AudioManager; import android.media.MediaPlayer; import android.os.IBinder; import android.preference.PreferenceManager; import android.support.v4.content.LocalBroadcastManager; import android.util.Log; import android.widget.Toast; import org.y20k.transistor.helpers.NotificationHelper; import java.io.IOException; /** * PlayerService class */ public final class PlayerService extends Service implements AudioManager.OnAudioFocusChangeListener, MediaPlayer.OnCompletionListener, MediaPlayer.OnPreparedListener, MediaPlayer.OnErrorListener, MediaPlayer.OnInfoListener { /* Define log tag */ private static final String LOG_TAG = PlayerService.class.getSimpleName(); /* Keys */ private static final String ACTION_PLAY = "org.y20k.transistor.action.PLAY"; private static final String ACTION_STOP = "org.y20k.transistor.action.STOP"; private static final String ACTION_PLAYBACK_STARTED = "org.y20k.transistor.action.PLAYBACK_STARTED"; private static final String ACTION_PLAYBACK_STOPPED = "org.y20k.transistor.action.PLAYBACK_STOPPED"; private static final String EXTRA_STREAM_URI = "STREAM_URI"; private static final String PLAYBACK = "playback"; private static final int PLAYER_SERVICE_NOTIFICATION_ID = 1; /* Main class variables */ private AudioManager mAudioManager; private MediaPlayer mMediaPlayer; private String mStreamUri; private boolean mPlayback; private int mPlayerInstanceCounter; private HeadphoneUnplugReceiver mHeadphoneUnplugReceiver; /* Constructor (default) */ public PlayerService() { } @Override public void onCreate() { super.onCreate(); // set up variables mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE); mMediaPlayer = null; mPlayerInstanceCounter = 0; // Listen for headphone unplug IntentFilter headphoneUnplugIntentFilter = new IntentFilter(AudioManager.ACTION_AUDIO_BECOMING_NOISY); mHeadphoneUnplugReceiver = new HeadphoneUnplugReceiver(); registerReceiver(mHeadphoneUnplugReceiver, headphoneUnplugIntentFilter); // TODO Listen for headphone button // Use MediaSession } @Override public int onStartCommand(Intent intent, int flags, int startId) { // checking for empty intent if (intent == null) { Log.v(LOG_TAG, "Null-Intent received. Stopping self."); stopSelf(); } // ACTION PLAY else if (intent.getAction().equals(ACTION_PLAY)) { Log.v(LOG_TAG, "Service received command: PLAY"); // set mPlayback true mPlayback = true; // get URL of station from intent mStreamUri = intent.getStringExtra(EXTRA_STREAM_URI); // start playback preparePlayback(); } // ACTION STOP else if (intent.getAction().equals(ACTION_STOP)) { Log.v(LOG_TAG, "Service received command: STOP"); // set mPlayback false mPlayback = false; // stop playback finishPlayback(); } // default return value for media playback return START_STICKY; } @Override public IBinder onBind(Intent intent) { return null; } @Override public void onAudioFocusChange(int focusChange) { switch (focusChange) { // gain of audio focus of unknown duration case AudioManager.AUDIOFOCUS_GAIN: if (mPlayback) { if (mMediaPlayer == null) { initializeMediaPlayer(); } else if (!mMediaPlayer.isPlaying()) { mMediaPlayer.start(); } mMediaPlayer.setVolume(1.0f, 1.0f); } break; // loss of audio focus of unknown duration case AudioManager.AUDIOFOCUS_LOSS: finishPlayback(); break; // transient loss of audio focus case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT: if (!mPlayback && mMediaPlayer != null && mMediaPlayer.isPlaying()) { finishPlayback(); } else if (mPlayback && mMediaPlayer != null && mMediaPlayer.isPlaying()) { mMediaPlayer.pause(); } break; // temporary external request of audio focus case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK: if (mMediaPlayer != null && mMediaPlayer.isPlaying()) { mMediaPlayer.setVolume(0.1f, 0.1f); } break; } } @Override public void onCompletion(MediaPlayer mp) { Log.v(LOG_TAG, "Resuming playback after completion / signal loss"); mMediaPlayer.reset(); initializeMediaPlayer(); } @Override public void onPrepared(MediaPlayer mp) { if (mPlayerInstanceCounter == 1) { Log.v(LOG_TAG, "+++ Preparation finished. Starting playback. Player instance count: " + mPlayerInstanceCounter + " +++"); mp.start(); } else { Log.v(LOG_TAG, "Stopping player service and re-initializing media player. Player instance count: " + mPlayerInstanceCounter); mp.stop(); mp.release(); mPlayerInstanceCounter = mPlayerInstanceCounter - 2; initializeMediaPlayer(); } } @Override public boolean onError(MediaPlayer mp, int what, int extra) { switch (what) { case MediaPlayer.MEDIA_ERROR_UNKNOWN: Log.e(LOG_TAG, "Unknown media playback error"); break; case MediaPlayer.MEDIA_ERROR_SERVER_DIED: Log.e(LOG_TAG, "Connection to server lost"); break; default: Log.e(LOG_TAG, "Generic audio playback error"); break; } switch (extra) { case MediaPlayer.MEDIA_ERROR_IO: Log.e(LOG_TAG, "IO media error."); break; case MediaPlayer.MEDIA_ERROR_MALFORMED: Log.e(LOG_TAG, "Malformed media."); break; case MediaPlayer.MEDIA_ERROR_UNSUPPORTED: Log.e(LOG_TAG, "Unsupported content type"); break; case MediaPlayer.MEDIA_ERROR_TIMED_OUT: Log.e(LOG_TAG, "Media timeout"); break; default: Log.e(LOG_TAG, "Other case of media playback error"); break; } mp.reset(); return true; } @Override public boolean onInfo(MediaPlayer mp, int what, int extra) { switch (what){ case MediaPlayer.MEDIA_INFO_UNKNOWN: Log.i(LOG_TAG, "Unknown media info"); break; case MediaPlayer.MEDIA_INFO_BUFFERING_START: Log.i(LOG_TAG, "Buffering started"); break; case MediaPlayer.MEDIA_INFO_BUFFERING_END: Log.i(LOG_TAG, "Buffering finished"); break; case MediaPlayer.MEDIA_INFO_METADATA_UPDATE: Log.i(LOG_TAG, "New metadata available"); break; default: Log.i(LOG_TAG, "other case of media info"); break; } return true; } @Override public void onDestroy() { super.onDestroy(); Log.v(LOG_TAG, "onDestroy called."); // save state mPlayback = false; savePlaybackState(); // unregister receivers this.unregisterReceiver(mHeadphoneUnplugReceiver); // retrieve notification system service and cancel notification NotificationManager notificationManager = (NotificationManager) getApplication().getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.cancel(PLAYER_SERVICE_NOTIFICATION_ID); } /* Method to start the player */ public void startActionPlay(Context context, String streamUri, String stationName) { mStreamUri = streamUri; Log.v(LOG_TAG, "starting playback service: " + mStreamUri); // start player service using intent Intent intent = new Intent(context, PlayerService.class); intent.setAction(ACTION_PLAY); intent.putExtra(EXTRA_STREAM_URI, mStreamUri); context.startService(intent); // put up notification NotificationHelper notificationHelper = new NotificationHelper(context); notificationHelper.setStationName(stationName); notificationHelper.createNotification(); } /* Method to stop the player */ public void startActionStop(Context context) { Log.v(LOG_TAG, "stopping playback service:"); // stop player service using intent Intent intent = new Intent(context, PlayerService.class); intent.setAction(ACTION_STOP); context.startService(intent); } /* Set up the media player */ private void initializeMediaPlayer() { mMediaPlayer = new MediaPlayer(); mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); mMediaPlayer.setOnPreparedListener(this); mMediaPlayer.setOnErrorListener(this); mMediaPlayer.setOnInfoListener(this); mMediaPlayer.setOnBufferingUpdateListener(new MediaPlayer.OnBufferingUpdateListener() { @Override public void onBufferingUpdate(MediaPlayer mp, int percent) { Log.v(LOG_TAG, "Buffering: " + percent); } }); try { mMediaPlayer.setDataSource(mStreamUri); mMediaPlayer.prepareAsync(); mPlayerInstanceCounter++; Log.v(LOG_TAG, "setting: " + mStreamUri); } catch (IllegalArgumentException | IllegalStateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } /* Release the media player */ private void releaseMediaPlayer() { if (mMediaPlayer != null) { if (mMediaPlayer.isPlaying()) { mMediaPlayer.stop(); } mMediaPlayer.reset(); mMediaPlayer.release(); mMediaPlayer = null; } } /* Prepare playback */ private void preparePlayback() { // stop running player if (mMediaPlayer != null && mMediaPlayer.isPlaying()) { releaseMediaPlayer(); } // request focus and initialize media player if (mStreamUri != null && requestFocus()) { initializeMediaPlayer(); } // save state mPlayback = true; savePlaybackState(); // send local broadcast (needed by MainActivityFragment) Intent i = new Intent(); i.setAction(ACTION_PLAYBACK_STARTED); LocalBroadcastManager.getInstance(this.getApplication()).sendBroadcast(i); } /* Finish playback */ private void finishPlayback() { // release player releaseMediaPlayer(); // save state mPlayback = false; savePlaybackState(); // send local broadcast (needed by PlayerActivityFragment and MainActivityFragment) Intent i = new Intent(); i.setAction(ACTION_PLAYBACK_STOPPED); LocalBroadcastManager.getInstance(this.getApplication()).sendBroadcast(i); // retrieve notification system service and cancel notification NotificationManager notificationManager = (NotificationManager) getApplication().getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.cancel(PLAYER_SERVICE_NOTIFICATION_ID); } /* Request audio manager focus */ private boolean requestFocus() { int result = mAudioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN); return result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED; } /* Saves state of playback */ private void savePlaybackState () { SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getApplication()); SharedPreferences.Editor editor = settings.edit(); editor.putBoolean(PLAYBACK, mPlayback); editor.apply(); } /** * Inner class: Receiver for headphone unplug-signal */ public class HeadphoneUnplugReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if (mPlayback && AudioManager.ACTION_AUDIO_BECOMING_NOISY.equals(intent.getAction())) { Log.v(LOG_TAG, "Headphones unplugged. Stopping playback."); // stop playback finishPlayback(); // notify user Toast.makeText(context, R.string.toastalert_headphones_unplugged, Toast.LENGTH_LONG).show(); } } } /** * End of inner class */ }
app/src/main/java/org/y20k/transistor/PlayerService.java
/** * PlayerService.java * Implements the app's playback background service * The player service does xyz * * This file is part of * TRANSISTOR - Radio App for Android * * Copyright (c) 2015 - Y20K.org * Licensed under the MIT-License * http://opensource.org/licenses/MIT */ package org.y20k.transistor; import android.app.NotificationManager; import android.app.Service; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.media.AudioManager; import android.media.MediaPlayer; import android.os.IBinder; import android.preference.PreferenceManager; import android.support.v4.content.LocalBroadcastManager; import android.util.Log; import android.widget.Toast; import org.y20k.transistor.helpers.NotificationHelper; import java.io.IOException; /** * PlayerService class */ public final class PlayerService extends Service implements AudioManager.OnAudioFocusChangeListener, MediaPlayer.OnCompletionListener, MediaPlayer.OnPreparedListener, MediaPlayer.OnErrorListener, MediaPlayer.OnInfoListener { /* Define log tag */ private static final String LOG_TAG = PlayerService.class.getSimpleName(); /* Keys */ private static final String ACTION_PLAY = "org.y20k.transistor.action.PLAY"; private static final String ACTION_STOP = "org.y20k.transistor.action.STOP"; private static final String ACTION_PLAYBACK_STARTED = "org.y20k.transistor.action.PLAYBACK_STARTED"; private static final String ACTION_PLAYBACK_STOPPED = "org.y20k.transistor.action.PLAYBACK_STOPPED"; private static final String EXTRA_STREAM_URI = "STREAM_URI"; private static final String PLAYBACK = "playback"; private static final int PLAYER_SERVICE_NOTIFICATION_ID = 1; /* Main class variables */ private AudioManager mAudioManager; private MediaPlayer mMediaPlayer; private String mStreamUri; private boolean mPlayback; private int mPlayerInstanceCounter; private HeadphoneUnplugReceiver mHeadphoneUnplugReceiver; /* Constructor (default) */ public PlayerService() { } @Override public void onCreate() { super.onCreate(); // set up variables mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE); mMediaPlayer = null; mPlayerInstanceCounter = 0; // Listen for headphone unplug IntentFilter headphoneUnplugIntentFilter = new IntentFilter(AudioManager.ACTION_AUDIO_BECOMING_NOISY); mHeadphoneUnplugReceiver = new HeadphoneUnplugReceiver(); registerReceiver(mHeadphoneUnplugReceiver, headphoneUnplugIntentFilter); // TODO Listen for headphone button // Use MediaSession } @Override public int onStartCommand(Intent intent, int flags, int startId) { // checking for empty intent if (intent == null) { Log.v(LOG_TAG, "Null-Intent received. Stopping self."); stopSelf(); } // ACTION PLAY else if (intent.getAction().equals(ACTION_PLAY)) { Log.v(LOG_TAG, "Service received command: PLAY"); // set mPlayback true mPlayback = true; // get URL of station from intent mStreamUri = intent.getStringExtra(EXTRA_STREAM_URI); // start playback preparePlayback(); } // ACTION STOP else if (intent.getAction().equals(ACTION_STOP)) { Log.v(LOG_TAG, "Service received command: STOP"); // set mPlayback false mPlayback = false; // stop playback finishPlayback(); } // default return value for media playback return START_STICKY; } @Override public IBinder onBind(Intent intent) { return null; } @Override public void onAudioFocusChange(int focusChange) { switch (focusChange) { // gain of audio focus of unknown duration case AudioManager.AUDIOFOCUS_GAIN: if (mPlayback) { if (mMediaPlayer == null) { initializeMediaPlayer(); } else if (!mMediaPlayer.isPlaying()) { mMediaPlayer.start(); } mMediaPlayer.setVolume(1.0f, 1.0f); } break; // loss of audio focus of unknown duration case AudioManager.AUDIOFOCUS_LOSS: finishPlayback(); break; // transient loss of audio focus case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT: if (!mPlayback && mMediaPlayer != null && mMediaPlayer.isPlaying()) { finishPlayback(); } else if (mPlayback && mMediaPlayer != null && mMediaPlayer.isPlaying()) { mMediaPlayer.pause(); } break; // temporary external request of audio focus case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK: if (mMediaPlayer != null && mMediaPlayer.isPlaying()) { mMediaPlayer.setVolume(0.1f, 0.1f); } break; } } @Override public void onCompletion(MediaPlayer mp) { Log.v(LOG_TAG, "Resuming playback after completion / signal loss"); mMediaPlayer.reset(); initializeMediaPlayer(); } @Override public void onPrepared(MediaPlayer mp) { if (mPlayerInstanceCounter == 1) { Log.v(LOG_TAG, "+++ Preparation finished. Starting playback. Player instance count: " + mPlayerInstanceCounter + " +++"); mp.start(); } else { Log.v(LOG_TAG, "Stopping player service and re-initializing media player. Player instance count: " + mPlayerInstanceCounter); stopSelf(); mPlayerInstanceCounter = mPlayerInstanceCounter - 2; initializeMediaPlayer(); } } @Override public boolean onError(MediaPlayer mp, int what, int extra) { switch (what) { case MediaPlayer.MEDIA_ERROR_UNKNOWN: Log.e(LOG_TAG, "Unknown media playback error"); break; case MediaPlayer.MEDIA_ERROR_SERVER_DIED: Log.e(LOG_TAG, "Connection to server lost"); break; default: Log.e(LOG_TAG, "Generic audio playback error"); break; } switch (extra) { case MediaPlayer.MEDIA_ERROR_IO: Log.e(LOG_TAG, "IO media error."); break; case MediaPlayer.MEDIA_ERROR_MALFORMED: Log.e(LOG_TAG, "Malformed media."); break; case MediaPlayer.MEDIA_ERROR_UNSUPPORTED: Log.e(LOG_TAG, "Unsupported content type"); break; case MediaPlayer.MEDIA_ERROR_TIMED_OUT: Log.e(LOG_TAG, "Media timeout"); break; default: Log.e(LOG_TAG, "Other case of media playback error"); break; } mp.reset(); return true; } @Override public boolean onInfo(MediaPlayer mp, int what, int extra) { switch (what){ case MediaPlayer.MEDIA_INFO_UNKNOWN: Log.i(LOG_TAG, "Unknown media info"); break; case MediaPlayer.MEDIA_INFO_BUFFERING_START: Log.i(LOG_TAG, "Buffering started"); break; case MediaPlayer.MEDIA_INFO_BUFFERING_END: Log.i(LOG_TAG, "Buffering finished"); break; case MediaPlayer.MEDIA_INFO_METADATA_UPDATE: Log.i(LOG_TAG, "New metadata available"); break; default: Log.i(LOG_TAG, "other case of media info"); break; } return true; } @Override public void onDestroy() { super.onDestroy(); // save state mPlayback = false; savePlaybackState(); // unregister receivers this.unregisterReceiver(mHeadphoneUnplugReceiver); // retrieve notification system service and cancel notification NotificationManager notificationManager = (NotificationManager) getApplication().getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.cancel(PLAYER_SERVICE_NOTIFICATION_ID); } /* Method to start the player */ public void startActionPlay(Context context, String streamUri, String stationName) { mStreamUri = streamUri; Log.v(LOG_TAG, "starting playback service: " + mStreamUri); // start player service using intent Intent intent = new Intent(context, PlayerService.class); intent.setAction(ACTION_PLAY); intent.putExtra(EXTRA_STREAM_URI, mStreamUri); context.startService(intent); // put up notification NotificationHelper notificationHelper = new NotificationHelper(context); notificationHelper.setStationName(stationName); notificationHelper.createNotification(); } /* Method to stop the player */ public void startActionStop(Context context) { Log.v(LOG_TAG, "stopping playback service:"); // stop player service using intent Intent intent = new Intent(context, PlayerService.class); intent.setAction(ACTION_STOP); context.startService(intent); } /* Set up the media player */ private void initializeMediaPlayer() { mMediaPlayer = new MediaPlayer(); mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); mMediaPlayer.setOnPreparedListener(this); mMediaPlayer.setOnErrorListener(this); mMediaPlayer.setOnInfoListener(this); mMediaPlayer.setOnBufferingUpdateListener(new MediaPlayer.OnBufferingUpdateListener() { @Override public void onBufferingUpdate(MediaPlayer mp, int percent) { Log.v(LOG_TAG, "Buffering: " + percent); } }); try { mMediaPlayer.setDataSource(mStreamUri); mMediaPlayer.prepareAsync(); mPlayerInstanceCounter++; Log.v(LOG_TAG, "setting: " + mStreamUri); } catch (IllegalArgumentException | IllegalStateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } /* Release the media player */ private void releaseMediaPlayer() { if (mMediaPlayer != null) { if (mMediaPlayer.isPlaying()) { mMediaPlayer.stop(); } mMediaPlayer.reset(); mMediaPlayer.release(); mMediaPlayer = null; } } /* Prepare playback */ private void preparePlayback() { // stop running player if (mMediaPlayer != null && mMediaPlayer.isPlaying()) { releaseMediaPlayer(); } // request focus and initialize media player if (mStreamUri != null && requestFocus()) { initializeMediaPlayer(); } // save state mPlayback = true; savePlaybackState(); // send local broadcast (needed by MainActivityFragment) Intent i = new Intent(); i.setAction(ACTION_PLAYBACK_STARTED); LocalBroadcastManager.getInstance(this.getApplication()).sendBroadcast(i); } /* Finish playback */ private void finishPlayback() { // release player releaseMediaPlayer(); // save state mPlayback = false; savePlaybackState(); // send local broadcast (needed by PlayerActivityFragment and MainActivityFragment) Intent i = new Intent(); i.setAction(ACTION_PLAYBACK_STOPPED); LocalBroadcastManager.getInstance(this.getApplication()).sendBroadcast(i); // retrieve notification system service and cancel notification NotificationManager notificationManager = (NotificationManager) getApplication().getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.cancel(PLAYER_SERVICE_NOTIFICATION_ID); } /* Request audio manager focus */ private boolean requestFocus() { int result = mAudioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN); return result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED; } /* Saves state of playback */ private void savePlaybackState () { SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getApplication()); SharedPreferences.Editor editor = settings.edit(); editor.putBoolean(PLAYBACK, mPlayback); editor.apply(); } /** * Inner class: Receiver for headphone unplug-signal */ public class HeadphoneUnplugReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if (mPlayback && AudioManager.ACTION_AUDIO_BECOMING_NOISY.equals(intent.getAction())) { Log.v(LOG_TAG, "Headphones unplugged. Stopping playback."); // stop playback finishPlayback(); // notify user Toast.makeText(context, R.string.toastalert_headphones_unplugged, Toast.LENGTH_LONG).show(); } } } /** * End of inner class */ }
oh boy. last commit was a stinker. caused all kinds of problems. rolling back a bit.
app/src/main/java/org/y20k/transistor/PlayerService.java
oh boy. last commit was a stinker. caused all kinds of problems. rolling back a bit.
Java
mit
f90b451887dac2bf3cad2c80764d7cbcb0767b08
0
AllTheTrees/CTCTrees
TreeLocatorFrame.java
import javax.swing.*; import java.awt.*; import java.io.IOException; public class TreeLocatorFrame extends JFrame { private TreeLocator tl; public TreeLocatorFrame() { } public void init() { buildUI(); } public void buildUI() { try { tl = new TreeLocator(1200, 800); } catch (IOException e) { //swallow } this.setContentPane(tl); this.pack(); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { TreeLocatorFrame tla = new TreeLocatorFrame(); tla.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); tla.setLayout(new BorderLayout()); tla.setResizable(false); tla.buildUI(); tla.setVisible(true); } }); } }
Delete TreeLocatorFrame.java
TreeLocatorFrame.java
Delete TreeLocatorFrame.java
Java
epl-1.0
e4c16348f2c8254714954d81992b767b9b7f75ff
0
spring-projects/sts4,spring-projects/sts4,spring-projects/sts4,spring-projects/sts4,spring-projects/sts4,spring-projects/sts4
/******************************************************************************* * Copyright (c) 2016 Pivotal, Inc. * All rights reserved. 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 * * Contributors: * Pivotal, Inc. - initial API and implementation *******************************************************************************/ package org.springframework.ide.vscode.concourse; import static org.junit.Assert.assertEquals; import static org.springframework.ide.vscode.languageserver.testharness.TestAsserts.assertContains; import java.io.InputStream; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import org.eclipse.lsp4j.Diagnostic; import org.eclipse.lsp4j.DiagnosticSeverity; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.springframework.ide.vscode.commons.languageserver.LanguageIds; import org.springframework.ide.vscode.commons.util.IOUtil; import org.springframework.ide.vscode.languageserver.testharness.Editor; import org.springframework.ide.vscode.languageserver.testharness.LanguageServerHarness; public class ConcourseEditorTest { private static final String CURSOR = "<*>"; LanguageServerHarness harness; @Before public void setup() throws Exception { harness = new LanguageServerHarness(() -> { return new ConcourseLanguageServer() .setMaxCompletions(100); }, LanguageIds.CONCOURSE_PIPELINE ); harness.intialize(null); } @Test public void testReconcileCatchesParseError() throws Exception { Editor editor = harness.newEditor( "somemap: val\n"+ "- sequence" ); editor.assertProblems( "-|expected <block end>" ); } @Test public void reconcileRunsOnDocumentOpenAndChange() throws Exception { Editor editor = harness.newEditor( "somemap: val\n"+ "- sequence" ); editor.assertProblems( "-|expected <block end>" ); editor.setText( "- sequence\n" + "zomemap: val" ); editor.assertProblems( "z|expected <block end>" ); } @Test public void reconcileMisSpelledPropertyNames() throws Exception { Editor editor; editor = harness.newEditor( "resorces:\n" + "- name: git\n" + " type: git\n" ); editor.assertProblems("resorces|Unknown property"); } @Test public void reconcileAcceptsSensiblePipelineFile() throws Exception { Editor editor; editor = harness.newEditor( getClasspathResourceText("workspace/pipeline.yml") ); editor.assertProblems(/*NONE*/);; } private String getClasspathResourceText(String resourceName) throws Exception { InputStream stream = ConcourseEditorTest.class.getClassLoader().getResourceAsStream(resourceName); return IOUtil.toString(stream); } @Test public void reconcileStructuralProblems() throws Exception { Editor editor; //resources should be a sequence not a map, even if there's only one entry editor = harness.newEditor( "resources:\n" + " name: git\n" + " type: git\n" ); editor.assertProblems( "name: git\n type: git|Expecting a 'Sequence' but found a 'Map'" ); editor = harness.newEditor( "jobs:\n" + "- name: a-job\n" + " plan:\n" + " - task: a-task\n" + " tags: a-single-string\n" ); editor.assertProblems( "-^ task|One of [config, file] is required", "a-single-string|Expecting a 'Sequence'" ); editor = harness.newEditor( "jobs:\n" + "- name: a-job\n" + " plan:\n" + " - try:\n" + " put: a-resource\n" ); editor.assertProblems( "a-resource|does not exist" ); //TODO: Add more test cases for structural problem? } @Test public void primaryStepCompletions() throws Exception { assertContextualCompletions( // Context: "jobs:\n" + "- name: some-job\n" + " plan:\n" + " - <*>" , // ============== "<*>" , // => "aggregate:\n" + " - <*>" , // ============== "do:\n" + " - <*>" , // ============== "get: <*>" , // ============== "put: <*>" , // ============== "task: <*>" , // ============== "try:\n" + " <*>" ); } @Test public void PT_136196057_do_step_completion_indentation() throws Exception { assertCompletions( "jobs:\n" + "- name:\n"+ " plan:\n" + " - do<*>" , // => "jobs:\n" + "- name:\n"+ " plan:\n" + " - do:\n" + " - <*>" ); } @Test public void primaryStepHovers() throws Exception { Editor editor = harness.newEditor( "jobs:\n" + "- name: some-job\n" + " plan:\n" + " - get: something\n" + " - put: something\n" + " - do: []\n" + " - aggregate:\n" + " - task: perform-something\n" + " - try:\n" + " put: test-logs\n" ); editor.assertHoverContains("get", "Fetches a resource"); editor.assertHoverContains("put", "Pushes to the given [Resource]"); editor.assertHoverContains("aggregate", "Performs the given steps in parallel"); editor.assertHoverContains("task", "Executes a [Task]"); editor.assertHoverContains("do", "performs the given steps serially"); editor.assertHoverContains("try", "Performs the given step, swallowing any failure"); } @Test public void putStepHovers() throws Exception { Editor editor = harness.newEditor( "jobs:\n" + "- name: some-job\n" + " plan:\n" + " - put: something\n" + " resource: something\n" + " params:\n" + " some_param: some_value\n" + " get_params:\n" + " skip_download: true\n" ); editor.assertHoverContains("resource", "The resource to update"); editor.assertHoverContains("params", "A map of arbitrary configuration"); editor.assertHoverContains("get_params", "A map of arbitrary configuration to forward to the resource that will be utilized during the implicit `get` step"); } @Test public void getStepHovers() throws Exception { Editor editor = harness.newEditor( "jobs:\n" + "- name: some-job\n" + " plan:\n" + " - get: something\n" + " resource: something\n" + " version: latest\n" + " passed: [other-job]\n" + " params:\n" + " some_param: some_value\n" + " trigger: true\n" + " attempts: 10\n" + " on_failure:\n" + " - bogus: bad\n" + " on_success:\n" + " - bogus: bad\n" + " ensure:\n" + " task: cleanups\n" ); editor.assertHoverContains("resource", "The resource to fetch"); editor.assertHoverContains("version", "The version of the resource to fetch"); editor.assertHoverContains("params", "A map of arbitrary configuration"); editor.assertHoverContains("trigger", "Set to `true` to auto-trigger"); editor.assertHoverContains("attempts", "Any step can set the number of times it should be attempted"); editor.assertHoverContains("on_failure", "Any step can have `on_failure` tacked onto it"); editor.assertHoverContains("on_success", "Any step can have `on_success` tacked onto it"); editor.assertHoverContains("ensure", "a second step to execute regardless of the result of the parent step"); } @Test public void groupHovers() throws Exception { Editor editor = harness.newEditor( "groups:\n" + "- name: some-group\n" + " resources: []\n" + " jobs: []\n" ); editor.assertHoverContains("name", "The name of the group"); editor.assertHoverContains("resources", "A list of resources that should appear in this group"); editor.assertHoverContains("jobs", " A list of jobs that should appear in this group"); } @Test public void taskStepHovers() throws Exception { Editor editor = harness.newEditor( "jobs:\n" + "- name: some-job\n" + " plan:\n" + " - task: do-something\n" + " file: some-file.yml\n" + " privileged: true\n" + " image: some-image\n" + " params:\n" + " map: of-stuff\n" + " input_mapping:\n" + " map: of-stuff\n" + " output_mapping:\n" + " map: of-stuff\n" + " config: some-config\n" + " tags: [a, b, c]\n"+ " attempts: 10\n" + " timeout: 1h30m\n" + " ensure:\n" + " bogus: bad\n" + " on_failure:\n" + " bogus: bad\n" + " on_success:\n" + " bogus: bad\n" ); editor.assertHoverContains("file", "`file` points at a `.yml` file containing the task config"); editor.assertHoverContains("privileged", "If set to `true`, the task will run with full capabilities"); editor.assertHoverContains("image", "Names an artifact source within the plan"); editor.assertHoverContains("params", "A map of task parameters to set, overriding those configured in `config` or `file`"); editor.assertHoverContains("input_mapping", "A map from task input names to concrete names in the build plan"); editor.assertHoverContains("output_mapping", "A map from task output names to concrete names"); editor.assertHoverContains("config", "Use `config` to inline the task config"); editor.assertHoverContains("tags", "Any step can be directed at a pool of workers"); editor.assertHoverContains("timeout", "amount of time to limit the step's execution"); } @Test public void aggregateStepHovers() throws Exception { Editor editor; editor = harness.newEditor( "jobs:\n" + "- name: some-job\n" + " plan:\n" + " - aggregate:\n" + " - get: some-resource\n" ); editor.assertHoverContains("aggregate", "Performs the given steps in parallel"); } @Test public void reconcileSimpleTypes() throws Exception { Editor editor; //check for 'format' errors: editor = harness.newEditor( "jobs:\n" + "- name: foo\n" + " serial: boohoo\n" + " max_in_flight: -1\n" + " plan:\n" + " - get: git\n" + " trigger: yohoho\n" + " attempts: 0\n" + " timeout: 1h:30m\n" ); editor.assertProblems( "boohoo|boolean", "-1|must be positive", "git|resource does not exist", "yohoho|boolean", "0|must be at least 1", "1h:30m|Duration" ); //check that correct values are indeed accepted editor = harness.newEditor( "resources:\n" + "- name: git\n" + " type: git\n" + "jobs:\n" + "- name: foo\n" + " serial: true\n" + " max_in_flight: 2\n" + " plan:\n" + " - get: git\n" + " trigger: true" ); editor.assertProblems(/*none*/); } @Test public void noListIndent() throws Exception { Editor editor; editor = harness.newEditor("jo<*>"); editor.assertCompletions( "jobs:\n"+ "- <*>" ); } @Test public void toplevelCompletions() throws Exception { Editor editor; editor = harness.newEditor(CURSOR); editor.assertCompletions( "groups:\n" + "- <*>" , // -------------- "jobs:\n" + "- <*>" , // --------------- "resource_types:\n" + "- <*>" , // --------------- "resources:\n"+ "- <*>" ); editor = harness.newEditor("rety<*>"); editor.assertCompletions( "resource_types:\n" + "- <*>" ); } @Test public void valueCompletions() throws Exception { String [] builtInResourceTypes = { "git", "hg", "time", "s3", "archive", "semver", "github-release", "docker-image", "tracker", "pool", "cf", "bosh-io-release", "bosh-io-stemcell", "bosh-deployment", "vagrant-cloud" }; Arrays.sort(builtInResourceTypes); String[] expectedCompletions = new String[builtInResourceTypes.length]; for (int i = 0; i < expectedCompletions.length; i++) { expectedCompletions[i] = "resources:\n" + "- type: "+builtInResourceTypes[i]+"<*>"; } assertCompletions( "resources:\n" + "- type: <*>" , //=> expectedCompletions ); assertCompletions( "jobs:\n" + "- name: foo\n" + " serial: <*>" , // => "jobs:\n" + "- name: foo\n" + " serial: false<*>" , // -- "jobs:\n" + "- name: foo\n" + " serial: true<*>" ); } @Test public void topLevelHoverInfos() throws Exception { Editor editor = harness.newEditor( "resource_types:\n" + "- name: s3-multi\n" + " type: docker-image\n" + " source:\n" + " repository: kdvolder/s3-resource-simple\n" + "resources:\n" + "- name: docker-git\n" + " type: git\n" + " source:\n" + " uri: [email protected]:spring-projects/sts4.git\n" + " branch: {{branch}}\n" + " username: kdvolder\n" + " private_key: {{rsa_id}}\n" + " paths:\n" + " - concourse/docker\n" + "jobs:\n" + "- name: build-docker-image\n" + " serial: true\n" + " plan:\n" + " - get: docker-git\n" + " trigger: true\n" + " - put: docker-image\n" + " params:\n" + " build: docker-git/concourse/docker\n" + " get_params: \n" + " skip_download: true\n" + "groups:\n" + "- name: a-groups\n" ); editor.assertHoverContains("resource_types", "each pipeline can configure its own custom types by specifying `resource_types` at the top level."); editor.assertHoverContains("resources", "A resource is any entity that can be checked for new versions"); editor.assertHoverContains("jobs", "At a high level, a job describes some actions to perform"); editor.assertHoverContains("groups", "A pipeline may optionally contain a section called `groups`"); } @Test public void reconcileResourceReferences() throws Exception { Editor editor = harness.newEditor( "resources:\n" + "- name: sts4\n" + " type: git\n" + " source:\n" + " uri: https://github.com/kdvolder/somestuff\n" + " branch: master\n" + "jobs:\n" + "- name: job1\n" + " plan:\n" + " - get: sts4\n" + " - get: bogus-get\n" + " - task: do-stuff\n" + " image: bogus-image\n" + " file: some-file.yml\n" + " input_mapping:\n" + " task-input: bogus-input\n" + " repo: sts4\n" + " - put: bogus-put\n" ); editor.assertProblems( "bogus-get|resource does not exist", "bogus-image|resource does not exist", "bogus-input|resource does not exist", "bogus-put|resource does not exist" ); editor.assertProblems( "bogus-get|[sts4]", "bogus-image|[sts4]", "bogus-input|[sts4]", "bogus-put|[sts4]" ); } @Test public void reconcileDuplicateResourceNames() throws Exception { Editor editor = harness.newEditor( "resources:\n" + "- name: sts4\n" + " type: git\n" + "- name: utils\n" + " type: git\n" + "- name: sts4\n" + " type: git\n" ); editor.assertProblems( "sts4|Duplicate resource name", "sts4|Duplicate resource name" ); } @Test public void reconcileDuplicateResourceTypeNames() throws Exception { Editor editor = harness.newEditor( "resource_types:\n" + "- name: slack-notification\n" + " type: docker_image\n" + "- name: slack-notification\n" + " type: docker_image" ); editor.assertProblems( "slack-notification|Duplicate resource-type name", "slack-notification|Duplicate resource-type name" ); } @Test public void violatedPropertyConstraintsAreWarnings() throws Exception { Editor editor; editor = harness.newEditor( "jobs:\n" + "- name: blah" ); Diagnostic problem = editor.assertProblems("-^ name: blah|'plan' is required").get(0); assertEquals(DiagnosticSeverity.Warning, problem.getSeverity()); editor = harness.newEditor( "jobs:\n" + "- name: do-stuff\n" + " plan:\n" + " - task: foo" ); problem = editor.assertProblems("-^ task: foo|One of [config, file] is required").get(0); assertEquals(DiagnosticSeverity.Warning, problem.getSeverity()); editor = harness.newEditor( "jobs:\n" + "- name: do-stuff\n" + " plan:\n" + " - task: foo\n" + " config: {}\n" + " file: path/to/file" ); { List<Diagnostic> problems = editor.assertProblems( "config|Only one of [config, file]", "config|[platform, run] are required", "config|One of [image_resource, image]", "file|Only one of [config, file]" ); //All of the problems in this example are property contraint violations! So all should be warnings. for (Diagnostic diagnostic : problems) { assertEquals(DiagnosticSeverity.Warning, diagnostic.getSeverity()); } } } @Test public void underlineParentPropertyForMissingNode() throws Exception { //See: https://www.pivotaltracker.com/story/show/140709005 Editor editor = harness.newEditor( "jobs:\n" + "- name: hello-world\n" + " plan:\n" + " - task: say-hello\n" + " config:\n" + " image_resource:\n" + " type: docker-image\n" + " source: {repository: ubuntu}\n" + " run:\n" + " path: echo\n" + " args: [\"Hello, world!\"]" ); editor.assertProblems( "config|'platform' is required" ); } @Test public void reconcileDuplicateJobNames() throws Exception { Editor editor = harness.newEditor( "jobs:\n" + "- name: job-1\n" + "- name: utils\n" + "- name: job-1\n" ); editor.assertProblems( "-^ name: job-1|'plan' is required", "job-1|Duplicate job name", "-^ name: utils|'plan' is required", "-^ name: job-1|'plan' is required", "job-1|Duplicate job name" ); } @Test public void completionsResourceReferences() throws Exception { assertContextualCompletions( "resources:\n" + "- name: sts4\n" + "- name: repo-a\n" + "- name: repo-b\n" + "jobs:\n" + "- name: job1\n" + " plan:\n" + " - get: <*>\n" , //////////////////// "<*>" , // => "repo-a<*>", "repo-b<*>", "sts4<*>" ); assertContextualCompletions( "resources:\n" + "- name: sts4\n" + "- name: repo-a\n" + "- name: repo-b\n" + "jobs:\n" + "- name: job1\n" + " plan:\n" + " - put: <*>\n" , //////////////////// "r<*>" , // => "repo-a<*>", "repo-b<*>" ); } @Test public void reconcileDuplicateKeys() throws Exception { Editor editor = harness.newEditor( "resources:\n" + "- name: my-repo\n" + " type: git\n" + " source:\n" + " branch: master\n" + " uri: https://github.com/kdvolder/my-repo\n" + "resources:\n" + "- name: your-repo\n" + " type: git\n" + " type: git\n" + " source:\n" + " branch: master\n" + " uri: https://github.com/kdvolder/forked-repo\n" ); editor.assertProblems( "resources|Duplicate key", "resources|Duplicate key", "type|Duplicate key", "type|Duplicate key" ); } @Test public void reconcileJobNames() throws Exception { Editor editor = harness.newEditor( "resources:\n" + "- name: git-repo\n" + " type: git\n" + "- name: build-artefact\n" + " type: git\n" + "jobs:\n" + "- name: build\n" + " plan:\n" + " - get: git-repo\n" + " - task: run-build\n" + " file: some-task.yml\n" + " - put: build-artefact\n" + "- name: test\n" + " plan:\n" + " - get: git-repo\n" + " passed:\n" + " - not-a-job\n" + " - build\n" ); editor.assertProblems("not-a-job|does not exist"); } @Test public void reconcileGroups() throws Exception { Editor editor = harness.newEditor( "resources:\n" + "- name: git-repo\n" + " type: git\n" + "- name: build-artefact\n" + " type: git\n" + "jobs:\n" + "- name: build\n" + " plan:\n" + " - get: git-repo\n" + " - task: run-build\n" + " file: tasks/some-task.yml\n" + " - put: build-artefact\n" + "- name: test\n" + " plan:\n" + " - get: git-repo\n" + "groups:\n" + "- name: some-group\n" + " jobs: [build, test, bogus-job]\n" + " resources: [git-repo, build-artefact, not-a-resource]" ); editor.assertProblems( "bogus-job|does not exist", "not-a-resource|does not exist" ); } @Test public void timeResourceCompletions() throws Exception { assertContextualCompletions( "resources:\n" + "- name: every5minutes\n" + " type: time\n" + " source:\n" + " location: <*>" , // ====================== "Van<*>" , // => "America/Vancouver<*>", "Asia/Vientiane<*>", "Europe/Vatican<*>" ); assertContextualCompletions( "resources:\n" + "- name: every5minutes\n" + " type: time\n" + " source:\n" + " <*>" , // ====================== "<*>" , // => "days:\n"+ " - <*>", "interval: <*>", "location: <*>", "start: <*>", "stop: <*>" ); assertContextualCompletions( "resources:\n" + "- name: every5minutes\n" + " type: time\n" + " source:\n" + " days:\n" + " - <*>" , // ====================== "<*>" , // => "Friday<*>", "Monday<*>", "Saturday<*>", "Sunday<*>", "Thursday<*>", "Tuesday<*>", "Wednesday<*>" ); } @Test public void timeResourceSourceReconcile() throws Exception { Editor editor; editor = harness.newEditor( "resources:\n" + "- name: every5minutes\n" + " type: time\n" + " source:\n" + " location: PST8PDT\n" + " start: 7AM\n" + " stop: 8AM\n" + " interval: 5m\n" + " days:\n" + " - Thursday\n" ); editor.assertProblems(/*NONE*/); editor = harness.newEditor( "resources:\n" + "- name: every5minutes\n" + " type: time\n" + " source:\n" + " location: some-location\n" + " start: the-start-time\n" + " stop: the-stop-time\n" + " interval: the-interval\n" + " days:\n" + " - Monday\n" + " - Someday\n" ); editor.assertProblems( "some-location|Unknown 'Location'", "the-start-time|not a valid 'Time'", "the-stop-time|not a valid 'Time'", "the-interval|not a valid 'Duration'", "Someday|unknown 'Day'" ); } @Test public void timeResourceSourceHovers() throws Exception { Editor editor = harness.newEditor( "resources:\n" + "- name: timed-trigger\n" + " type: time\n" + " source:\n" + " interval: 5m\n" + " location: UTC\n" + " start: 8:00PM\n" + " stop: 9:00PM\n" + " days: [Monday, Wednesday, Friday]" ); editor.assertHoverContains("interval", "interval on which to report new versions"); editor.assertHoverContains("location", "*Optional. Default `UTC`"); editor.assertHoverContains("start", "The supported time formats are"); editor.assertHoverContains("stop", "The supported time formats are"); editor.assertHoverContains("days", "Run only on these day(s)"); } @Test public void gitResourceSourceReconcile() throws Exception { Editor editor = harness.newEditor( "resources:\n" + "- name: sts4-out\n" + " type: git\n" + " source:\n" + " uri: [email protected]:spring-projects/sts4.git\n" + " bogus: bad\n" + " branch: {{branch}}\n" + " private_key: {{rsa_id}}\n" + " username: jeffy\n" + " password: {{git_passwords}}\n" + " paths: not-a-list\n" + " ignore_paths: also-not-a-list\n" + " skip_ssl_verification: skip-it\n" + " tag_filter: RELEASE_*\n" + " git_config:\n" + " - name: good\n" + " val: bad\n" + " disable_ci_skip: no_ci_skip\n" + " commit_verification_keys: not-a-list-of-keys\n" + " commit_verification_key_ids: not-a-list-of-ids\n" + " gpg_keyserver: hkp://somekeyserver.net" ); editor.assertProblems( "bogus|Unknown property", "not-a-list|Expecting a 'Sequence'", "also-not-a-list|Expecting a 'Sequence'", "skip-it|'boolean'", "val|Unknown property", "no_ci_skip|'boolean'", "not-a-list-of-keys|Expecting a 'Sequence'", "not-a-list-of-ids|Expecting a 'Sequence'" ); } @Test public void gitResourceSourceCompletions() throws Exception { assertContextualCompletions( "resources:\n" + "- name: the-repo\n" + " type: git\n" + " source:\n" + " <*>" , //================ "<*>" , // ==> "branch: <*>" , "commit_verification_key_ids:\n" + " - <*>" , "commit_verification_keys:\n" + " - <*>" , "disable_ci_skip: <*>" , "git_config:\n" + " - <*>" , "gpg_keyserver: <*>" , "ignore_paths:\n" + " - <*>" , "password: <*>" , "paths:\n" + " - <*>" , "private_key: <*>" , "skip_ssl_verification: <*>" , "tag_filter: <*>" , "uri: <*>" , "username: <*>" ); assertContextualCompletions( "resources:\n" + "- name: the-repo\n" + " type: git\n" + " source:\n" + " git_config:\n" + " - <*>" , // ============= "<*>" , // ==> "name: <*>", "value: <*>" ); } @Test public void gitResourceSourceHovers() throws Exception { Editor editor = harness.newEditor( "resources:\n" + "- name: sts4-out\n" + " type: git\n" + " source:\n" + " uri: [email protected]:spring-projects/sts4.git\n" + " bogus: bad\n" + " branch: {{branch}}\n" + " private_key: {{rsa_id}}\n" + " username: jeffy\n" + " password: {{git_passwords}}\n" + " paths: not-a-list\n" + " ignore_paths: also-not-a-list\n" + " skip_ssl_verification: skip-it\n" + " tag_filter: RELEASE_*\n" + " git_config:\n" + " - name: good\n" + " val: bad\n" + " disable_ci_skip: no_ci_skip\n" + " commit_verification_keys: not-a-list-of-keys\n" + " commit_verification_key_ids: not-a-list-of-ids\n" + " gpg_keyserver: hkp://somekeyserver.net" ); editor.assertHoverContains("uri", "*Required.* The location of the repository."); editor.assertHoverContains("branch", "The branch to track"); editor.assertHoverContains("private_key", "Private key to use when pulling/pushing"); editor.assertHoverContains("username", "Username for HTTP(S) auth"); editor.assertHoverContains("password", "Password for HTTP(S) auth"); editor.assertHoverContains("paths", "a list of glob patterns"); editor.assertHoverContains("ignore_paths", "The inverse of `paths`"); editor.assertHoverContains("skip_ssl_verification", "Skips git ssl verification"); editor.assertHoverContains("tag_filter", "the resource will only detect commits"); editor.assertHoverContains("git_config", "configure git global options"); editor.assertHoverContains("disable_ci_skip", "Allows for commits that have been labeled with `[ci skip]`"); editor.assertHoverContains("commit_verification_keys", "Array of GPG public keys"); editor.assertHoverContains("commit_verification_key_ids", "Array of GPG public key ids"); } @Test public void gitResourceGetParamsCompletions() throws Exception { String context = "resources:\n" + "- name: my-git\n" + " type: git\n" + "jobs:\n" + "- name: do-stuff\n" + " plan:\n" + " - get: my-git\n" + " params:\n" + " <*>"; assertContextualCompletions(context, "<*>" , // ===> "depth: <*>" , "disable_git_lfs: <*>" , "submodules:\n"+ " <*>" ); assertContextualCompletions(context, "disable_git_lfs: <*>" , // ===> "disable_git_lfs: false<*>", "disable_git_lfs: true<*>" ); assertContextualCompletions(context, "submodules: <*>" , // ===> "submodules: all<*>", "submodules: none<*>" ); } @Test public void gitResourceGetParamsHovers() throws Exception { Editor editor = harness.newEditor( "resources:\n" + "- name: my-git\n" + " type: git\n" + "jobs:\n" + "- name: do-stuff\n" + " plan:\n" + " - get: my-git\n" + " params:\n" + " depth: -1\n" + " disable_git_lfs: not-bool\n" + " submodules: none" ); editor.assertHoverContains("depth", "using the `--depth` option"); editor.assertHoverContains("submodules", "If `none`, submodules will not be fetched"); editor.assertHoverContains("disable_git_lfs", "will not fetch Git LFS files"); } @Test public void gitResourceGetParamsReconcile() throws Exception { Editor editor = harness.newEditor( "resources:\n" + "- name: my-git\n" + " type: git\n" + "jobs:\n" + "- name: do-stuff\n" + " plan:\n" + " - get: my-git\n" + " params:\n" + " depth: -1\n" + " disable_git_lfs: not-bool\n" ); editor.assertProblems( "-1|must be positive", "not-bool|'boolean'" ); } @Test public void gitResourcePutParamsCompletions() throws Exception { String context = "resources:\n" + "- name: my-git\n" + " type: git\n" + "jobs:\n" + "- name: do-stuff\n" + " plan:\n" + " - put: my-git\n" + " params:\n" + " <*>"; assertContextualCompletions(context, "<*>" , // ===> "annotate: <*>" , "force: <*>" , "only_tag: <*>" , "rebase: <*>" , "repository: <*>" , "tag: <*>" , "tag_prefix: <*>" ); assertContextualCompletions(context, "rebase: <*>" , // ===> "rebase: false<*>", "rebase: true<*>" ); assertContextualCompletions(context, "only_tag: <*>" , // ===> "only_tag: false<*>", "only_tag: true<*>" ); assertContextualCompletions(context, "force: <*>" , // ===> "force: false<*>", "force: true<*>" ); } @Test public void gitResourcePutParamsReconcile() throws Exception { Editor editor; editor = harness.newEditor( "resources:\n" + "- name: my-git\n" + " type: git\n" + "jobs:\n" + "- name: do-stuff\n" + " plan:\n" + " - put: my-git\n" + " params: {}\n" ); editor.assertProblems("params|'repository' is required"); editor = harness.newEditor( "resources:\n" + "- name: my-git\n" + " type: git\n" + "jobs:\n" + "- name: do-stuff\n" + " plan:\n" + " - put: my-git\n" + " params:\n" + " repository: some-other-repo\n" + " rebase: do-rebase\n" + " only_tag: do-tag\n" + " force: force-it\n" ); editor.assertProblems( "do-rebase|'boolean'", "do-tag|'boolean'", "force-it|'boolean'" ); } @Test public void gitResourcePutParamsHovers() throws Exception { Editor editor = harness.newEditor( "resources:\n" + "- name: my-git\n" + " type: git\n" + "jobs:\n" + "- name: do-stuff\n" + " plan:\n" + " - put: my-git\n" + " params:\n" + " repository: some-other-repo\n" + " rebase: do-rebase\n" + " tag: the-tag-file\n" + " only_tag: do-tag\n" + " tag_prefix: RELEASE\n" + " force: force-it\n" + " annotate: release-annotion\n" ); editor.assertHoverContains("repository", "The path of the repository"); editor.assertHoverContains("rebase", "attempt rebasing"); editor.assertHoverContains("tag", "HEAD will be tagged"); editor.assertHoverContains("only_tag", "push only the tags"); editor.assertHoverContains("tag_prefix", "prepended with this string"); editor.assertHoverContains("force", "pushed regardless of the upstream state"); editor.assertHoverContains("annotate", "path to a file containing the annotation message"); } @Test public void gitResourcePut_get_params_Hovers() throws Exception { Editor editor = harness.newEditor( "resources:\n" + "- name: my-git\n" + " type: git\n" + "jobs:\n" + "- name: do-stuff\n" + " plan:\n" + " - put: my-git\n" + " get_params:\n" + " depth: 1\n" + " submodules: none\n" + " disable_git_lfs: true\n" ); editor.assertHoverContains("depth", "using the `--depth` option"); editor.assertHoverContains("submodules", "If `none`, submodules will not be fetched"); editor.assertHoverContains("disable_git_lfs", "will not fetch Git LFS files"); } @Test public void contentAssistJobNames() throws Exception { assertContextualCompletions( "resources:\n" + "- name: git-repo\n" + "- name: build-artefact\n" + "jobs:\n" + "- name: build\n" + " plan:\n" + " - get: git-repo\n" + " - task: run-build\n" + " - put: build-artefact\n" + "- name: test\n" + " plan:\n" + " - get: git-repo\n" + " passed:\n" + " - <*>\n" , /////////////////////////// "<*>" , // => "build<*>", "test<*>" ); } @Test public void resourceTypeAttributeHovers() throws Exception { Editor editor = harness.newEditor( "resource_types:\n" + "- name: s3-multi\n" + " type: docker-image\n" + " source:\n" + " repository: kdvolder/s3-resource-simple\n" ); editor.assertHoverContains("name", "This name will be referenced by `resources` defined within the same pipeline"); editor.assertHoverContains("type", 2, "used to provide the resource type's container image"); editor.assertHoverContains("source", 2, "The location of the resource type's resource"); } @Test public void resourceAttributeHovers() throws Exception { Editor editor = harness.newEditor( "resources:\n" + "- name: sts4\n" + " type: git\n" + " check_every: 5m\n" + " source:\n" + " repository: https://github.com/spring-projects/sts4\n" ); editor.assertHoverContains("name", "The name of the resource"); editor.assertHoverContains("type", "The type of the resource. Each worker advertises"); editor.assertHoverContains("source", 2, "The location of the resource"); editor.assertHoverContains("check_every", "The interval on which to check for new versions"); } @Test public void requiredPropertiesReconcile() throws Exception { Editor editor; //addProp(resource, "name", resourceNameDef).isRequired(true); editor = harness.newEditor( "resources:\n" + "- type: git" ); editor.assertProblems("-^ type: git|'name' is required"); //addProp(resource, "type", t_resource_type_name).isRequired(true); editor = harness.newEditor( "resources:\n" + "- name: foo" ); editor.assertProblems("-^ name: foo|'type' is required"); //Both name and type missing: editor = harness.newEditor( "resources:\n" + "- source: {}" ); editor.assertProblems("-^ source:|[name, type] are required"); //addProp(job, "name", jobNameDef).isRequired(true); editor = harness.newEditor( "jobs:\n" + "- name: foo" ); editor.assertProblems("-^ name: foo|'plan' is required"); //addProp(job, "plan", f.yseq(step)).isRequired(true); editor = harness.newEditor( "jobs:\n" + "- plan: []" ); editor.assertProblems("-^ plan: []|'name' is required"); //addProp(resourceType, "name", t_ne_string).isRequired(true); editor = harness.newEditor( "resource_types:\n" + "- type: docker-image" ); editor.assertProblems("-^ type: docker-image|'name' is required"); //addProp(resourceType, "type", t_image_type).isRequired(true); editor = harness.newEditor( "resource_types:\n" + "- name: foo" ); editor.assertProblems("-^ name: foo|'type' is required"); //addProp(gitSource, "uri", t_string).isRequired(true); editor = harness.newEditor( "resources:\n" + "- name: foo\n" + " type: git\n" + " source:\n" + " branch: master" ); editor.assertProblems("source|'uri' is required"); //addProp(gitSource, "branch", t_string).isRequired(true); editor = harness.newEditor( "resources:\n" + "- name: foo\n" + " type: git\n" + " source:\n" + " uri: https://yada" ); editor.assertProblems("source|'branch' is required"); //addProp(group, "name", t_ne_string).isRequired(true); editor = harness.newEditor( "groups:\n" + "- jobs: []" ); editor.assertProblems("-^ jobs: []|'name' is required"); } @Test public void dockerImageResourceSourceReconcileAndHovers() throws Exception { Editor editor; editor = harness.newEditor( "resources:\n" + "- name: my-docker-image\n" + " type: docker-image\n" + " source:\n" + " tag: latest\n" ); editor.assertProblems("source|'repository' is required"); editor = harness.newEditor( "resources:\n" + "- name: my-docker-image\n" + " type: docker-image\n" + " source:\n" + " repository: kdvolder/sts4-build-env\n" + " tag: latest\n" + " username: kdvolder\n" + " password: {{docker_password}}\n" + " aws_access_key_id: {{aws_access_key}}\n" + " aws_secret_access_key: {{aws_secret_key}}\n" + " insecure_registries: no-list\n" + " registry_mirror: https://my-docker-registry.com\n" + " ca_certs:\n" + " - domain: example.com:443\n" + " cert: |\n" + " -----BEGIN CERTIFICATE-----\n" + " ...\n" + " -----END CERTIFICATE-----\n" + " bogus_ca_certs_prop: bad\n" + " client_certs:\n" + " - domain: example.com:443\n" + " cert: |\n" + " -----BEGIN CERTIFICATE-----\n" + " ...\n" + " -----END CERTIFICATE-----\n" + " key: |\n" + " -----BEGIN RSA PRIVATE KEY-----\n" + " ...\n" + " -----END RSA PRIVATE KEY-----\n" + " bogus_client_cert_prop: bad\n" ); editor.assertProblems( "no-list|Expecting a 'Sequence'", "bogus_ca_certs_prop|Unknown property", //ca_certs "bogus_client_cert_prop|Unknown property" //client_certs ); editor.assertHoverContains("repository", "The name of the repository"); editor.assertHoverContains("tag", "The tag to track"); editor.assertHoverContains("username", "username to authenticate"); editor.assertHoverContains("password", "password to use"); editor.assertHoverContains("aws_access_key_id", "AWS access key to use"); editor.assertHoverContains("aws_secret_access_key", "AWS secret key to use"); editor.assertHoverContains("insecure_registries", "array of CIDRs"); editor.assertHoverContains("registry_mirror", "URL pointing to a docker registry"); editor.assertHoverContains("ca_certs", "Each entry specifies the x509 CA certificate for"); editor.assertHoverContains("client_certs", "Each entry specifies the x509 certificate and key"); } @Test public void dockerImageResourceGetParamsReconcileAndHovers() throws Exception { Editor editor; editor = harness.newEditor( "resources:\n" + "- name: my-docker-image\n" + " type: docker-image\n" + "jobs:\n" + "- name: a-job\n" + " plan:\n" + " - get: my-docker-image\n" + " params:\n" + " save: save-it\n" + " rootfs: tar-it\n" + " skip_download: skip-it\n" ); editor.assertProblems( "save-it|'boolean'", "tar-it|'boolean'", "skip-it|'boolean'" ); editor.assertHoverContains("save", "docker save"); editor.assertHoverContains("rootfs", "a `.tar` file of the image"); editor.assertHoverContains("skip_download", "Skip `docker pull`"); } @Test public void dockerImageResourcePutParamsReconcileAndHovers() throws Exception { Editor editor; editor = harness.newEditor( "resources:\n" + "- name: my-docker-image\n" + " type: docker-image\n" + "jobs:\n" + "- name: a-job\n" + " plan:\n" + " - put: my-docker-image\n" + " params:\n" + " build: path/to/docker/dir\n" + " load: path/to/image\n" + " dockerfile: path/to/Dockerfile\n"+ " cache: cache-it\n" + " cache_tag: the-cache-tag\n" + " load_base: path/to/base-image\n" + " load_file: path/to/file-to-load\n" + " load_repository: some-repo\n" + " load_tag: some-tag\n" + " import_file: path/to/file-to-import\n" + " pull_repository: path/to/repository-to-pull\n" + " pull_tag: tag-to-pull\n" + " tag: path/to/file-containing-tag\n" + " tag_prefix: v\n" + " tag_as_latest: tag-latest\n" + " build_args: the-build-args\n" + " build_args_file: path/to/file-with-build-args.json\n" + " get_params:\n" + " save: save-it\n" + " rootfs: tar-it\n" + " skip_download: skip-it\n" ); editor.assertProblems( "cache-it|'boolean'", "pull_repository|Deprecated", "pull_tag|Deprecated", "tag-latest|'boolean'", "the-build-args|Expecting a 'Map'", "save-it|'boolean'", "tar-it|'boolean'", "skip-it|'boolean'" ); assertEquals(DiagnosticSeverity.Warning, editor.assertProblem("pull_repository").getSeverity()); assertEquals(DiagnosticSeverity.Warning, editor.assertProblem("pull_tag").getSeverity()); editor.assertHoverContains("build", "directory containing a `Dockerfile`"); editor.assertHoverContains("load", "directory containing an image"); editor.assertHoverContains("dockerfile", "path of the `Dockerfile` in the directory"); editor.assertHoverContains("cache", "first pull `image:tag` from the Docker registry"); editor.assertHoverContains("cache_tag", "specific tag to pull"); editor.assertHoverContains("load_base", "path to a directory containing an image to `docker load`"); editor.assertHoverContains("load_file", "path to a file to `docker load`"); editor.assertHoverContains("load_repository", "repository of the image loaded from `load_file`"); editor.assertHoverContains("load_tag", "tag of image loaded from `load_file`"); editor.assertHoverContains("import_file", "file to `docker import`"); editor.assertHoverContains("pull_repository", "repository to pull down"); editor.assertHoverContains("pull_tag", "tag of the repository to pull down"); editor.assertHoverContains(" tag:", "a path to a file containing the name"); // The word 'tag' occurs many times in editor so add use " tag: " to be precise editor.assertHoverContains("tag_prefix", "prepended with this string"); editor.assertHoverContains("tag_as_latest", "tagged as `latest`"); editor.assertHoverContains("build_args", "map of Docker build arguments"); editor.assertHoverContains("build_args_file", "JSON file containing"); editor.assertHoverContains("save", "docker save"); editor.assertHoverContains("rootfs", "a `.tar` file of the image"); editor.assertHoverContains("skip_download", "Skip `docker pull`"); } @Test public void s3ResourceSourceReconcileAndHovers() throws Exception { Editor editor; editor = harness.newEditor( "resources:\n" + "- name: s3-snapshots\n" + " type: s3\n" + " source:\n" + " access_key_id: the-key" ); editor.assertProblems( "source|'bucket' is required", "source|One of [regexp, versioned_file] is required" ); editor = harness.newEditor( "resources:\n" + "- name: s3-snapshots\n" + " type: s3\n" + " source:\n" + " bucket: the-bucket\n" + " access_key_id: the-access-key\n" + " secret_access_key: the-secret-key\n" + " region_name: bogus-region\n" + " private: is-private\n" + " cloudfront_url: https://d5yxxxxx.cloudfront.net\n" + " endpoint: https://blah.custom.com/blah/blah\n" + " disable_ssl: no_ssl_checking\n" + " server_side_encryption: some-encryption-algo\n" + //TODO: validation and CA? What values are acceptable? " sse_kms_key_id: the-master-key-id\n" + " use_v2_signing: should-use-v2\n" + " regexp: path-to-file-(.*).tar.gz\n" + " versioned_file: path/to/file.tar.gz\n" ); editor.assertProblems( "bogus-region|unknown 'S3Region'", "is-private|'boolean'", "no_ssl_checking|'boolean'", "should-use-v2|'boolean'", "regexp|Only one of [regexp, versioned_file] should be defined", "versioned_file|Only one of [regexp, versioned_file] should be defined" ); editor.assertHoverContains("bucket", "The name of the bucket"); editor.assertHoverContains("access_key_id", "The AWS access key"); editor.assertHoverContains("secret_access_key", "The AWS secret key"); editor.assertHoverContains("region_name", "The region the bucket is in"); editor.assertHoverContains("private", "Indicates that the bucket is private"); editor.assertHoverContains("cloudfront_url", "The URL (scheme and domain) of your CloudFront distribution"); editor.assertHoverContains("endpoint", "Custom endpoint for using S3"); editor.assertHoverContains("disable_ssl", "Disable SSL for the endpoint"); editor.assertHoverContains("server_side_encryption", "An encryption algorithm to use"); editor.assertHoverContains("sse_kms_key_id", "The ID of the AWS KMS master encryption key"); editor.assertHoverContains("use_v2_signing", "Use signature v2 signing"); editor.assertHoverContains("regexp", "The pattern to match filenames against within S3"); editor.assertHoverContains("versioned_file", "If you enable versioning for your S3 bucket"); } @Test public void s3ResourceRegionCompletions() throws Exception { String[] validRegions = { //See: http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketPUT.html "us-west-1", "us-west-2", "ca-central-1", "EU", "eu-west-1", "eu-west-2", "eu-central-1", "ap-south-1", "ap-southeast-1", "ap-southeast-2", "ap-northeast-1", "ap-northeast-2", "sa-east-1", "us-east-2" }; Arrays.sort(validRegions); String[] expectedCompletions = new String[validRegions.length]; for (int i = 0; i < expectedCompletions.length; i++) { expectedCompletions[i] = validRegions[i]+"<*>"; } assertContextualCompletions( "resources:\n" + "- name: s3-snapshots\n" + " type: s3\n" + " source:\n" + " region_name: <*>" , //=================== "<*>" , // ===> expectedCompletions ); } @Test public void s3ResourceGetParamsReconcileAndHovers() throws Exception { Editor editor; editor = harness.newEditor( "resources:\n" + "- name: my-s3-bucket\n" + " type: s3\n" + "jobs:\n" + "- name: a-job\n" + " plan:\n" + " - get: my-s3-bucket\n" + " params:\n" + " no-params-expected: bad" ); editor.assertProblems( "no-params-expected|Unknown property" ); } @Test public void s3ResourcePutParamsReconcileAndHovers() throws Exception { Editor editor; editor = harness.newEditor( "resources:\n" + "- name: my-s3-bucket\n" + " type: s3\n" + "jobs:\n" + "- name: a-job\n" + " plan:\n" + " - put: my-s3-bucket\n" + " params:\n" + " acl: public-read\n" + " get_params:\n" + " no-params-expected: bad" ); editor.assertProblems( "params|'file' is required", "no-params-expected|Unknown property" ); editor = harness.newEditor( "resources:\n" + "- name: my-s3-bucket\n" + " type: s3\n" + "jobs:\n" + "- name: a-job\n" + " plan:\n" + " - put: my-s3-bucket\n" + " params:\n" + " file: path/to/file\n" + " acl: bad-acl\n" + " content_type: anything/goes\n" ); editor.assertProblems( "bad-acl|unknown 'S3CannedAcl'" ); editor.assertHoverContains("file", "Path to the file to upload"); editor.assertHoverContains("acl", "Canned Acl"); editor.assertHoverContains("content_type", "MIME"); } @Test public void s3ResourcePutParamsContentAssist() throws Exception { String[] cannedAcls = { //See http://docs.aws.amazon.com/AmazonS3/latest/dev/acl-overview.html#canned-acl "private", "public-read", "public-read-write", "aws-exec-read", "authenticated-read", "bucket-owner-read", "bucket-owner-full-control", "log-delivery-write" }; Arrays.sort(cannedAcls); String conText = "resources:\n" + "- name: my-s3-bucket\n" + " type: s3\n" + "jobs:\n" + "- name: a-job\n" + " plan:\n" + " - put: my-s3-bucket\n" + " params:\n" + " <*>"; assertContextualCompletions(conText, "content_type: json<*>" , //=> "content_type: application/json; charset=utf-8<*>" ); String[] expectedAclCompletions = new String[cannedAcls.length]; for (int i = 0; i < expectedAclCompletions.length; i++) { expectedAclCompletions[i] = "acl: "+cannedAcls[i]+"<*>"; } assertContextualCompletions(conText, "acl: <*>" , // ===> expectedAclCompletions ); } @Test public void poolResourceSourceReconcileAndHovers() throws Exception { Editor editor; editor = harness.newEditor( "resources:\n" + "- name: swimming-pool\n" + " type: pool\n" + " source:\n" + " private_key: stuff" ); editor.assertProblems( "source|[branch, pool, uri] are required" ); editor = harness.newEditor( "resources:\n" + "- name: the--locks\n" + " type: pool\n" + " source:\n" + " uri: [email protected]:concourse/locks.git\n" + " branch: master\n" + " pool: aws\n" + " private_key: |\n" + " -----BEGIN RSA PRIVATE KEY-----\n" + " MIIEowIBAAKCAQEAtCS10/f7W7lkQaSgD/mVeaSOvSF9ql4hf/zfMwfVGgHWjj+W\n" + " ...\n" + " DWiJL+OFeg9kawcUL6hQ8JeXPhlImG6RTUffma9+iGQyyBMCGd1l\n" + " -----END RSA PRIVATE KEY-----\n" + " username: jonhsmith\n" + " password: his-password\n" + " retry_delay: retry-after\n" ); System.out.println(editor.getRawText()); editor.assertProblems( "retry-after|'Duration'" ); editor.assertHoverContains("uri", "The location of the repository."); editor.assertHoverContains("branch", "The branch to track"); editor.assertHoverContains("pool", 2, "The logical name of your pool of things to lock"); editor.assertHoverContains("private_key", "Private key to use when pulling/pushing"); editor.assertHoverContains("username", "Username for HTTP(S) auth"); editor.assertHoverContains("password", "Password for HTTP(S) auth "); editor.assertHoverContains("retry_delay", "how long to wait until retrying"); } @Test public void poolResourceGetParamsReconcileAndHovers() throws Exception { Editor editor; editor = harness.newEditor( "resources:\n" + "- name: my-locks\n" + " type: pool\n" + "jobs:\n" + "- name: a-job\n" + " plan:\n" + " - get: my-locks\n" + " params:\n" + " no-params-expected: bad" ); editor.assertProblems( "no-params-expected|Unknown property" ); } @Test public void poolResourcePutParamsReconcileAndHovers() throws Exception { Editor editor; editor = harness.newEditor( "resources:\n" + "- name: my-locks\n" + " type: pool\n" + "jobs:\n" + "- name: a-job\n" + " plan:\n" + " - put: my-locks\n" + " params:\n" + " acquire: should-acquire\n" + " claim: a-specific-lock\n" + " release: path/to/lock\n" + " add: path/to/lock\n" + " add_claimed: path/to/lock\n" + " remove: path/to/lock" ); editor.assertProblems( "acquire|Only one of", "should-acquire|'boolean'", "claim|Only one of", "release|Only one of", "add|Only one of", "add_claimed|Only one of", "remove|Only one of" ); editor.assertHoverContains("acquire", "attempt to move a randomly chosen lock"); editor.assertHoverContains("claim", "the specified lock from the pool will be acquired"); editor.assertHoverContains("release", "release the lock"); editor.assertHoverContains("add", "add a new lock to the pool in the unclaimed state"); editor.assertHoverContains("add_claimed", "in the *claimed* state"); editor.assertHoverContains("remove", "remove the given lock from the pool"); } @Test public void semverResourceSourceReconcileAtomNotAllowed() throws Exception { Editor editor = harness.newEditor( "resources:\n" + "- name: version\n" + " type: semver\n" + " source: an-atom" ); editor.assertProblems("an-atom|Expecting a 'Map'"); } @Test public void semverResourceSourceReconcileRequiredProps() throws Exception { Editor editor; //required props for s3 driver editor = harness.newEditor( "resources:\n" + "- name: version\n" + " type: semver\n" + " source:\n" + " driver: s3" ); editor.assertProblems( "source|[access_key_id, bucket, key, secret_access_key] are required" ); editor = harness.newEditor( "resources:\n" + "- name: version\n" + " type: semver\n" + " source: {}" ); editor.assertProblems( "source|[access_key_id, bucket, key, secret_access_key] are required" ); // required props for git driver editor = harness.newEditor( "resources:\n" + "- name: version\n" + " type: semver\n" + " source:\n" + " driver: git" ); editor.assertProblems( "source|[branch, file, uri] are required" ); //required props for swift driver editor = harness.newEditor( "resources:\n" + "- name: version\n" + " type: semver\n" + " source:\n" + " driver: swift" ); editor.assertProblems( "source|'openstack' is required" ); } @Test public void semverResourceSourceBadDriver() throws Exception { Editor editor = harness.newEditor( "resources:\n" + "- name: version\n" + " type: semver\n" + " source:\n" + " driver: bad-driver" ); editor.assertProblems("bad-driver|'SemverDriver'"); } @Test public void semverGitResourceSourceContentAssist() throws Exception { String conText = "resources:\n" + "- name: version\n" + " type: semver\n" + " source:\n" + "<*>"; assertContextualCompletions(conText, " driver: git\n" + " <*>" , // ==> " driver: git\n" + " branch: <*>" , " driver: git\n" + " file: <*>" , " driver: git\n" + " git_user: <*>" , " driver: git\n" + " initial_version: <*>" , " driver: git\n" + " password: <*>" , " driver: git\n" + " private_key: <*>" , " driver: git\n" + " uri: <*>" , " driver: git\n" + " username: <*>" , " driver: git<*>" ); } @Test public void semverGitResourceSourceReconcileAndHovers() throws Exception { Editor editor; // required props for git driver editor = harness.newEditor( "resources:\n" + "- name: version\n" + " type: semver\n" + " source:\n" + " initial_version: not-a-version\n" + //TODO: should be marked as a error but isn't yet. " driver: git\n" + " uri: [email protected]:concourse/concourse.git\n" + " branch: version\n" + " file: version\n" + " private_key: {{concourse-repo-private-key}}\n" + " username: jsmith\n" + " password: s3cre$t\n" + " git_user: [email protected]\n" + " bogus: bad" ); editor.assertProblems( "bogus|Unknown property" ); editor.assertHoverContains("initial_version", "version number to use when bootstrapping"); editor.assertHoverContains("driver", "The driver to use"); editor.assertHoverContains("uri", "The repository URL"); editor.assertHoverContains("branch", "The branch the file lives on"); editor.assertHoverContains("file", "The name of the file"); editor.assertHoverContains("private_key", "The SSH private key"); editor.assertHoverContains("username", "Username for HTTP(S) auth"); editor.assertHoverContains("password", "Password for HTTP(S) auth"); editor.assertHoverContains("git_user", "The git identity to use"); } @Test public void semverS3ResourceSourceReconcileAndHovers() throws Exception { Editor editor; //without explicit 'driver'... should assume s3 by default editor = harness.newEditor( "resources:\n" + "- name: version\n" + " type: semver\n" + " source:\n" + " initial_version: 1.2.3\n" + " bucket: the-bucket\n" + " key: object-key\n" + " access_key_id: aws-access-key\n" + " secret_access_key: aws-access-key\n" + " region_name: bogus-region\n" + " endpoint: https://blah.com/blah\n" + " disable_ssl: no-use-ssl\n" + " bogus-prop: bad" ); editor.assertProblems( "bogus-region|'S3Region'", "no-use-ssl|'boolean'", "bogus-prop|Unknown property" ); //with explicit 'driver: s3' editor = harness.newEditor( "resources:\n" + "- name: version\n" + " type: semver\n" + " source:\n" + " initial_version: 1.2.3\n" + " driver: s3\n" + " bucket: the-bucket\n" + " key: object-key\n" + " access_key_id: aws-access-key\n" + " secret_access_key: aws-access-key\n" + " region_name: bogus-region\n" + " endpoint: https://blah.com/blah\n" + " disable_ssl: no-use-ssl\n" + " bogus-prop: bad" ); editor.assertProblems( "bogus-region|'S3Region'", "no-use-ssl|'boolean'", "bogus-prop|Unknown property" ); editor.assertHoverContains("initial_version", "version number to use when bootstrapping"); editor.assertHoverContains("driver", "The driver to use"); editor.assertHoverContains("bucket", "The name of the bucket"); editor.assertHoverContains("key", "The key to use for the object"); editor.assertHoverContains("access_key_id", "The AWS access key to"); editor.assertHoverContains("secret_access_key", "The AWS secret key to"); editor.assertHoverContains("region_name", "The region the bucket is in"); editor.assertHoverContains("endpoint", "Custom endpoint for using S3"); editor.assertHoverContains("disable_ssl", "Disable SSL for the endpoint"); } @Test public void semverSwiftResourceSourceReconcileAndHovers() throws Exception { Editor editor = harness.newEditor( "resources:\n" + "- name: version\n" + " type: semver\n" + " source:\n" + " initial_version: 1.2.3\n" + " driver: swift\n" + " openstack:\n" + " container: nice-container\n" + " item_name: flubber-blub\n" + " region_name: us-west-1\n" ); editor.assertProblems(/*NONE*/); editor.assertHoverContains("openstack", "All openstack configuration"); } @Test public void semverResourceGetParamsReconcileAndHovers() throws Exception { Editor editor = harness.newEditor( "resources:\n" + "- name: version\n" + " type: semver\n" + " source:\n" + " initial_version: 1.2.3\n" + " driver: swift\n" + " openstack: whatever\n" + "jobs:\n" + "- name: a-job\n" + " plan:\n" + " - get: version\n" + " params:\n" + " bump: what-to-bump\n" + " pre: beta\n" + " bogus: bad\n" ); editor.assertProblems( "what-to-bump|[final, major, minor, patch]", "bogus|Unknown property" ); editor.assertHoverContains("bump", "Bump the version number"); editor.assertHoverContains("pre", "bump to a prerelease"); } @Test public void semverPutParamsReconcileAndHovers() throws Exception { Editor editor = harness.newEditor( "resources:\n" + "- name: version\n" + " type: semver\n" + " source:\n" + " initial_version: 1.2.3\n" + " driver: swift\n" + " openstack: whatever\n" + "jobs:\n" + "- name: a-job\n" + " plan:\n" + " - put: version\n" + " params:\n" + " file: version-file\n" + " bump: what-to-bump\n" + " pre: alpha\n" + " bogus-one: bad\n" + " get_params:\n" + " file: not-expected-here\n" + " bump: what-to-get-bump\n" + " pre: beta\n" + " bogus-two: bad\n" ); editor.assertProblems( "what-to-bump|[final, major, minor, patch]", "bogus-one|Unknown property", "file|Unknown property", "what-to-get-bump|[final, major, minor, patch]", "bogus-two|Unknown property" ); editor.assertHoverContains("file", 1, "Path to a file containing the version number"); editor.assertHoverContains("bump", 1, "Bump the version number"); editor.assertHoverContains("bump", 2, "Bump the version number"); editor.assertHoverContains("pre", 1, "bump to a prerelease"); editor.assertHoverContains("pre", 2, "bump to a prerelease"); } @Test public void reconcileExplicitResourceAttributeInPutStep() throws Exception { //See: https://www.pivotaltracker.com/story/show/138568839 Editor editor; editor = harness.newEditor( "resources:\n" + "- name: aws-environments\n" + " type: pool\n" + "jobs:\n" + "- name: test-multi-aws\n" + " plan:\n" + " - put: environment-1\n" + " resource: aws-environments\n" + " params:\n" + " acquire: true\n" + " bogus_param: bad\n" + " get_params:\n" + " bogus_get_param: bad" ); editor.assertProblems( "bogus_param|Unknown property", "bogus_get_param|Unknown property" ); editor = harness.newEditor( "resources:\n" + "- name: aws-environments\n" + " type: pool\n" + "jobs:\n" + "- name: test-multi-aws\n" + " plan:\n" + " - get: environment-1\n" + " resource: aws-environments\n" + " params:\n" + " bogus_param: bad\n" ); editor.assertProblems( "bogus_param|Unknown property" ); editor = harness.newEditor( "resources:\n" + "- name: aws-environments\n" + " type: pool\n" + " source:\n" + " uri: [email protected]:concourse/locks.git\n" + " branch: master\n" + " pool: aws\n" + " private_key: |\n" + " -----BEGIN RSA PRIVATE KEY-----\n" + " MIIEowIBAAKCAQEAtCS10/f7W7lkQaSgD/mVeaSOvSF9ql4hf/zfMwfVGgHWjj+W\n" + " ...\n" + " DWiJL+OFeg9kawcUL6hQ8JeXPhlImG6RTUffma9+iGQyyBMCGd1l\n" + " -----END RSA PRIVATE KEY-----\n" + " username: jonhsmith\n" + " password: his-password\n" + " retry_delay: 10s\n" + "jobs:\n" + "- name: test-multi-aws\n" + " plan:\n" + " - get: aws-environments\n" + " params: {} \n" + " - put: environment-1\n" + " resource: aws-environments\n" + " params: {acquire: true}\n" + " - put: environment-2\n" + " resource: aws-environments\n" + " params: \n" + " acquire: true\n" + " bogus_param: blah\n" + " - task: test-multi-aws\n" + " file: my-scripts/test-multi-aws.yml\n" + " - put: aws-environments\n" + " params: {release: environment-1}\n" + " - put: aws-environments\n" + " params: {release: environment-2}" ); editor.assertProblems( "bogus_param|Unknown property" ); } @Test public void resourceNameContentAssist() throws Exception { String conText; conText = "resources:\n" + "- name: foo-resource\n" + "- name: bar-resource\n" + "- name: other-resource\n" + "jobs:\n" + "- name: test-multi-aws\n" + " plan:\n" + " - <*>"; assertContextualCompletions(conText , // ============== "get: <*>" , "get: bar-resource<*>", "get: foo-resource<*>", "get: other-resource<*>" ); assertContextualCompletions(conText , // ============== "put: <*>" , // ==> "put: bar-resource<*>", "put: foo-resource<*>", "put: other-resource<*>" ); conText = "resources:\n" + "- name: foo-resource\n" + "- name: bar-resource\n" + "- name: other-resource\n" + "jobs:\n" + "- name: test-multi-aws\n" + " plan:\n" + " - put: something\n" + " <*>"; assertContextualCompletions(conText , // ============== "resource: <*>" , // ==> "resource: bar-resource<*>", "resource: foo-resource<*>", "resource: other-resource<*>" ); conText = "resources:\n" + "- name: foo-resource\n" + "- name: bar-resource\n" + "- name: other-resource\n" + "jobs:\n" + "- name: test-multi-aws\n" + " plan:\n" + " - <*>\n" + " resource: foo-resource\n"; // presence of explicit 'resource' attribute should disable treating the name in put/get as a resource-name assertContextualCompletions(conText, "put: <*>" // ==> NONE ); assertContextualCompletions(conText, "get: <*>" // ==> NONE ); } @Test public void gotoResourceDefinition() throws Exception { Editor editor = harness.newEditor( "resources:\n" + "- name: my-git\n" + " type: git\n" + "- name: build-env\n" + " type: docker-image\n" + "jobs:\n" + "- name: do-stuff\n" + " plan:\n" + " - get: my-git\n" + " params:\n" + " rootfs: true\n" + " save: true\n" + " - put: build-env\n" + " build: my-git/docker\n" ); editor.assertGotoDefinition(editor.positionOf("get: my-git", "my-git"), editor.rangeOf("- name: my-git", "my-git") ); } @Test public void gotoJobDefinition() throws Exception { Editor editor = harness.newEditor( "resources:\n" + "- name: my-git\n" + " type: git\n" + "jobs:\n" + "- name: prepare-stuff\n" + " plan:\n" + " - get: my-git\n" + " - task: preparations\n" + " file: my-git/ci/tasks/preparations.yml\n" + "- name: do-stuff\n" + " plan:\n" + " - get: my-git\n" + " passed:\n" + " - prepare-stuff\n" ); editor.assertGotoDefinition(editor.positionOf("- prepare-stuff", "prepare-stuff"), editor.rangeOf("- name: prepare-stuff", "prepare-stuff") ); } @Test public void gotoResourceTypeDefinition() throws Exception { Editor editor = harness.newEditor( "resource_types:\n" + "- name: slack-notification\n" + " type: docker_image\n" + "resources:\n" + "- name: zazazee\n" + " type: slack-notification\n" ); editor.assertGotoDefinition(editor.positionOf("type: slack-notification", "slack-notification"), editor.rangeOf("- name: slack-notification", "slack-notification") ); } @Test public void reconcileResourceTypeNames() throws Exception { String userDefinedResourceTypesSnippet = "resource_types:\n" + "- name: s3-multi\n" + " type: docker-image\n" + " source:\n" + " repository: kdvolder/s3-resource-simple\n" + "- name: slack-notification\n" + " type: docker-image\n" + " source:\n" + " repository: cfcommunity/slack-notification-resource\n" + " tag: latest\n"; String[] goodNames = { //user-defined: "s3-multi", "slack-notification", //built-in: "git", "hg", "time", "s3", "archive", "semver", "github-release", "docker-image", "tracker", "pool", "cf", "bosh-io-release", "bosh-io-stemcell", "bosh-deployment", "vagrant-cloud" }; String[] badNames = { "bogus", "wrong", "not-defined-resource-type" }; //All the bad names are detected and flagged: for (String badName : badNames) { Editor editor = harness.newEditor( userDefinedResourceTypesSnippet + "resources:\n" + "- name: the-resource\n" + " type: "+badName ); editor.assertProblems(badName+"|Resource Type does not exist"); } //All the good names are accepted: for (String goodName : goodNames) { Editor editor = harness.newEditor( userDefinedResourceTypesSnippet + "resources:\n" + "- name: the-resource\n" + " type: "+goodName ); editor.assertProblems(/*None*/); } } @Test public void contentAssistResourceTypeNames() throws Exception { String[] goodNames = { //user-defined: "s3-multi", "slack-notification", //built-in: "git", "hg", "time", "s3", "archive", "semver", "github-release", "docker-image", "tracker", "pool", "cf", "bosh-io-release", "bosh-io-stemcell", "bosh-deployment", "vagrant-cloud" }; Arrays.sort(goodNames); String context = "resource_types:\n" + "- name: s3-multi\n" + " type: docker-image\n" + " source:\n" + " repository: kdvolder/s3-resource-simple\n" + "- name: slack-notification\n" + " type: docker-image\n" + " source:\n" + " repository: cfcommunity/slack-notification-resource\n" + " tag: latest\n" + "resources:\n" + "- type: <*>"; //All the good names are accepted: String[] expectedCompletions = new String[goodNames.length]; for (int i = 0; i < expectedCompletions.length; i++) { expectedCompletions[i] = goodNames[i] +"<*>"; } assertContextualCompletions(context, "<*>" , // ===> expectedCompletions ); } @Test public void reconcileTaskFileToplevelProperties() throws Exception { Editor editor; editor = harness.newEditor(LanguageIds.CONCOURSE_TASK, "image: some-image" ); editor.assertProblems("image: some-image|[platform, run] are required"); editor = harness.newEditor(LanguageIds.CONCOURSE_TASK, "platform: a-platform\n" + "image_resource:\n" + " name: should-not-be-here\n" + " type: docker-image\n" + " source:\n" + " bogus-source-prop: bad\n" + " repository: ruby\n" + " tag: '2.1'\n" + "image: some-image\n" + "inputs:\n" + "- path: path/to/input\n" + "outputs:\n" + "- path: path/to/output\n" + "run:\n" + " path: my-app/scripts/test\n" + "params: the-params\n" ); editor.assertProblems( "image_resource|Only one of [image_resource, image] should be defined", "name|Unknown property", "bogus-source-prop|Unknown property", "image|Only one of [image_resource, image] should be defined", "-^ path: path/to/input|'name' is required", "-^ path: path/to/output|'name' is required", "the-params|Expecting a 'Map'" ); } @Test public void contentAssistTaskFileToplevelProperties() throws Exception { assertTaskCompletions( "<*>" , // ==> "image: <*>" , "image_resource:\n" + " <*>" , "inputs:\n" + "- <*>" , "outputs:\n" + "- <*>" , "params:\n" + " <*>" , "platform: <*>" , "run:\n" + " <*>" ); assertTaskCompletions( "platform: <*>" , //=> "platform: darwin<*>", "platform: linux<*>", "platform: windows<*>" ); } @Test public void hoversForTaskFileToplevelProperties() throws Exception { Editor editor = harness.newEditor(LanguageIds.CONCOURSE_TASK, "image: some-image\n" + "image_resource:\n" + " type: docker-image\n" + " source:\n" + " repository: kdvolder/sts4-build-env\n" + "inputs: []\n" + "outputs: []\n" + "params: {}\n" + "platform: linux\n" + "run:\n" + " path: sts4/concourse/tasks/build-vscode-extensions.sh" ); editor.assertHoverContains("platform", "The platform the task should run on"); editor.assertHoverContains("image_resource", "The base image of the container"); editor.assertHoverContains("image", "A string specifying the rootfs of the container"); editor.assertHoverContains("inputs", "The expected set of inputs for the task"); editor.assertHoverContains("outputs", "The artifacts produced by the task"); editor.assertHoverContains("run", "Note that this is *not* provided as a script blob"); editor.assertHoverContains("params", "A key-value mapping of values that are exposed to the task via environment variables"); editor.assertHoverContains("repository", "The name of the repository"); editor.assertHoverContains("platform", "The platform the task should run on"); } @Test public void reconcileEmbeddedTaskConfig() throws Exception { Editor editor = harness.newEditor( "jobs:\n" + "- name: foo\n" + " plan:\n" + " - task: the-task\n" + " config:\n" + " platform: a-platform\n" + " image_resource:\n" + " name: should-not-be-here\n" + " type: docker-image\n" + " source:\n" + " bogus-source-prop: bad\n" + " repository: ruby\n" + " tag: '2.1'\n" + " image: some-image\n" + " inputs:\n" + " - path: path/to/input\n" + " outputs:\n" + " - path: path/to/output\n" + " run:\n" + " path: my-app/scripts/test\n" + " params: the-params" ); editor.assertProblems( "image_resource|Only one of [image_resource, image] should be defined", "name|Unknown property", "bogus-source-prop|Unknown property", "image|Only one of [image_resource, image] should be defined", "-^ path: path/to/input|'name' is required", "-^ path: path/to/output|'name' is required", "the-params|Expecting a 'Map'" ); } @Test public void taskRunPropertiesValidationAndHovers() throws Exception { Editor editor; editor = harness.newEditor(LanguageIds.CONCOURSE_TASK, "inputs:\n" + "- name: sts4\n" + "outputs:\n" + "- name: vsix-files\n" + "platform: linux\n" + "image_resource:\n" + " type: docker-image\n" + " source:\n" + " repository: kdvolder/sts4-build-env\n" + "run:\n" + " path: sts4/concourse/tasks/build-vscode-extensions.sh\n" + " args: the-args\n" + " user: admin\n" + " dir: the-dir\n" + " bogus: bad\n" ); editor.assertProblems( "the-args|Expecting a 'Sequence'", "bogus|Unknown property" ); editor.assertHoverContains("path", "The command to execute, relative to the task's working directory"); editor.assertHoverContains("args", "Arguments to pass to the command"); editor.assertHoverContains("dir", "A directory, relative to the initial working directory, to set as the working directory"); editor.assertHoverContains("user", "Explicitly set the user to run as"); editor = harness.newEditor(LanguageIds.CONCOURSE_TASK, "inputs:\n" + "- name: sts4\n" + "outputs:\n" + "- name: vsix-files\n" + "platform: linux\n" + "image_resource:\n" + " type: docker-image\n" + " source:\n" + " repository: kdvolder/sts4-build-env\n" + "run:\n" + " user: admin\n" ); editor.assertProblems("run|'path' is required"); } @Test public void nameAndPathHoversInTaskInputsAndOutputs() throws Exception { Editor editor = harness.newEditor(LanguageIds.CONCOURSE_TASK, "inputs:\n" + "- name: sts4\n" + " path: botk\n" + "outputs:\n" + "- name: vsix-files\n" + " path: zaza" ); editor.assertHoverContains("name", 1, "The logical name of the input"); editor.assertHoverContains("name", 2, "The logical name of the output"); editor.assertHoverContains("path", 1, "The path where the input will be placed"); editor.assertHoverContains("path", 2, "The path to a directory where the output will be taken from"); } @Test public void PT_140711495_triple_dash_at_start_of_file_disrupts_content_assist() throws Exception { assertContextualCompletions( "#leading comment\n" + "---\n" + "resources:\n" + "- name: my-repo\n" + " type: git\n" + " source:\n" + " uri: https://github.com/spring-projects/sts4.git\n" + " <*>" , // ================== "bra<*>" , // ==> "branch: <*>" ); assertContextualCompletions( "---\n" + "resources:\n" + "- name: my-repo\n" + " type: git\n" + " source:\n" + " uri: https://github.com/spring-projects/sts4.git\n" + " <*>" , // ================== "bra<*>" , // ==> "branch: <*>" ); assertContextualCompletions( // "---\n" + "resources:\n" + "- name: my-repo\n" + " type: git\n" + " source:\n" + " uri: https://github.com/spring-projects/sts4.git\n" + " <*>" , // ================== "bra<*>" , // ==> "branch: <*>" ); } @Test public void PT_141050891_language_server_crashes_on_CA_before_first_document_marker() throws Exception { Editor editor = harness.newEditor( "%Y<*>\n" + "#leading comment\n" + "---\n" + "resources:\n" + "- name: my-repo\n" + " type: git\n" + " source:\n" + " uri: https://github.com/spring-projects/sts4.git\n" + " <*>" ); //We don't expect completions, but this should at least not crash! editor.assertCompletions(/*NONE*/); } @Test public void resourceInEmbeddedTaskConfigNotRequiredIfSpecifiedInTask() throws Exception { Editor editor; editor = harness.newEditor( "resources:\n" + "- name: docker-image\n" + " type: docker-image\n" + " source:\n" + " username: {{docker_hub_username}}\n" + " password: {{docker_hub_password}}\n" + " repository: kdvolder/sts3-build-env\n" + "jobs:\n" + "- name: build-commons-update-site\n" + " plan:\n" + " - task: hello-world\n" + " image: docker-image\n" + //Given here! So not required in config! " config:\n" + " inputs:\n" + " - name: commons-git\n" + " platform: linux\n" + " run:\n" + " path: which\n" + " args:\n" + " - mvn" ); editor.assertProblems(/*none*/); editor = harness.newEditor( "resources:\n" + "- name: docker-image\n" + " type: docker-image\n" + " source:\n" + " username: {{docker_hub_username}}\n" + " password: {{docker_hub_password}}\n" + " repository: kdvolder/sts3-build-env\n" + "jobs:\n" + "- name: build-commons-update-site\n" + " plan:\n" + " - task: hello-world\n" + " config:\n" + " inputs:\n" + " - name: commons-git\n" + " platform: linux\n" + " run:\n" + " path: which\n" + " args:\n" + " - mvn" ); editor.assertProblems( "config|One of [image_resource, image] is required" ); } @Test public void resourceInTaskConfigFileNotRequired() throws Exception { Editor editor = harness.newEditor(LanguageIds.CONCOURSE_TASK, "inputs:\n" + "- name: commons-git\n" + "platform: linux\n" + "run:\n" + " path: which\n" + " args:\n" + " - mvn" ); editor.assertProblems(/*NONE*/); } @Test public void resourceInEmbeddedTaskConfigDeprecated() throws Exception { Editor editor = harness.newEditor( "resources:\n" + "- name: my-docker-image\n" + " type: docker-image\n" + " source:\n" + " username: {{docker_hub_username}}\n" + " password: {{docker_hub_password}}\n" + " repository: kdvolder/sts3-build-env\n" + "jobs:\n" + "- name: build-commons-update-site\n" + " plan:\n" + " - task: hello-world\n" + " image: my-docker-image\n" + " config:\n" + " image: blah\n" + " image_resource:\n" + " type: docker-image\n" + " inputs:\n" + " - name: commons-git\n" + " platform: linux\n" + " run:\n" + " path: which\n" + " args:\n" + " - mvn" ); List<Diagnostic> problems = editor.assertProblems( "image|Deprecated", "image_resource|Deprecated" ); for (Diagnostic d : problems) { assertEquals(DiagnosticSeverity.Warning, d.getSeverity()); } } @Test public void relaxedIndentContextMoreSpaces() throws Exception { Editor editor; editor = harness.newEditor( "resources:\n" + "- name: foo\n" + " type: git\n" + " source:\n" + " <*>" ); editor.assertCompletionLabels( //For the 'exact' context: "check_every", "name", "source", "type", //For the nested context: "➔ branch", "➔ commit_verification_key_ids", "➔ commit_verification_keys", "➔ disable_ci_skip", "➔ git_config", "➔ gpg_keyserver", "➔ ignore_paths", "➔ password", "➔ paths", "➔ private_key", "➔ skip_ssl_verification", "➔ tag_filter", "➔ uri", "➔ username" ); editor.assertCompletionWithLabel("check_every", "resources:\n" + "- name: foo\n" + " type: git\n" + " source:\n" + " check_every: <*>" ); editor.assertCompletionWithLabel("➔ branch", "resources:\n" + "- name: foo\n" + " type: git\n" + " source:\n" + " branch: <*>" ); editor.assertCompletionWithLabel("➔ commit_verification_key_ids", "resources:\n" + "- name: foo\n" + " type: git\n" + " source:\n" + " commit_verification_key_ids:\n" + " - <*>" ); } @Test public void relaxedIndentContextMoreSpaces2() throws Exception { assertContextualCompletions( "resources:\n" + "- name: foo\n" + " type: git\n" + " source:\n" + " <*>" , // ========= "bra<*>" , //=> " branch: <*>" ); assertContextualCompletions( "resources:\n" + "- name: foo\n" + " type: git\n" + " source:\n" + " <*>" , // ========= "comverids<*>" , //=> " commit_verification_key_ids:\n" + " - <*>" ); } @Test public void relaxedIndentContextMoreSpaces3() throws Exception { Editor editor = harness.newEditor( "jobs:\n" + "- name: job-hello-world\n" + " public: true\n" + " plan:\n" + " - get: resource-tutorial\n" + " - task: hello-world\n" + " <*>" ); editor.assertCompletionLabels( //completions for current (i.e Job) context: "build_logs_to_retain", "disable_manual_trigger", "max_in_flight", "serial", "serial_groups", "name", "plan", "public", //Completions for nested context (i.e. task step) "➔ attempts", "➔ config", "➔ ensure", "➔ file", "➔ image", "➔ input_mapping", "➔ on_failure", "➔ on_success", "➔ output_mapping", "➔ params", "➔ privileged", "➔ tags", "➔ task", "➔ timeout" ); } ////////////////////////////////////////////////////////////////////////////// private void assertContextualCompletions(String conText, String textBefore, String... textAfter) throws Exception { Editor editor = harness.newEditor(conText); editor.reconcile(); //this ensures the conText is parsed and its AST is cached (will be used for //dynamic CA when the conText + textBefore is not parsable. assertContains(CURSOR, conText); textBefore = conText.replace(CURSOR, textBefore); textAfter = Arrays.stream(textAfter) .map((String t) -> conText.replace(CURSOR, t)) .collect(Collectors.toList()).toArray(new String[0]); editor.setText(textBefore); editor.assertCompletions(textAfter); } private void assertCompletions(String textBefore, String... textAfter) throws Exception { Editor editor = harness.newEditor(textBefore); editor.assertCompletions(textAfter); } private void assertTaskCompletions(String textBefore, String... textAfter) throws Exception { Editor editor = harness.newEditor(LanguageIds.CONCOURSE_TASK, textBefore); editor.assertCompletions(textAfter); } }
vscode-extensions/vscode-concourse/src/test/java/org/springframework/ide/vscode/concourse/ConcourseEditorTest.java
/******************************************************************************* * Copyright (c) 2016 Pivotal, Inc. * All rights reserved. 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 * * Contributors: * Pivotal, Inc. - initial API and implementation *******************************************************************************/ package org.springframework.ide.vscode.concourse; import static org.junit.Assert.assertEquals; import static org.springframework.ide.vscode.languageserver.testharness.TestAsserts.assertContains; import java.io.InputStream; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import org.eclipse.lsp4j.Diagnostic; import org.eclipse.lsp4j.DiagnosticSeverity; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.springframework.ide.vscode.commons.languageserver.LanguageIds; import org.springframework.ide.vscode.commons.util.IOUtil; import org.springframework.ide.vscode.languageserver.testharness.Editor; import org.springframework.ide.vscode.languageserver.testharness.LanguageServerHarness; public class ConcourseEditorTest { private static final String CURSOR = "<*>"; LanguageServerHarness harness; @Before public void setup() throws Exception { harness = new LanguageServerHarness(() -> { return new ConcourseLanguageServer() .setMaxCompletions(100); }, LanguageIds.CONCOURSE_PIPELINE ); harness.intialize(null); } @Test public void testReconcileCatchesParseError() throws Exception { Editor editor = harness.newEditor( "somemap: val\n"+ "- sequence" ); editor.assertProblems( "-|expected <block end>" ); } @Test public void reconcileRunsOnDocumentOpenAndChange() throws Exception { Editor editor = harness.newEditor( "somemap: val\n"+ "- sequence" ); editor.assertProblems( "-|expected <block end>" ); editor.setText( "- sequence\n" + "zomemap: val" ); editor.assertProblems( "z|expected <block end>" ); } @Test public void reconcileMisSpelledPropertyNames() throws Exception { Editor editor; editor = harness.newEditor( "resorces:\n" + "- name: git\n" + " type: git\n" ); editor.assertProblems("resorces|Unknown property"); } @Test public void reconcileAcceptsSensiblePipelineFile() throws Exception { Editor editor; editor = harness.newEditor( getClasspathResourceText("workspace/pipeline.yml") ); editor.assertProblems(/*NONE*/);; } private String getClasspathResourceText(String resourceName) throws Exception { InputStream stream = ConcourseEditorTest.class.getClassLoader().getResourceAsStream(resourceName); return IOUtil.toString(stream); } @Test public void reconcileStructuralProblems() throws Exception { Editor editor; //resources should be a sequence not a map, even if there's only one entry editor = harness.newEditor( "resources:\n" + " name: git\n" + " type: git\n" ); editor.assertProblems( "name: git\n type: git|Expecting a 'Sequence' but found a 'Map'" ); editor = harness.newEditor( "jobs:\n" + "- name: a-job\n" + " plan:\n" + " - task: a-task\n" + " tags: a-single-string\n" ); editor.assertProblems( "-^ task|One of [config, file] is required", "a-single-string|Expecting a 'Sequence'" ); editor = harness.newEditor( "jobs:\n" + "- name: a-job\n" + " plan:\n" + " - try:\n" + " put: a-resource\n" ); editor.assertProblems( "a-resource|does not exist" ); //TODO: Add more test cases for structural problem? } @Test public void primaryStepCompletions() throws Exception { assertContextualCompletions( // Context: "jobs:\n" + "- name: some-job\n" + " plan:\n" + " - <*>" , // ============== "<*>" , // => "aggregate:\n" + " - <*>" , // ============== "do:\n" + " - <*>" , // ============== "get: <*>" , // ============== "put: <*>" , // ============== "task: <*>" , // ============== "try:\n" + " <*>" ); } @Test public void PT_136196057_do_step_completion_indentation() throws Exception { assertCompletions( "jobs:\n" + "- name:\n"+ " plan:\n" + " - do<*>" , // => "jobs:\n" + "- name:\n"+ " plan:\n" + " - do:\n" + " - <*>" ); } @Test public void primaryStepHovers() throws Exception { Editor editor = harness.newEditor( "jobs:\n" + "- name: some-job\n" + " plan:\n" + " - get: something\n" + " - put: something\n" + " - do: []\n" + " - aggregate:\n" + " - task: perform-something\n" + " - try:\n" + " put: test-logs\n" ); editor.assertHoverContains("get", "Fetches a resource"); editor.assertHoverContains("put", "Pushes to the given [Resource]"); editor.assertHoverContains("aggregate", "Performs the given steps in parallel"); editor.assertHoverContains("task", "Executes a [Task]"); editor.assertHoverContains("do", "performs the given steps serially"); editor.assertHoverContains("try", "Performs the given step, swallowing any failure"); } @Test public void putStepHovers() throws Exception { Editor editor = harness.newEditor( "jobs:\n" + "- name: some-job\n" + " plan:\n" + " - put: something\n" + " resource: something\n" + " params:\n" + " some_param: some_value\n" + " get_params:\n" + " skip_download: true\n" ); editor.assertHoverContains("resource", "The resource to update"); editor.assertHoverContains("params", "A map of arbitrary configuration"); editor.assertHoverContains("get_params", "A map of arbitrary configuration to forward to the resource that will be utilized during the implicit `get` step"); } @Test public void getStepHovers() throws Exception { Editor editor = harness.newEditor( "jobs:\n" + "- name: some-job\n" + " plan:\n" + " - get: something\n" + " resource: something\n" + " version: latest\n" + " passed: [other-job]\n" + " params:\n" + " some_param: some_value\n" + " trigger: true\n" + " attempts: 10\n" + " on_failure:\n" + " - bogus: bad\n" + " on_success:\n" + " - bogus: bad\n" + " ensure:\n" + " task: cleanups\n" ); editor.assertHoverContains("resource", "The resource to fetch"); editor.assertHoverContains("version", "The version of the resource to fetch"); editor.assertHoverContains("params", "A map of arbitrary configuration"); editor.assertHoverContains("trigger", "Set to `true` to auto-trigger"); editor.assertHoverContains("attempts", "Any step can set the number of times it should be attempted"); editor.assertHoverContains("on_failure", "Any step can have `on_failure` tacked onto it"); editor.assertHoverContains("on_success", "Any step can have `on_success` tacked onto it"); editor.assertHoverContains("ensure", "a second step to execute regardless of the result of the parent step"); } @Test public void groupHovers() throws Exception { Editor editor = harness.newEditor( "groups:\n" + "- name: some-group\n" + " resources: []\n" + " jobs: []\n" ); editor.assertHoverContains("name", "The name of the group"); editor.assertHoverContains("resources", "A list of resources that should appear in this group"); editor.assertHoverContains("jobs", " A list of jobs that should appear in this group"); } @Test public void taskStepHovers() throws Exception { Editor editor = harness.newEditor( "jobs:\n" + "- name: some-job\n" + " plan:\n" + " - task: do-something\n" + " file: some-file.yml\n" + " privileged: true\n" + " image: some-image\n" + " params:\n" + " map: of-stuff\n" + " input_mapping:\n" + " map: of-stuff\n" + " output_mapping:\n" + " map: of-stuff\n" + " config: some-config\n" + " tags: [a, b, c]\n"+ " attempts: 10\n" + " timeout: 1h30m\n" + " ensure:\n" + " bogus: bad\n" + " on_failure:\n" + " bogus: bad\n" + " on_success:\n" + " bogus: bad\n" ); editor.assertHoverContains("file", "`file` points at a `.yml` file containing the task config"); editor.assertHoverContains("privileged", "If set to `true`, the task will run with full capabilities"); editor.assertHoverContains("image", "Names an artifact source within the plan"); editor.assertHoverContains("params", "A map of task parameters to set, overriding those configured in `config` or `file`"); editor.assertHoverContains("input_mapping", "A map from task input names to concrete names in the build plan"); editor.assertHoverContains("output_mapping", "A map from task output names to concrete names"); editor.assertHoverContains("config", "Use `config` to inline the task config"); editor.assertHoverContains("tags", "Any step can be directed at a pool of workers"); editor.assertHoverContains("timeout", "amount of time to limit the step's execution"); } @Test public void aggregateStepHovers() throws Exception { Editor editor; editor = harness.newEditor( "jobs:\n" + "- name: some-job\n" + " plan:\n" + " - aggregate:\n" + " - get: some-resource\n" ); editor.assertHoverContains("aggregate", "Performs the given steps in parallel"); } @Test public void reconcileSimpleTypes() throws Exception { Editor editor; //check for 'format' errors: editor = harness.newEditor( "jobs:\n" + "- name: foo\n" + " serial: boohoo\n" + " max_in_flight: -1\n" + " plan:\n" + " - get: git\n" + " trigger: yohoho\n" + " attempts: 0\n" + " timeout: 1h:30m\n" ); editor.assertProblems( "boohoo|boolean", "-1|must be positive", "git|resource does not exist", "yohoho|boolean", "0|must be at least 1", "1h:30m|Duration" ); //check that correct values are indeed accepted editor = harness.newEditor( "resources:\n" + "- name: git\n" + " type: git\n" + "jobs:\n" + "- name: foo\n" + " serial: true\n" + " max_in_flight: 2\n" + " plan:\n" + " - get: git\n" + " trigger: true" ); editor.assertProblems(/*none*/); } @Test public void noListIndent() throws Exception { Editor editor; editor = harness.newEditor("jo<*>"); editor.assertCompletions( "jobs:\n"+ "- <*>" ); } @Test public void toplevelCompletions() throws Exception { Editor editor; editor = harness.newEditor(CURSOR); editor.assertCompletions( "groups:\n" + "- <*>" , // -------------- "jobs:\n" + "- <*>" , // --------------- "resource_types:\n" + "- <*>" , // --------------- "resources:\n"+ "- <*>" ); editor = harness.newEditor("rety<*>"); editor.assertCompletions( "resource_types:\n" + "- <*>" ); } @Test public void valueCompletions() throws Exception { String [] builtInResourceTypes = { "git", "hg", "time", "s3", "archive", "semver", "github-release", "docker-image", "tracker", "pool", "cf", "bosh-io-release", "bosh-io-stemcell", "bosh-deployment", "vagrant-cloud" }; Arrays.sort(builtInResourceTypes); String[] expectedCompletions = new String[builtInResourceTypes.length]; for (int i = 0; i < expectedCompletions.length; i++) { expectedCompletions[i] = "resources:\n" + "- type: "+builtInResourceTypes[i]+"<*>"; } assertCompletions( "resources:\n" + "- type: <*>" , //=> expectedCompletions ); assertCompletions( "jobs:\n" + "- name: foo\n" + " serial: <*>" , // => "jobs:\n" + "- name: foo\n" + " serial: false<*>" , // -- "jobs:\n" + "- name: foo\n" + " serial: true<*>" ); } @Test public void topLevelHoverInfos() throws Exception { Editor editor = harness.newEditor( "resource_types:\n" + "- name: s3-multi\n" + " type: docker-image\n" + " source:\n" + " repository: kdvolder/s3-resource-simple\n" + "resources:\n" + "- name: docker-git\n" + " type: git\n" + " source:\n" + " uri: [email protected]:spring-projects/sts4.git\n" + " branch: {{branch}}\n" + " username: kdvolder\n" + " private_key: {{rsa_id}}\n" + " paths:\n" + " - concourse/docker\n" + "jobs:\n" + "- name: build-docker-image\n" + " serial: true\n" + " plan:\n" + " - get: docker-git\n" + " trigger: true\n" + " - put: docker-image\n" + " params:\n" + " build: docker-git/concourse/docker\n" + " get_params: \n" + " skip_download: true\n" + "groups:\n" + "- name: a-groups\n" ); editor.assertHoverContains("resource_types", "each pipeline can configure its own custom types by specifying `resource_types` at the top level."); editor.assertHoverContains("resources", "A resource is any entity that can be checked for new versions"); editor.assertHoverContains("jobs", "At a high level, a job describes some actions to perform"); editor.assertHoverContains("groups", "A pipeline may optionally contain a section called `groups`"); } @Test public void reconcileResourceReferences() throws Exception { Editor editor = harness.newEditor( "resources:\n" + "- name: sts4\n" + " type: git\n" + " source:\n" + " uri: https://github.com/kdvolder/somestuff\n" + " branch: master\n" + "jobs:\n" + "- name: job1\n" + " plan:\n" + " - get: sts4\n" + " - get: bogus-get\n" + " - task: do-stuff\n" + " image: bogus-image\n" + " file: some-file.yml\n" + " input_mapping:\n" + " task-input: bogus-input\n" + " repo: sts4\n" + " - put: bogus-put\n" ); editor.assertProblems( "bogus-get|resource does not exist", "bogus-image|resource does not exist", "bogus-input|resource does not exist", "bogus-put|resource does not exist" ); editor.assertProblems( "bogus-get|[sts4]", "bogus-image|[sts4]", "bogus-input|[sts4]", "bogus-put|[sts4]" ); } @Test public void reconcileDuplicateResourceNames() throws Exception { Editor editor = harness.newEditor( "resources:\n" + "- name: sts4\n" + " type: git\n" + "- name: utils\n" + " type: git\n" + "- name: sts4\n" + " type: git\n" ); editor.assertProblems( "sts4|Duplicate resource name", "sts4|Duplicate resource name" ); } @Test public void reconcileDuplicateResourceTypeNames() throws Exception { Editor editor = harness.newEditor( "resource_types:\n" + "- name: slack-notification\n" + " type: docker_image\n" + "- name: slack-notification\n" + " type: docker_image" ); editor.assertProblems( "slack-notification|Duplicate resource-type name", "slack-notification|Duplicate resource-type name" ); } @Test public void violatedPropertyConstraintsAreWarnings() throws Exception { Editor editor; editor = harness.newEditor( "jobs:\n" + "- name: blah" ); Diagnostic problem = editor.assertProblems("-^ name: blah|'plan' is required").get(0); assertEquals(DiagnosticSeverity.Warning, problem.getSeverity()); editor = harness.newEditor( "jobs:\n" + "- name: do-stuff\n" + " plan:\n" + " - task: foo" ); problem = editor.assertProblems("-^ task: foo|One of [config, file] is required").get(0); assertEquals(DiagnosticSeverity.Warning, problem.getSeverity()); editor = harness.newEditor( "jobs:\n" + "- name: do-stuff\n" + " plan:\n" + " - task: foo\n" + " config: {}\n" + " file: path/to/file" ); { List<Diagnostic> problems = editor.assertProblems( "config|Only one of [config, file]", "config|[platform, run] are required", "config|One of [image_resource, image]", "file|Only one of [config, file]" ); //All of the problems in this example are property contraint violations! So all should be warnings. for (Diagnostic diagnostic : problems) { assertEquals(DiagnosticSeverity.Warning, diagnostic.getSeverity()); } } } @Test public void underlineParentPropertyForMissingNode() throws Exception { //See: https://www.pivotaltracker.com/story/show/140709005 Editor editor = harness.newEditor( "jobs:\n" + "- name: hello-world\n" + " plan:\n" + " - task: say-hello\n" + " config:\n" + " image_resource:\n" + " type: docker-image\n" + " source: {repository: ubuntu}\n" + " run:\n" + " path: echo\n" + " args: [\"Hello, world!\"]" ); editor.assertProblems( "config|'platform' is required" ); } @Test public void reconcileDuplicateJobNames() throws Exception { Editor editor = harness.newEditor( "jobs:\n" + "- name: job-1\n" + "- name: utils\n" + "- name: job-1\n" ); editor.assertProblems( "-^ name: job-1|'plan' is required", "job-1|Duplicate job name", "-^ name: utils|'plan' is required", "-^ name: job-1|'plan' is required", "job-1|Duplicate job name" ); } @Test public void completionsResourceReferences() throws Exception { assertContextualCompletions( "resources:\n" + "- name: sts4\n" + "- name: repo-a\n" + "- name: repo-b\n" + "jobs:\n" + "- name: job1\n" + " plan:\n" + " - get: <*>\n" , //////////////////// "<*>" , // => "repo-a<*>", "repo-b<*>", "sts4<*>" ); assertContextualCompletions( "resources:\n" + "- name: sts4\n" + "- name: repo-a\n" + "- name: repo-b\n" + "jobs:\n" + "- name: job1\n" + " plan:\n" + " - put: <*>\n" , //////////////////// "r<*>" , // => "repo-a<*>", "repo-b<*>" ); } @Test public void reconcileDuplicateKeys() throws Exception { Editor editor = harness.newEditor( "resources:\n" + "- name: my-repo\n" + " type: git\n" + " source:\n" + " branch: master\n" + " uri: https://github.com/kdvolder/my-repo\n" + "resources:\n" + "- name: your-repo\n" + " type: git\n" + " type: git\n" + " source:\n" + " branch: master\n" + " uri: https://github.com/kdvolder/forked-repo\n" ); editor.assertProblems( "resources|Duplicate key", "resources|Duplicate key", "type|Duplicate key", "type|Duplicate key" ); } @Test public void reconcileJobNames() throws Exception { Editor editor = harness.newEditor( "resources:\n" + "- name: git-repo\n" + " type: git\n" + "- name: build-artefact\n" + " type: git\n" + "jobs:\n" + "- name: build\n" + " plan:\n" + " - get: git-repo\n" + " - task: run-build\n" + " file: some-task.yml\n" + " - put: build-artefact\n" + "- name: test\n" + " plan:\n" + " - get: git-repo\n" + " passed:\n" + " - not-a-job\n" + " - build\n" ); editor.assertProblems("not-a-job|does not exist"); } @Test public void reconcileGroups() throws Exception { Editor editor = harness.newEditor( "resources:\n" + "- name: git-repo\n" + " type: git\n" + "- name: build-artefact\n" + " type: git\n" + "jobs:\n" + "- name: build\n" + " plan:\n" + " - get: git-repo\n" + " - task: run-build\n" + " file: tasks/some-task.yml\n" + " - put: build-artefact\n" + "- name: test\n" + " plan:\n" + " - get: git-repo\n" + "groups:\n" + "- name: some-group\n" + " jobs: [build, test, bogus-job]\n" + " resources: [git-repo, build-artefact, not-a-resource]" ); editor.assertProblems( "bogus-job|does not exist", "not-a-resource|does not exist" ); } @Test public void timeResourceCompletions() throws Exception { assertContextualCompletions( "resources:\n" + "- name: every5minutes\n" + " type: time\n" + " source:\n" + " <*>" , // ====================== "<*>" , // => "days:\n"+ " - <*>", "interval: <*>", "location: <*>", "start: <*>", "stop: <*>" ); assertContextualCompletions( "resources:\n" + "- name: every5minutes\n" + " type: time\n" + " source:\n" + " days:\n" + " - <*>" , // ====================== "<*>" , // => "Friday<*>", "Monday<*>", "Saturday<*>", "Sunday<*>", "Thursday<*>", "Tuesday<*>", "Wednesday<*>" ); assertContextualCompletions( "resources:\n" + "- name: every5minutes\n" + " type: time\n" + " location: <*>" , // ====================== "Van<*>" , // => "America/Vancouver" ); } @Test public void timeResourceSourceReconcile() throws Exception { Editor editor; editor = harness.newEditor( "resources:\n" + "- name: every5minutes\n" + " type: time\n" + " source:\n" + " location: PST8PDT\n" + " start: 7AM\n" + " stop: 8AM\n" + " interval: 5m\n" + " days:\n" + " - Thursday\n" ); editor.assertProblems(/*NONE*/); editor = harness.newEditor( "resources:\n" + "- name: every5minutes\n" + " type: time\n" + " source:\n" + " location: some-location\n" + " start: the-start-time\n" + " stop: the-stop-time\n" + " interval: the-interval\n" + " days:\n" + " - Monday\n" + " - Someday\n" ); editor.assertProblems( "some-location|Unknown 'Location'", "the-start-time|not a valid 'Time'", "the-stop-time|not a valid 'Time'", "the-interval|not a valid 'Duration'", "Someday|unknown 'Day'" ); } @Test public void timeResourceSourceHovers() throws Exception { Editor editor = harness.newEditor( "resources:\n" + "- name: timed-trigger\n" + " type: time\n" + " source:\n" + " interval: 5m\n" + " location: UTC\n" + " start: 8:00PM\n" + " stop: 9:00PM\n" + " days: [Monday, Wednesday, Friday]" ); editor.assertHoverContains("interval", "interval on which to report new versions"); editor.assertHoverContains("location", "*Optional. Default `UTC`"); editor.assertHoverContains("start", "The supported time formats are"); editor.assertHoverContains("stop", "The supported time formats are"); editor.assertHoverContains("days", "Run only on these day(s)"); } @Test public void gitResourceSourceReconcile() throws Exception { Editor editor = harness.newEditor( "resources:\n" + "- name: sts4-out\n" + " type: git\n" + " source:\n" + " uri: [email protected]:spring-projects/sts4.git\n" + " bogus: bad\n" + " branch: {{branch}}\n" + " private_key: {{rsa_id}}\n" + " username: jeffy\n" + " password: {{git_passwords}}\n" + " paths: not-a-list\n" + " ignore_paths: also-not-a-list\n" + " skip_ssl_verification: skip-it\n" + " tag_filter: RELEASE_*\n" + " git_config:\n" + " - name: good\n" + " val: bad\n" + " disable_ci_skip: no_ci_skip\n" + " commit_verification_keys: not-a-list-of-keys\n" + " commit_verification_key_ids: not-a-list-of-ids\n" + " gpg_keyserver: hkp://somekeyserver.net" ); editor.assertProblems( "bogus|Unknown property", "not-a-list|Expecting a 'Sequence'", "also-not-a-list|Expecting a 'Sequence'", "skip-it|'boolean'", "val|Unknown property", "no_ci_skip|'boolean'", "not-a-list-of-keys|Expecting a 'Sequence'", "not-a-list-of-ids|Expecting a 'Sequence'" ); } @Test public void gitResourceSourceCompletions() throws Exception { assertContextualCompletions( "resources:\n" + "- name: the-repo\n" + " type: git\n" + " source:\n" + " <*>" , //================ "<*>" , // ==> "branch: <*>" , "commit_verification_key_ids:\n" + " - <*>" , "commit_verification_keys:\n" + " - <*>" , "disable_ci_skip: <*>" , "git_config:\n" + " - <*>" , "gpg_keyserver: <*>" , "ignore_paths:\n" + " - <*>" , "password: <*>" , "paths:\n" + " - <*>" , "private_key: <*>" , "skip_ssl_verification: <*>" , "tag_filter: <*>" , "uri: <*>" , "username: <*>" ); assertContextualCompletions( "resources:\n" + "- name: the-repo\n" + " type: git\n" + " source:\n" + " git_config:\n" + " - <*>" , // ============= "<*>" , // ==> "name: <*>", "value: <*>" ); } @Test public void gitResourceSourceHovers() throws Exception { Editor editor = harness.newEditor( "resources:\n" + "- name: sts4-out\n" + " type: git\n" + " source:\n" + " uri: [email protected]:spring-projects/sts4.git\n" + " bogus: bad\n" + " branch: {{branch}}\n" + " private_key: {{rsa_id}}\n" + " username: jeffy\n" + " password: {{git_passwords}}\n" + " paths: not-a-list\n" + " ignore_paths: also-not-a-list\n" + " skip_ssl_verification: skip-it\n" + " tag_filter: RELEASE_*\n" + " git_config:\n" + " - name: good\n" + " val: bad\n" + " disable_ci_skip: no_ci_skip\n" + " commit_verification_keys: not-a-list-of-keys\n" + " commit_verification_key_ids: not-a-list-of-ids\n" + " gpg_keyserver: hkp://somekeyserver.net" ); editor.assertHoverContains("uri", "*Required.* The location of the repository."); editor.assertHoverContains("branch", "The branch to track"); editor.assertHoverContains("private_key", "Private key to use when pulling/pushing"); editor.assertHoverContains("username", "Username for HTTP(S) auth"); editor.assertHoverContains("password", "Password for HTTP(S) auth"); editor.assertHoverContains("paths", "a list of glob patterns"); editor.assertHoverContains("ignore_paths", "The inverse of `paths`"); editor.assertHoverContains("skip_ssl_verification", "Skips git ssl verification"); editor.assertHoverContains("tag_filter", "the resource will only detect commits"); editor.assertHoverContains("git_config", "configure git global options"); editor.assertHoverContains("disable_ci_skip", "Allows for commits that have been labeled with `[ci skip]`"); editor.assertHoverContains("commit_verification_keys", "Array of GPG public keys"); editor.assertHoverContains("commit_verification_key_ids", "Array of GPG public key ids"); } @Test public void gitResourceGetParamsCompletions() throws Exception { String context = "resources:\n" + "- name: my-git\n" + " type: git\n" + "jobs:\n" + "- name: do-stuff\n" + " plan:\n" + " - get: my-git\n" + " params:\n" + " <*>"; assertContextualCompletions(context, "<*>" , // ===> "depth: <*>" , "disable_git_lfs: <*>" , "submodules:\n"+ " <*>" ); assertContextualCompletions(context, "disable_git_lfs: <*>" , // ===> "disable_git_lfs: false<*>", "disable_git_lfs: true<*>" ); assertContextualCompletions(context, "submodules: <*>" , // ===> "submodules: all<*>", "submodules: none<*>" ); } @Test public void gitResourceGetParamsHovers() throws Exception { Editor editor = harness.newEditor( "resources:\n" + "- name: my-git\n" + " type: git\n" + "jobs:\n" + "- name: do-stuff\n" + " plan:\n" + " - get: my-git\n" + " params:\n" + " depth: -1\n" + " disable_git_lfs: not-bool\n" + " submodules: none" ); editor.assertHoverContains("depth", "using the `--depth` option"); editor.assertHoverContains("submodules", "If `none`, submodules will not be fetched"); editor.assertHoverContains("disable_git_lfs", "will not fetch Git LFS files"); } @Test public void gitResourceGetParamsReconcile() throws Exception { Editor editor = harness.newEditor( "resources:\n" + "- name: my-git\n" + " type: git\n" + "jobs:\n" + "- name: do-stuff\n" + " plan:\n" + " - get: my-git\n" + " params:\n" + " depth: -1\n" + " disable_git_lfs: not-bool\n" ); editor.assertProblems( "-1|must be positive", "not-bool|'boolean'" ); } @Test public void gitResourcePutParamsCompletions() throws Exception { String context = "resources:\n" + "- name: my-git\n" + " type: git\n" + "jobs:\n" + "- name: do-stuff\n" + " plan:\n" + " - put: my-git\n" + " params:\n" + " <*>"; assertContextualCompletions(context, "<*>" , // ===> "annotate: <*>" , "force: <*>" , "only_tag: <*>" , "rebase: <*>" , "repository: <*>" , "tag: <*>" , "tag_prefix: <*>" ); assertContextualCompletions(context, "rebase: <*>" , // ===> "rebase: false<*>", "rebase: true<*>" ); assertContextualCompletions(context, "only_tag: <*>" , // ===> "only_tag: false<*>", "only_tag: true<*>" ); assertContextualCompletions(context, "force: <*>" , // ===> "force: false<*>", "force: true<*>" ); } @Test public void gitResourcePutParamsReconcile() throws Exception { Editor editor; editor = harness.newEditor( "resources:\n" + "- name: my-git\n" + " type: git\n" + "jobs:\n" + "- name: do-stuff\n" + " plan:\n" + " - put: my-git\n" + " params: {}\n" ); editor.assertProblems("params|'repository' is required"); editor = harness.newEditor( "resources:\n" + "- name: my-git\n" + " type: git\n" + "jobs:\n" + "- name: do-stuff\n" + " plan:\n" + " - put: my-git\n" + " params:\n" + " repository: some-other-repo\n" + " rebase: do-rebase\n" + " only_tag: do-tag\n" + " force: force-it\n" ); editor.assertProblems( "do-rebase|'boolean'", "do-tag|'boolean'", "force-it|'boolean'" ); } @Test public void gitResourcePutParamsHovers() throws Exception { Editor editor = harness.newEditor( "resources:\n" + "- name: my-git\n" + " type: git\n" + "jobs:\n" + "- name: do-stuff\n" + " plan:\n" + " - put: my-git\n" + " params:\n" + " repository: some-other-repo\n" + " rebase: do-rebase\n" + " tag: the-tag-file\n" + " only_tag: do-tag\n" + " tag_prefix: RELEASE\n" + " force: force-it\n" + " annotate: release-annotion\n" ); editor.assertHoverContains("repository", "The path of the repository"); editor.assertHoverContains("rebase", "attempt rebasing"); editor.assertHoverContains("tag", "HEAD will be tagged"); editor.assertHoverContains("only_tag", "push only the tags"); editor.assertHoverContains("tag_prefix", "prepended with this string"); editor.assertHoverContains("force", "pushed regardless of the upstream state"); editor.assertHoverContains("annotate", "path to a file containing the annotation message"); } @Test public void gitResourcePut_get_params_Hovers() throws Exception { Editor editor = harness.newEditor( "resources:\n" + "- name: my-git\n" + " type: git\n" + "jobs:\n" + "- name: do-stuff\n" + " plan:\n" + " - put: my-git\n" + " get_params:\n" + " depth: 1\n" + " submodules: none\n" + " disable_git_lfs: true\n" ); editor.assertHoverContains("depth", "using the `--depth` option"); editor.assertHoverContains("submodules", "If `none`, submodules will not be fetched"); editor.assertHoverContains("disable_git_lfs", "will not fetch Git LFS files"); } @Test public void contentAssistJobNames() throws Exception { assertContextualCompletions( "resources:\n" + "- name: git-repo\n" + "- name: build-artefact\n" + "jobs:\n" + "- name: build\n" + " plan:\n" + " - get: git-repo\n" + " - task: run-build\n" + " - put: build-artefact\n" + "- name: test\n" + " plan:\n" + " - get: git-repo\n" + " passed:\n" + " - <*>\n" , /////////////////////////// "<*>" , // => "build<*>", "test<*>" ); } @Test public void resourceTypeAttributeHovers() throws Exception { Editor editor = harness.newEditor( "resource_types:\n" + "- name: s3-multi\n" + " type: docker-image\n" + " source:\n" + " repository: kdvolder/s3-resource-simple\n" ); editor.assertHoverContains("name", "This name will be referenced by `resources` defined within the same pipeline"); editor.assertHoverContains("type", 2, "used to provide the resource type's container image"); editor.assertHoverContains("source", 2, "The location of the resource type's resource"); } @Test public void resourceAttributeHovers() throws Exception { Editor editor = harness.newEditor( "resources:\n" + "- name: sts4\n" + " type: git\n" + " check_every: 5m\n" + " source:\n" + " repository: https://github.com/spring-projects/sts4\n" ); editor.assertHoverContains("name", "The name of the resource"); editor.assertHoverContains("type", "The type of the resource. Each worker advertises"); editor.assertHoverContains("source", 2, "The location of the resource"); editor.assertHoverContains("check_every", "The interval on which to check for new versions"); } @Test public void requiredPropertiesReconcile() throws Exception { Editor editor; //addProp(resource, "name", resourceNameDef).isRequired(true); editor = harness.newEditor( "resources:\n" + "- type: git" ); editor.assertProblems("-^ type: git|'name' is required"); //addProp(resource, "type", t_resource_type_name).isRequired(true); editor = harness.newEditor( "resources:\n" + "- name: foo" ); editor.assertProblems("-^ name: foo|'type' is required"); //Both name and type missing: editor = harness.newEditor( "resources:\n" + "- source: {}" ); editor.assertProblems("-^ source:|[name, type] are required"); //addProp(job, "name", jobNameDef).isRequired(true); editor = harness.newEditor( "jobs:\n" + "- name: foo" ); editor.assertProblems("-^ name: foo|'plan' is required"); //addProp(job, "plan", f.yseq(step)).isRequired(true); editor = harness.newEditor( "jobs:\n" + "- plan: []" ); editor.assertProblems("-^ plan: []|'name' is required"); //addProp(resourceType, "name", t_ne_string).isRequired(true); editor = harness.newEditor( "resource_types:\n" + "- type: docker-image" ); editor.assertProblems("-^ type: docker-image|'name' is required"); //addProp(resourceType, "type", t_image_type).isRequired(true); editor = harness.newEditor( "resource_types:\n" + "- name: foo" ); editor.assertProblems("-^ name: foo|'type' is required"); //addProp(gitSource, "uri", t_string).isRequired(true); editor = harness.newEditor( "resources:\n" + "- name: foo\n" + " type: git\n" + " source:\n" + " branch: master" ); editor.assertProblems("source|'uri' is required"); //addProp(gitSource, "branch", t_string).isRequired(true); editor = harness.newEditor( "resources:\n" + "- name: foo\n" + " type: git\n" + " source:\n" + " uri: https://yada" ); editor.assertProblems("source|'branch' is required"); //addProp(group, "name", t_ne_string).isRequired(true); editor = harness.newEditor( "groups:\n" + "- jobs: []" ); editor.assertProblems("-^ jobs: []|'name' is required"); } @Test public void dockerImageResourceSourceReconcileAndHovers() throws Exception { Editor editor; editor = harness.newEditor( "resources:\n" + "- name: my-docker-image\n" + " type: docker-image\n" + " source:\n" + " tag: latest\n" ); editor.assertProblems("source|'repository' is required"); editor = harness.newEditor( "resources:\n" + "- name: my-docker-image\n" + " type: docker-image\n" + " source:\n" + " repository: kdvolder/sts4-build-env\n" + " tag: latest\n" + " username: kdvolder\n" + " password: {{docker_password}}\n" + " aws_access_key_id: {{aws_access_key}}\n" + " aws_secret_access_key: {{aws_secret_key}}\n" + " insecure_registries: no-list\n" + " registry_mirror: https://my-docker-registry.com\n" + " ca_certs:\n" + " - domain: example.com:443\n" + " cert: |\n" + " -----BEGIN CERTIFICATE-----\n" + " ...\n" + " -----END CERTIFICATE-----\n" + " bogus_ca_certs_prop: bad\n" + " client_certs:\n" + " - domain: example.com:443\n" + " cert: |\n" + " -----BEGIN CERTIFICATE-----\n" + " ...\n" + " -----END CERTIFICATE-----\n" + " key: |\n" + " -----BEGIN RSA PRIVATE KEY-----\n" + " ...\n" + " -----END RSA PRIVATE KEY-----\n" + " bogus_client_cert_prop: bad\n" ); editor.assertProblems( "no-list|Expecting a 'Sequence'", "bogus_ca_certs_prop|Unknown property", //ca_certs "bogus_client_cert_prop|Unknown property" //client_certs ); editor.assertHoverContains("repository", "The name of the repository"); editor.assertHoverContains("tag", "The tag to track"); editor.assertHoverContains("username", "username to authenticate"); editor.assertHoverContains("password", "password to use"); editor.assertHoverContains("aws_access_key_id", "AWS access key to use"); editor.assertHoverContains("aws_secret_access_key", "AWS secret key to use"); editor.assertHoverContains("insecure_registries", "array of CIDRs"); editor.assertHoverContains("registry_mirror", "URL pointing to a docker registry"); editor.assertHoverContains("ca_certs", "Each entry specifies the x509 CA certificate for"); editor.assertHoverContains("client_certs", "Each entry specifies the x509 certificate and key"); } @Test public void dockerImageResourceGetParamsReconcileAndHovers() throws Exception { Editor editor; editor = harness.newEditor( "resources:\n" + "- name: my-docker-image\n" + " type: docker-image\n" + "jobs:\n" + "- name: a-job\n" + " plan:\n" + " - get: my-docker-image\n" + " params:\n" + " save: save-it\n" + " rootfs: tar-it\n" + " skip_download: skip-it\n" ); editor.assertProblems( "save-it|'boolean'", "tar-it|'boolean'", "skip-it|'boolean'" ); editor.assertHoverContains("save", "docker save"); editor.assertHoverContains("rootfs", "a `.tar` file of the image"); editor.assertHoverContains("skip_download", "Skip `docker pull`"); } @Test public void dockerImageResourcePutParamsReconcileAndHovers() throws Exception { Editor editor; editor = harness.newEditor( "resources:\n" + "- name: my-docker-image\n" + " type: docker-image\n" + "jobs:\n" + "- name: a-job\n" + " plan:\n" + " - put: my-docker-image\n" + " params:\n" + " build: path/to/docker/dir\n" + " load: path/to/image\n" + " dockerfile: path/to/Dockerfile\n"+ " cache: cache-it\n" + " cache_tag: the-cache-tag\n" + " load_base: path/to/base-image\n" + " load_file: path/to/file-to-load\n" + " load_repository: some-repo\n" + " load_tag: some-tag\n" + " import_file: path/to/file-to-import\n" + " pull_repository: path/to/repository-to-pull\n" + " pull_tag: tag-to-pull\n" + " tag: path/to/file-containing-tag\n" + " tag_prefix: v\n" + " tag_as_latest: tag-latest\n" + " build_args: the-build-args\n" + " build_args_file: path/to/file-with-build-args.json\n" + " get_params:\n" + " save: save-it\n" + " rootfs: tar-it\n" + " skip_download: skip-it\n" ); editor.assertProblems( "cache-it|'boolean'", "pull_repository|Deprecated", "pull_tag|Deprecated", "tag-latest|'boolean'", "the-build-args|Expecting a 'Map'", "save-it|'boolean'", "tar-it|'boolean'", "skip-it|'boolean'" ); assertEquals(DiagnosticSeverity.Warning, editor.assertProblem("pull_repository").getSeverity()); assertEquals(DiagnosticSeverity.Warning, editor.assertProblem("pull_tag").getSeverity()); editor.assertHoverContains("build", "directory containing a `Dockerfile`"); editor.assertHoverContains("load", "directory containing an image"); editor.assertHoverContains("dockerfile", "path of the `Dockerfile` in the directory"); editor.assertHoverContains("cache", "first pull `image:tag` from the Docker registry"); editor.assertHoverContains("cache_tag", "specific tag to pull"); editor.assertHoverContains("load_base", "path to a directory containing an image to `docker load`"); editor.assertHoverContains("load_file", "path to a file to `docker load`"); editor.assertHoverContains("load_repository", "repository of the image loaded from `load_file`"); editor.assertHoverContains("load_tag", "tag of image loaded from `load_file`"); editor.assertHoverContains("import_file", "file to `docker import`"); editor.assertHoverContains("pull_repository", "repository to pull down"); editor.assertHoverContains("pull_tag", "tag of the repository to pull down"); editor.assertHoverContains(" tag:", "a path to a file containing the name"); // The word 'tag' occurs many times in editor so add use " tag: " to be precise editor.assertHoverContains("tag_prefix", "prepended with this string"); editor.assertHoverContains("tag_as_latest", "tagged as `latest`"); editor.assertHoverContains("build_args", "map of Docker build arguments"); editor.assertHoverContains("build_args_file", "JSON file containing"); editor.assertHoverContains("save", "docker save"); editor.assertHoverContains("rootfs", "a `.tar` file of the image"); editor.assertHoverContains("skip_download", "Skip `docker pull`"); } @Test public void s3ResourceSourceReconcileAndHovers() throws Exception { Editor editor; editor = harness.newEditor( "resources:\n" + "- name: s3-snapshots\n" + " type: s3\n" + " source:\n" + " access_key_id: the-key" ); editor.assertProblems( "source|'bucket' is required", "source|One of [regexp, versioned_file] is required" ); editor = harness.newEditor( "resources:\n" + "- name: s3-snapshots\n" + " type: s3\n" + " source:\n" + " bucket: the-bucket\n" + " access_key_id: the-access-key\n" + " secret_access_key: the-secret-key\n" + " region_name: bogus-region\n" + " private: is-private\n" + " cloudfront_url: https://d5yxxxxx.cloudfront.net\n" + " endpoint: https://blah.custom.com/blah/blah\n" + " disable_ssl: no_ssl_checking\n" + " server_side_encryption: some-encryption-algo\n" + //TODO: validation and CA? What values are acceptable? " sse_kms_key_id: the-master-key-id\n" + " use_v2_signing: should-use-v2\n" + " regexp: path-to-file-(.*).tar.gz\n" + " versioned_file: path/to/file.tar.gz\n" ); editor.assertProblems( "bogus-region|unknown 'S3Region'", "is-private|'boolean'", "no_ssl_checking|'boolean'", "should-use-v2|'boolean'", "regexp|Only one of [regexp, versioned_file] should be defined", "versioned_file|Only one of [regexp, versioned_file] should be defined" ); editor.assertHoverContains("bucket", "The name of the bucket"); editor.assertHoverContains("access_key_id", "The AWS access key"); editor.assertHoverContains("secret_access_key", "The AWS secret key"); editor.assertHoverContains("region_name", "The region the bucket is in"); editor.assertHoverContains("private", "Indicates that the bucket is private"); editor.assertHoverContains("cloudfront_url", "The URL (scheme and domain) of your CloudFront distribution"); editor.assertHoverContains("endpoint", "Custom endpoint for using S3"); editor.assertHoverContains("disable_ssl", "Disable SSL for the endpoint"); editor.assertHoverContains("server_side_encryption", "An encryption algorithm to use"); editor.assertHoverContains("sse_kms_key_id", "The ID of the AWS KMS master encryption key"); editor.assertHoverContains("use_v2_signing", "Use signature v2 signing"); editor.assertHoverContains("regexp", "The pattern to match filenames against within S3"); editor.assertHoverContains("versioned_file", "If you enable versioning for your S3 bucket"); } @Test public void s3ResourceRegionCompletions() throws Exception { String[] validRegions = { //See: http://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketPUT.html "us-west-1", "us-west-2", "ca-central-1", "EU", "eu-west-1", "eu-west-2", "eu-central-1", "ap-south-1", "ap-southeast-1", "ap-southeast-2", "ap-northeast-1", "ap-northeast-2", "sa-east-1", "us-east-2" }; Arrays.sort(validRegions); String[] expectedCompletions = new String[validRegions.length]; for (int i = 0; i < expectedCompletions.length; i++) { expectedCompletions[i] = validRegions[i]+"<*>"; } assertContextualCompletions( "resources:\n" + "- name: s3-snapshots\n" + " type: s3\n" + " source:\n" + " region_name: <*>" , //=================== "<*>" , // ===> expectedCompletions ); } @Test public void s3ResourceGetParamsReconcileAndHovers() throws Exception { Editor editor; editor = harness.newEditor( "resources:\n" + "- name: my-s3-bucket\n" + " type: s3\n" + "jobs:\n" + "- name: a-job\n" + " plan:\n" + " - get: my-s3-bucket\n" + " params:\n" + " no-params-expected: bad" ); editor.assertProblems( "no-params-expected|Unknown property" ); } @Test public void s3ResourcePutParamsReconcileAndHovers() throws Exception { Editor editor; editor = harness.newEditor( "resources:\n" + "- name: my-s3-bucket\n" + " type: s3\n" + "jobs:\n" + "- name: a-job\n" + " plan:\n" + " - put: my-s3-bucket\n" + " params:\n" + " acl: public-read\n" + " get_params:\n" + " no-params-expected: bad" ); editor.assertProblems( "params|'file' is required", "no-params-expected|Unknown property" ); editor = harness.newEditor( "resources:\n" + "- name: my-s3-bucket\n" + " type: s3\n" + "jobs:\n" + "- name: a-job\n" + " plan:\n" + " - put: my-s3-bucket\n" + " params:\n" + " file: path/to/file\n" + " acl: bad-acl\n" + " content_type: anything/goes\n" ); editor.assertProblems( "bad-acl|unknown 'S3CannedAcl'" ); editor.assertHoverContains("file", "Path to the file to upload"); editor.assertHoverContains("acl", "Canned Acl"); editor.assertHoverContains("content_type", "MIME"); } @Test public void s3ResourcePutParamsContentAssist() throws Exception { String[] cannedAcls = { //See http://docs.aws.amazon.com/AmazonS3/latest/dev/acl-overview.html#canned-acl "private", "public-read", "public-read-write", "aws-exec-read", "authenticated-read", "bucket-owner-read", "bucket-owner-full-control", "log-delivery-write" }; Arrays.sort(cannedAcls); String conText = "resources:\n" + "- name: my-s3-bucket\n" + " type: s3\n" + "jobs:\n" + "- name: a-job\n" + " plan:\n" + " - put: my-s3-bucket\n" + " params:\n" + " <*>"; assertContextualCompletions(conText, "content_type: json<*>" , //=> "content_type: application/json; charset=utf-8<*>" ); String[] expectedAclCompletions = new String[cannedAcls.length]; for (int i = 0; i < expectedAclCompletions.length; i++) { expectedAclCompletions[i] = "acl: "+cannedAcls[i]+"<*>"; } assertContextualCompletions(conText, "acl: <*>" , // ===> expectedAclCompletions ); } @Test public void poolResourceSourceReconcileAndHovers() throws Exception { Editor editor; editor = harness.newEditor( "resources:\n" + "- name: swimming-pool\n" + " type: pool\n" + " source:\n" + " private_key: stuff" ); editor.assertProblems( "source|[branch, pool, uri] are required" ); editor = harness.newEditor( "resources:\n" + "- name: the--locks\n" + " type: pool\n" + " source:\n" + " uri: [email protected]:concourse/locks.git\n" + " branch: master\n" + " pool: aws\n" + " private_key: |\n" + " -----BEGIN RSA PRIVATE KEY-----\n" + " MIIEowIBAAKCAQEAtCS10/f7W7lkQaSgD/mVeaSOvSF9ql4hf/zfMwfVGgHWjj+W\n" + " ...\n" + " DWiJL+OFeg9kawcUL6hQ8JeXPhlImG6RTUffma9+iGQyyBMCGd1l\n" + " -----END RSA PRIVATE KEY-----\n" + " username: jonhsmith\n" + " password: his-password\n" + " retry_delay: retry-after\n" ); System.out.println(editor.getRawText()); editor.assertProblems( "retry-after|'Duration'" ); editor.assertHoverContains("uri", "The location of the repository."); editor.assertHoverContains("branch", "The branch to track"); editor.assertHoverContains("pool", 2, "The logical name of your pool of things to lock"); editor.assertHoverContains("private_key", "Private key to use when pulling/pushing"); editor.assertHoverContains("username", "Username for HTTP(S) auth"); editor.assertHoverContains("password", "Password for HTTP(S) auth "); editor.assertHoverContains("retry_delay", "how long to wait until retrying"); } @Test public void poolResourceGetParamsReconcileAndHovers() throws Exception { Editor editor; editor = harness.newEditor( "resources:\n" + "- name: my-locks\n" + " type: pool\n" + "jobs:\n" + "- name: a-job\n" + " plan:\n" + " - get: my-locks\n" + " params:\n" + " no-params-expected: bad" ); editor.assertProblems( "no-params-expected|Unknown property" ); } @Test public void poolResourcePutParamsReconcileAndHovers() throws Exception { Editor editor; editor = harness.newEditor( "resources:\n" + "- name: my-locks\n" + " type: pool\n" + "jobs:\n" + "- name: a-job\n" + " plan:\n" + " - put: my-locks\n" + " params:\n" + " acquire: should-acquire\n" + " claim: a-specific-lock\n" + " release: path/to/lock\n" + " add: path/to/lock\n" + " add_claimed: path/to/lock\n" + " remove: path/to/lock" ); editor.assertProblems( "acquire|Only one of", "should-acquire|'boolean'", "claim|Only one of", "release|Only one of", "add|Only one of", "add_claimed|Only one of", "remove|Only one of" ); editor.assertHoverContains("acquire", "attempt to move a randomly chosen lock"); editor.assertHoverContains("claim", "the specified lock from the pool will be acquired"); editor.assertHoverContains("release", "release the lock"); editor.assertHoverContains("add", "add a new lock to the pool in the unclaimed state"); editor.assertHoverContains("add_claimed", "in the *claimed* state"); editor.assertHoverContains("remove", "remove the given lock from the pool"); } @Test public void semverResourceSourceReconcileAtomNotAllowed() throws Exception { Editor editor = harness.newEditor( "resources:\n" + "- name: version\n" + " type: semver\n" + " source: an-atom" ); editor.assertProblems("an-atom|Expecting a 'Map'"); } @Test public void semverResourceSourceReconcileRequiredProps() throws Exception { Editor editor; //required props for s3 driver editor = harness.newEditor( "resources:\n" + "- name: version\n" + " type: semver\n" + " source:\n" + " driver: s3" ); editor.assertProblems( "source|[access_key_id, bucket, key, secret_access_key] are required" ); editor = harness.newEditor( "resources:\n" + "- name: version\n" + " type: semver\n" + " source: {}" ); editor.assertProblems( "source|[access_key_id, bucket, key, secret_access_key] are required" ); // required props for git driver editor = harness.newEditor( "resources:\n" + "- name: version\n" + " type: semver\n" + " source:\n" + " driver: git" ); editor.assertProblems( "source|[branch, file, uri] are required" ); //required props for swift driver editor = harness.newEditor( "resources:\n" + "- name: version\n" + " type: semver\n" + " source:\n" + " driver: swift" ); editor.assertProblems( "source|'openstack' is required" ); } @Test public void semverResourceSourceBadDriver() throws Exception { Editor editor = harness.newEditor( "resources:\n" + "- name: version\n" + " type: semver\n" + " source:\n" + " driver: bad-driver" ); editor.assertProblems("bad-driver|'SemverDriver'"); } @Test public void semverGitResourceSourceContentAssist() throws Exception { String conText = "resources:\n" + "- name: version\n" + " type: semver\n" + " source:\n" + "<*>"; assertContextualCompletions(conText, " driver: git\n" + " <*>" , // ==> " driver: git\n" + " branch: <*>" , " driver: git\n" + " file: <*>" , " driver: git\n" + " git_user: <*>" , " driver: git\n" + " initial_version: <*>" , " driver: git\n" + " password: <*>" , " driver: git\n" + " private_key: <*>" , " driver: git\n" + " uri: <*>" , " driver: git\n" + " username: <*>" , " driver: git<*>" ); } @Test public void semverGitResourceSourceReconcileAndHovers() throws Exception { Editor editor; // required props for git driver editor = harness.newEditor( "resources:\n" + "- name: version\n" + " type: semver\n" + " source:\n" + " initial_version: not-a-version\n" + //TODO: should be marked as a error but isn't yet. " driver: git\n" + " uri: [email protected]:concourse/concourse.git\n" + " branch: version\n" + " file: version\n" + " private_key: {{concourse-repo-private-key}}\n" + " username: jsmith\n" + " password: s3cre$t\n" + " git_user: [email protected]\n" + " bogus: bad" ); editor.assertProblems( "bogus|Unknown property" ); editor.assertHoverContains("initial_version", "version number to use when bootstrapping"); editor.assertHoverContains("driver", "The driver to use"); editor.assertHoverContains("uri", "The repository URL"); editor.assertHoverContains("branch", "The branch the file lives on"); editor.assertHoverContains("file", "The name of the file"); editor.assertHoverContains("private_key", "The SSH private key"); editor.assertHoverContains("username", "Username for HTTP(S) auth"); editor.assertHoverContains("password", "Password for HTTP(S) auth"); editor.assertHoverContains("git_user", "The git identity to use"); } @Test public void semverS3ResourceSourceReconcileAndHovers() throws Exception { Editor editor; //without explicit 'driver'... should assume s3 by default editor = harness.newEditor( "resources:\n" + "- name: version\n" + " type: semver\n" + " source:\n" + " initial_version: 1.2.3\n" + " bucket: the-bucket\n" + " key: object-key\n" + " access_key_id: aws-access-key\n" + " secret_access_key: aws-access-key\n" + " region_name: bogus-region\n" + " endpoint: https://blah.com/blah\n" + " disable_ssl: no-use-ssl\n" + " bogus-prop: bad" ); editor.assertProblems( "bogus-region|'S3Region'", "no-use-ssl|'boolean'", "bogus-prop|Unknown property" ); //with explicit 'driver: s3' editor = harness.newEditor( "resources:\n" + "- name: version\n" + " type: semver\n" + " source:\n" + " initial_version: 1.2.3\n" + " driver: s3\n" + " bucket: the-bucket\n" + " key: object-key\n" + " access_key_id: aws-access-key\n" + " secret_access_key: aws-access-key\n" + " region_name: bogus-region\n" + " endpoint: https://blah.com/blah\n" + " disable_ssl: no-use-ssl\n" + " bogus-prop: bad" ); editor.assertProblems( "bogus-region|'S3Region'", "no-use-ssl|'boolean'", "bogus-prop|Unknown property" ); editor.assertHoverContains("initial_version", "version number to use when bootstrapping"); editor.assertHoverContains("driver", "The driver to use"); editor.assertHoverContains("bucket", "The name of the bucket"); editor.assertHoverContains("key", "The key to use for the object"); editor.assertHoverContains("access_key_id", "The AWS access key to"); editor.assertHoverContains("secret_access_key", "The AWS secret key to"); editor.assertHoverContains("region_name", "The region the bucket is in"); editor.assertHoverContains("endpoint", "Custom endpoint for using S3"); editor.assertHoverContains("disable_ssl", "Disable SSL for the endpoint"); } @Test public void semverSwiftResourceSourceReconcileAndHovers() throws Exception { Editor editor = harness.newEditor( "resources:\n" + "- name: version\n" + " type: semver\n" + " source:\n" + " initial_version: 1.2.3\n" + " driver: swift\n" + " openstack:\n" + " container: nice-container\n" + " item_name: flubber-blub\n" + " region_name: us-west-1\n" ); editor.assertProblems(/*NONE*/); editor.assertHoverContains("openstack", "All openstack configuration"); } @Test public void semverResourceGetParamsReconcileAndHovers() throws Exception { Editor editor = harness.newEditor( "resources:\n" + "- name: version\n" + " type: semver\n" + " source:\n" + " initial_version: 1.2.3\n" + " driver: swift\n" + " openstack: whatever\n" + "jobs:\n" + "- name: a-job\n" + " plan:\n" + " - get: version\n" + " params:\n" + " bump: what-to-bump\n" + " pre: beta\n" + " bogus: bad\n" ); editor.assertProblems( "what-to-bump|[final, major, minor, patch]", "bogus|Unknown property" ); editor.assertHoverContains("bump", "Bump the version number"); editor.assertHoverContains("pre", "bump to a prerelease"); } @Test public void semverPutParamsReconcileAndHovers() throws Exception { Editor editor = harness.newEditor( "resources:\n" + "- name: version\n" + " type: semver\n" + " source:\n" + " initial_version: 1.2.3\n" + " driver: swift\n" + " openstack: whatever\n" + "jobs:\n" + "- name: a-job\n" + " plan:\n" + " - put: version\n" + " params:\n" + " file: version-file\n" + " bump: what-to-bump\n" + " pre: alpha\n" + " bogus-one: bad\n" + " get_params:\n" + " file: not-expected-here\n" + " bump: what-to-get-bump\n" + " pre: beta\n" + " bogus-two: bad\n" ); editor.assertProblems( "what-to-bump|[final, major, minor, patch]", "bogus-one|Unknown property", "file|Unknown property", "what-to-get-bump|[final, major, minor, patch]", "bogus-two|Unknown property" ); editor.assertHoverContains("file", 1, "Path to a file containing the version number"); editor.assertHoverContains("bump", 1, "Bump the version number"); editor.assertHoverContains("bump", 2, "Bump the version number"); editor.assertHoverContains("pre", 1, "bump to a prerelease"); editor.assertHoverContains("pre", 2, "bump to a prerelease"); } @Test public void reconcileExplicitResourceAttributeInPutStep() throws Exception { //See: https://www.pivotaltracker.com/story/show/138568839 Editor editor; editor = harness.newEditor( "resources:\n" + "- name: aws-environments\n" + " type: pool\n" + "jobs:\n" + "- name: test-multi-aws\n" + " plan:\n" + " - put: environment-1\n" + " resource: aws-environments\n" + " params:\n" + " acquire: true\n" + " bogus_param: bad\n" + " get_params:\n" + " bogus_get_param: bad" ); editor.assertProblems( "bogus_param|Unknown property", "bogus_get_param|Unknown property" ); editor = harness.newEditor( "resources:\n" + "- name: aws-environments\n" + " type: pool\n" + "jobs:\n" + "- name: test-multi-aws\n" + " plan:\n" + " - get: environment-1\n" + " resource: aws-environments\n" + " params:\n" + " bogus_param: bad\n" ); editor.assertProblems( "bogus_param|Unknown property" ); editor = harness.newEditor( "resources:\n" + "- name: aws-environments\n" + " type: pool\n" + " source:\n" + " uri: [email protected]:concourse/locks.git\n" + " branch: master\n" + " pool: aws\n" + " private_key: |\n" + " -----BEGIN RSA PRIVATE KEY-----\n" + " MIIEowIBAAKCAQEAtCS10/f7W7lkQaSgD/mVeaSOvSF9ql4hf/zfMwfVGgHWjj+W\n" + " ...\n" + " DWiJL+OFeg9kawcUL6hQ8JeXPhlImG6RTUffma9+iGQyyBMCGd1l\n" + " -----END RSA PRIVATE KEY-----\n" + " username: jonhsmith\n" + " password: his-password\n" + " retry_delay: 10s\n" + "jobs:\n" + "- name: test-multi-aws\n" + " plan:\n" + " - get: aws-environments\n" + " params: {} \n" + " - put: environment-1\n" + " resource: aws-environments\n" + " params: {acquire: true}\n" + " - put: environment-2\n" + " resource: aws-environments\n" + " params: \n" + " acquire: true\n" + " bogus_param: blah\n" + " - task: test-multi-aws\n" + " file: my-scripts/test-multi-aws.yml\n" + " - put: aws-environments\n" + " params: {release: environment-1}\n" + " - put: aws-environments\n" + " params: {release: environment-2}" ); editor.assertProblems( "bogus_param|Unknown property" ); } @Test public void resourceNameContentAssist() throws Exception { String conText; conText = "resources:\n" + "- name: foo-resource\n" + "- name: bar-resource\n" + "- name: other-resource\n" + "jobs:\n" + "- name: test-multi-aws\n" + " plan:\n" + " - <*>"; assertContextualCompletions(conText , // ============== "get: <*>" , "get: bar-resource<*>", "get: foo-resource<*>", "get: other-resource<*>" ); assertContextualCompletions(conText , // ============== "put: <*>" , // ==> "put: bar-resource<*>", "put: foo-resource<*>", "put: other-resource<*>" ); conText = "resources:\n" + "- name: foo-resource\n" + "- name: bar-resource\n" + "- name: other-resource\n" + "jobs:\n" + "- name: test-multi-aws\n" + " plan:\n" + " - put: something\n" + " <*>"; assertContextualCompletions(conText , // ============== "resource: <*>" , // ==> "resource: bar-resource<*>", "resource: foo-resource<*>", "resource: other-resource<*>" ); conText = "resources:\n" + "- name: foo-resource\n" + "- name: bar-resource\n" + "- name: other-resource\n" + "jobs:\n" + "- name: test-multi-aws\n" + " plan:\n" + " - <*>\n" + " resource: foo-resource\n"; // presence of explicit 'resource' attribute should disable treating the name in put/get as a resource-name assertContextualCompletions(conText, "put: <*>" // ==> NONE ); assertContextualCompletions(conText, "get: <*>" // ==> NONE ); } @Test public void gotoResourceDefinition() throws Exception { Editor editor = harness.newEditor( "resources:\n" + "- name: my-git\n" + " type: git\n" + "- name: build-env\n" + " type: docker-image\n" + "jobs:\n" + "- name: do-stuff\n" + " plan:\n" + " - get: my-git\n" + " params:\n" + " rootfs: true\n" + " save: true\n" + " - put: build-env\n" + " build: my-git/docker\n" ); editor.assertGotoDefinition(editor.positionOf("get: my-git", "my-git"), editor.rangeOf("- name: my-git", "my-git") ); } @Test public void gotoJobDefinition() throws Exception { Editor editor = harness.newEditor( "resources:\n" + "- name: my-git\n" + " type: git\n" + "jobs:\n" + "- name: prepare-stuff\n" + " plan:\n" + " - get: my-git\n" + " - task: preparations\n" + " file: my-git/ci/tasks/preparations.yml\n" + "- name: do-stuff\n" + " plan:\n" + " - get: my-git\n" + " passed:\n" + " - prepare-stuff\n" ); editor.assertGotoDefinition(editor.positionOf("- prepare-stuff", "prepare-stuff"), editor.rangeOf("- name: prepare-stuff", "prepare-stuff") ); } @Test public void gotoResourceTypeDefinition() throws Exception { Editor editor = harness.newEditor( "resource_types:\n" + "- name: slack-notification\n" + " type: docker_image\n" + "resources:\n" + "- name: zazazee\n" + " type: slack-notification\n" ); editor.assertGotoDefinition(editor.positionOf("type: slack-notification", "slack-notification"), editor.rangeOf("- name: slack-notification", "slack-notification") ); } @Test public void reconcileResourceTypeNames() throws Exception { String userDefinedResourceTypesSnippet = "resource_types:\n" + "- name: s3-multi\n" + " type: docker-image\n" + " source:\n" + " repository: kdvolder/s3-resource-simple\n" + "- name: slack-notification\n" + " type: docker-image\n" + " source:\n" + " repository: cfcommunity/slack-notification-resource\n" + " tag: latest\n"; String[] goodNames = { //user-defined: "s3-multi", "slack-notification", //built-in: "git", "hg", "time", "s3", "archive", "semver", "github-release", "docker-image", "tracker", "pool", "cf", "bosh-io-release", "bosh-io-stemcell", "bosh-deployment", "vagrant-cloud" }; String[] badNames = { "bogus", "wrong", "not-defined-resource-type" }; //All the bad names are detected and flagged: for (String badName : badNames) { Editor editor = harness.newEditor( userDefinedResourceTypesSnippet + "resources:\n" + "- name: the-resource\n" + " type: "+badName ); editor.assertProblems(badName+"|Resource Type does not exist"); } //All the good names are accepted: for (String goodName : goodNames) { Editor editor = harness.newEditor( userDefinedResourceTypesSnippet + "resources:\n" + "- name: the-resource\n" + " type: "+goodName ); editor.assertProblems(/*None*/); } } @Test public void contentAssistResourceTypeNames() throws Exception { String[] goodNames = { //user-defined: "s3-multi", "slack-notification", //built-in: "git", "hg", "time", "s3", "archive", "semver", "github-release", "docker-image", "tracker", "pool", "cf", "bosh-io-release", "bosh-io-stemcell", "bosh-deployment", "vagrant-cloud" }; Arrays.sort(goodNames); String context = "resource_types:\n" + "- name: s3-multi\n" + " type: docker-image\n" + " source:\n" + " repository: kdvolder/s3-resource-simple\n" + "- name: slack-notification\n" + " type: docker-image\n" + " source:\n" + " repository: cfcommunity/slack-notification-resource\n" + " tag: latest\n" + "resources:\n" + "- type: <*>"; //All the good names are accepted: String[] expectedCompletions = new String[goodNames.length]; for (int i = 0; i < expectedCompletions.length; i++) { expectedCompletions[i] = goodNames[i] +"<*>"; } assertContextualCompletions(context, "<*>" , // ===> expectedCompletions ); } @Test public void reconcileTaskFileToplevelProperties() throws Exception { Editor editor; editor = harness.newEditor(LanguageIds.CONCOURSE_TASK, "image: some-image" ); editor.assertProblems("image: some-image|[platform, run] are required"); editor = harness.newEditor(LanguageIds.CONCOURSE_TASK, "platform: a-platform\n" + "image_resource:\n" + " name: should-not-be-here\n" + " type: docker-image\n" + " source:\n" + " bogus-source-prop: bad\n" + " repository: ruby\n" + " tag: '2.1'\n" + "image: some-image\n" + "inputs:\n" + "- path: path/to/input\n" + "outputs:\n" + "- path: path/to/output\n" + "run:\n" + " path: my-app/scripts/test\n" + "params: the-params\n" ); editor.assertProblems( "image_resource|Only one of [image_resource, image] should be defined", "name|Unknown property", "bogus-source-prop|Unknown property", "image|Only one of [image_resource, image] should be defined", "-^ path: path/to/input|'name' is required", "-^ path: path/to/output|'name' is required", "the-params|Expecting a 'Map'" ); } @Test public void contentAssistTaskFileToplevelProperties() throws Exception { assertTaskCompletions( "<*>" , // ==> "image: <*>" , "image_resource:\n" + " <*>" , "inputs:\n" + "- <*>" , "outputs:\n" + "- <*>" , "params:\n" + " <*>" , "platform: <*>" , "run:\n" + " <*>" ); assertTaskCompletions( "platform: <*>" , //=> "platform: darwin<*>", "platform: linux<*>", "platform: windows<*>" ); } @Test public void hoversForTaskFileToplevelProperties() throws Exception { Editor editor = harness.newEditor(LanguageIds.CONCOURSE_TASK, "image: some-image\n" + "image_resource:\n" + " type: docker-image\n" + " source:\n" + " repository: kdvolder/sts4-build-env\n" + "inputs: []\n" + "outputs: []\n" + "params: {}\n" + "platform: linux\n" + "run:\n" + " path: sts4/concourse/tasks/build-vscode-extensions.sh" ); editor.assertHoverContains("platform", "The platform the task should run on"); editor.assertHoverContains("image_resource", "The base image of the container"); editor.assertHoverContains("image", "A string specifying the rootfs of the container"); editor.assertHoverContains("inputs", "The expected set of inputs for the task"); editor.assertHoverContains("outputs", "The artifacts produced by the task"); editor.assertHoverContains("run", "Note that this is *not* provided as a script blob"); editor.assertHoverContains("params", "A key-value mapping of values that are exposed to the task via environment variables"); editor.assertHoverContains("repository", "The name of the repository"); editor.assertHoverContains("platform", "The platform the task should run on"); } @Test public void reconcileEmbeddedTaskConfig() throws Exception { Editor editor = harness.newEditor( "jobs:\n" + "- name: foo\n" + " plan:\n" + " - task: the-task\n" + " config:\n" + " platform: a-platform\n" + " image_resource:\n" + " name: should-not-be-here\n" + " type: docker-image\n" + " source:\n" + " bogus-source-prop: bad\n" + " repository: ruby\n" + " tag: '2.1'\n" + " image: some-image\n" + " inputs:\n" + " - path: path/to/input\n" + " outputs:\n" + " - path: path/to/output\n" + " run:\n" + " path: my-app/scripts/test\n" + " params: the-params" ); editor.assertProblems( "image_resource|Only one of [image_resource, image] should be defined", "name|Unknown property", "bogus-source-prop|Unknown property", "image|Only one of [image_resource, image] should be defined", "-^ path: path/to/input|'name' is required", "-^ path: path/to/output|'name' is required", "the-params|Expecting a 'Map'" ); } @Test public void taskRunPropertiesValidationAndHovers() throws Exception { Editor editor; editor = harness.newEditor(LanguageIds.CONCOURSE_TASK, "inputs:\n" + "- name: sts4\n" + "outputs:\n" + "- name: vsix-files\n" + "platform: linux\n" + "image_resource:\n" + " type: docker-image\n" + " source:\n" + " repository: kdvolder/sts4-build-env\n" + "run:\n" + " path: sts4/concourse/tasks/build-vscode-extensions.sh\n" + " args: the-args\n" + " user: admin\n" + " dir: the-dir\n" + " bogus: bad\n" ); editor.assertProblems( "the-args|Expecting a 'Sequence'", "bogus|Unknown property" ); editor.assertHoverContains("path", "The command to execute, relative to the task's working directory"); editor.assertHoverContains("args", "Arguments to pass to the command"); editor.assertHoverContains("dir", "A directory, relative to the initial working directory, to set as the working directory"); editor.assertHoverContains("user", "Explicitly set the user to run as"); editor = harness.newEditor(LanguageIds.CONCOURSE_TASK, "inputs:\n" + "- name: sts4\n" + "outputs:\n" + "- name: vsix-files\n" + "platform: linux\n" + "image_resource:\n" + " type: docker-image\n" + " source:\n" + " repository: kdvolder/sts4-build-env\n" + "run:\n" + " user: admin\n" ); editor.assertProblems("run|'path' is required"); } @Test public void nameAndPathHoversInTaskInputsAndOutputs() throws Exception { Editor editor = harness.newEditor(LanguageIds.CONCOURSE_TASK, "inputs:\n" + "- name: sts4\n" + " path: botk\n" + "outputs:\n" + "- name: vsix-files\n" + " path: zaza" ); editor.assertHoverContains("name", 1, "The logical name of the input"); editor.assertHoverContains("name", 2, "The logical name of the output"); editor.assertHoverContains("path", 1, "The path where the input will be placed"); editor.assertHoverContains("path", 2, "The path to a directory where the output will be taken from"); } @Test public void PT_140711495_triple_dash_at_start_of_file_disrupts_content_assist() throws Exception { assertContextualCompletions( "#leading comment\n" + "---\n" + "resources:\n" + "- name: my-repo\n" + " type: git\n" + " source:\n" + " uri: https://github.com/spring-projects/sts4.git\n" + " <*>" , // ================== "bra<*>" , // ==> "branch: <*>" ); assertContextualCompletions( "---\n" + "resources:\n" + "- name: my-repo\n" + " type: git\n" + " source:\n" + " uri: https://github.com/spring-projects/sts4.git\n" + " <*>" , // ================== "bra<*>" , // ==> "branch: <*>" ); assertContextualCompletions( // "---\n" + "resources:\n" + "- name: my-repo\n" + " type: git\n" + " source:\n" + " uri: https://github.com/spring-projects/sts4.git\n" + " <*>" , // ================== "bra<*>" , // ==> "branch: <*>" ); } @Test public void PT_141050891_language_server_crashes_on_CA_before_first_document_marker() throws Exception { Editor editor = harness.newEditor( "%Y<*>\n" + "#leading comment\n" + "---\n" + "resources:\n" + "- name: my-repo\n" + " type: git\n" + " source:\n" + " uri: https://github.com/spring-projects/sts4.git\n" + " <*>" ); //We don't expect completions, but this should at least not crash! editor.assertCompletions(/*NONE*/); } @Test public void resourceInEmbeddedTaskConfigNotRequiredIfSpecifiedInTask() throws Exception { Editor editor; editor = harness.newEditor( "resources:\n" + "- name: docker-image\n" + " type: docker-image\n" + " source:\n" + " username: {{docker_hub_username}}\n" + " password: {{docker_hub_password}}\n" + " repository: kdvolder/sts3-build-env\n" + "jobs:\n" + "- name: build-commons-update-site\n" + " plan:\n" + " - task: hello-world\n" + " image: docker-image\n" + //Given here! So not required in config! " config:\n" + " inputs:\n" + " - name: commons-git\n" + " platform: linux\n" + " run:\n" + " path: which\n" + " args:\n" + " - mvn" ); editor.assertProblems(/*none*/); editor = harness.newEditor( "resources:\n" + "- name: docker-image\n" + " type: docker-image\n" + " source:\n" + " username: {{docker_hub_username}}\n" + " password: {{docker_hub_password}}\n" + " repository: kdvolder/sts3-build-env\n" + "jobs:\n" + "- name: build-commons-update-site\n" + " plan:\n" + " - task: hello-world\n" + " config:\n" + " inputs:\n" + " - name: commons-git\n" + " platform: linux\n" + " run:\n" + " path: which\n" + " args:\n" + " - mvn" ); editor.assertProblems( "config|One of [image_resource, image] is required" ); } @Test public void resourceInTaskConfigFileNotRequired() throws Exception { Editor editor = harness.newEditor(LanguageIds.CONCOURSE_TASK, "inputs:\n" + "- name: commons-git\n" + "platform: linux\n" + "run:\n" + " path: which\n" + " args:\n" + " - mvn" ); editor.assertProblems(/*NONE*/); } @Test public void resourceInEmbeddedTaskConfigDeprecated() throws Exception { Editor editor = harness.newEditor( "resources:\n" + "- name: my-docker-image\n" + " type: docker-image\n" + " source:\n" + " username: {{docker_hub_username}}\n" + " password: {{docker_hub_password}}\n" + " repository: kdvolder/sts3-build-env\n" + "jobs:\n" + "- name: build-commons-update-site\n" + " plan:\n" + " - task: hello-world\n" + " image: my-docker-image\n" + " config:\n" + " image: blah\n" + " image_resource:\n" + " type: docker-image\n" + " inputs:\n" + " - name: commons-git\n" + " platform: linux\n" + " run:\n" + " path: which\n" + " args:\n" + " - mvn" ); List<Diagnostic> problems = editor.assertProblems( "image|Deprecated", "image_resource|Deprecated" ); for (Diagnostic d : problems) { assertEquals(DiagnosticSeverity.Warning, d.getSeverity()); } } @Test public void relaxedIndentContextMoreSpaces() throws Exception { Editor editor; editor = harness.newEditor( "resources:\n" + "- name: foo\n" + " type: git\n" + " source:\n" + " <*>" ); editor.assertCompletionLabels( //For the 'exact' context: "check_every", "name", "source", "type", //For the nested context: "➔ branch", "➔ commit_verification_key_ids", "➔ commit_verification_keys", "➔ disable_ci_skip", "➔ git_config", "➔ gpg_keyserver", "➔ ignore_paths", "➔ password", "➔ paths", "➔ private_key", "➔ skip_ssl_verification", "➔ tag_filter", "➔ uri", "➔ username" ); editor.assertCompletionWithLabel("check_every", "resources:\n" + "- name: foo\n" + " type: git\n" + " source:\n" + " check_every: <*>" ); editor.assertCompletionWithLabel("➔ branch", "resources:\n" + "- name: foo\n" + " type: git\n" + " source:\n" + " branch: <*>" ); editor.assertCompletionWithLabel("➔ commit_verification_key_ids", "resources:\n" + "- name: foo\n" + " type: git\n" + " source:\n" + " commit_verification_key_ids:\n" + " - <*>" ); } @Test public void relaxedIndentContextMoreSpaces2() throws Exception { assertContextualCompletions( "resources:\n" + "- name: foo\n" + " type: git\n" + " source:\n" + " <*>" , // ========= "bra<*>" , //=> " branch: <*>" ); assertContextualCompletions( "resources:\n" + "- name: foo\n" + " type: git\n" + " source:\n" + " <*>" , // ========= "comverids<*>" , //=> " commit_verification_key_ids:\n" + " - <*>" ); } @Test public void relaxedIndentContextMoreSpaces3() throws Exception { Editor editor = harness.newEditor( "jobs:\n" + "- name: job-hello-world\n" + " public: true\n" + " plan:\n" + " - get: resource-tutorial\n" + " - task: hello-world\n" + " <*>" ); editor.assertCompletionLabels( //completions for current (i.e Job) context: "build_logs_to_retain", "disable_manual_trigger", "max_in_flight", "serial", "serial_groups", "name", "plan", "public", //Completions for nested context (i.e. task step) "➔ attempts", "➔ config", "➔ ensure", "➔ file", "➔ image", "➔ input_mapping", "➔ on_failure", "➔ on_success", "➔ output_mapping", "➔ params", "➔ privileged", "➔ tags", "➔ task", "➔ timeout" ); } ////////////////////////////////////////////////////////////////////////////// private void assertContextualCompletions(String conText, String textBefore, String... textAfter) throws Exception { Editor editor = harness.newEditor(conText); editor.reconcile(); //this ensures the conText is parsed and its AST is cached (will be used for //dynamic CA when the conText + textBefore is not parsable. assertContains(CURSOR, conText); textBefore = conText.replace(CURSOR, textBefore); textAfter = Arrays.stream(textAfter) .map((String t) -> conText.replace(CURSOR, t)) .collect(Collectors.toList()).toArray(new String[0]); editor.setText(textBefore); editor.assertCompletions(textAfter); } private void assertCompletions(String textBefore, String... textAfter) throws Exception { Editor editor = harness.newEditor(textBefore); editor.assertCompletions(textAfter); } private void assertTaskCompletions(String textBefore, String... textAfter) throws Exception { Editor editor = harness.newEditor(LanguageIds.CONCOURSE_TASK, textBefore); editor.assertCompletions(textAfter); } }
Fix failing test
vscode-extensions/vscode-concourse/src/test/java/org/springframework/ide/vscode/concourse/ConcourseEditorTest.java
Fix failing test
Java
agpl-3.0
966801af450ddb8123d5be138387889d420d9dfe
0
qiuyesuifeng/sql-layer,wfxiang08/sql-layer-1,qiuyesuifeng/sql-layer,ngaut/sql-layer,relateiq/sql-layer,shunwang/sql-layer-1,ngaut/sql-layer,relateiq/sql-layer,jaytaylor/sql-layer,shunwang/sql-layer-1,relateiq/sql-layer,relateiq/sql-layer,jaytaylor/sql-layer,shunwang/sql-layer-1,wfxiang08/sql-layer-1,wfxiang08/sql-layer-1,shunwang/sql-layer-1,ngaut/sql-layer,qiuyesuifeng/sql-layer,jaytaylor/sql-layer,ngaut/sql-layer,qiuyesuifeng/sql-layer,jaytaylor/sql-layer,wfxiang08/sql-layer-1
/** * END USER LICENSE AGREEMENT (“EULA”) * * READ THIS AGREEMENT CAREFULLY (date: 9/13/2011): * http://www.akiban.com/licensing/20110913 * * BY INSTALLING OR USING ALL OR ANY PORTION OF THE SOFTWARE, YOU ARE ACCEPTING * ALL OF THE TERMS AND CONDITIONS OF THIS AGREEMENT. YOU AGREE THAT THIS * AGREEMENT IS ENFORCEABLE LIKE ANY WRITTEN AGREEMENT SIGNED BY YOU. * * IF YOU HAVE PAID A LICENSE FEE FOR USE OF THE SOFTWARE AND DO NOT AGREE TO * THESE TERMS, YOU MAY RETURN THE SOFTWARE FOR A FULL REFUND PROVIDED YOU (A) DO * NOT USE THE SOFTWARE AND (B) RETURN THE SOFTWARE WITHIN THIRTY (30) DAYS OF * YOUR INITIAL PURCHASE. * * IF YOU WISH TO USE THE SOFTWARE AS AN EMPLOYEE, CONTRACTOR, OR AGENT OF A * CORPORATION, PARTNERSHIP OR SIMILAR ENTITY, THEN YOU MUST BE AUTHORIZED TO SIGN * FOR AND BIND THE ENTITY IN ORDER TO ACCEPT THE TERMS OF THIS AGREEMENT. THE * LICENSES GRANTED UNDER THIS AGREEMENT ARE EXPRESSLY CONDITIONED UPON ACCEPTANCE * BY SUCH AUTHORIZED PERSONNEL. * * IF YOU HAVE ENTERED INTO A SEPARATE WRITTEN LICENSE AGREEMENT WITH AKIBAN FOR * USE OF THE SOFTWARE, THE TERMS AND CONDITIONS OF SUCH OTHER AGREEMENT SHALL * PREVAIL OVER ANY CONFLICTING TERMS OR CONDITIONS IN THIS AGREEMENT. */ package com.akiban.ais.model; import com.akiban.server.geophile.Space; import com.akiban.server.error.InvalidArgumentTypeException; import java.math.BigInteger; public class SpaceHelper { /** Given the types of latitude and longitude decimal columns, return an appropriate * {@link Space}. */ public static Space latLon(Column latCol, Column lonCol) { long latScale, lonScale; if (latCol.getType() == Types.INT) latScale = 1; else if (latCol.getType() == Types.DECIMAL) latScale = BigInteger.TEN.pow(latCol.getTypeParameter2().intValue()).longValue(); else throw new InvalidArgumentTypeException("Latitude must be DECIMAL or INT"); if (lonCol.getType() == Types.INT) lonScale = 1; else if (lonCol.getType() == Types.DECIMAL) lonScale = BigInteger.TEN.pow(lonCol.getTypeParameter2().intValue()).longValue(); else throw new InvalidArgumentTypeException("Longitude must be DECIMAL or INT"); // TODO: Maybe there should be subclasses of Space for // different coordinate systems? // Latitude is actually -90 - +90 or 0 - 180, but dims apparently have to be the same. // Jack says that's because I let the third argument default. return new Space(new long[] { -180 * latScale, -180 * lonScale }, new long[] { 180 * latScale, 180 * lonScale }); } private SpaceHelper() { } }
src/main/java/com/akiban/ais/model/SpaceHelper.java
/** * END USER LICENSE AGREEMENT (“EULA”) * * READ THIS AGREEMENT CAREFULLY (date: 9/13/2011): * http://www.akiban.com/licensing/20110913 * * BY INSTALLING OR USING ALL OR ANY PORTION OF THE SOFTWARE, YOU ARE ACCEPTING * ALL OF THE TERMS AND CONDITIONS OF THIS AGREEMENT. YOU AGREE THAT THIS * AGREEMENT IS ENFORCEABLE LIKE ANY WRITTEN AGREEMENT SIGNED BY YOU. * * IF YOU HAVE PAID A LICENSE FEE FOR USE OF THE SOFTWARE AND DO NOT AGREE TO * THESE TERMS, YOU MAY RETURN THE SOFTWARE FOR A FULL REFUND PROVIDED YOU (A) DO * NOT USE THE SOFTWARE AND (B) RETURN THE SOFTWARE WITHIN THIRTY (30) DAYS OF * YOUR INITIAL PURCHASE. * * IF YOU WISH TO USE THE SOFTWARE AS AN EMPLOYEE, CONTRACTOR, OR AGENT OF A * CORPORATION, PARTNERSHIP OR SIMILAR ENTITY, THEN YOU MUST BE AUTHORIZED TO SIGN * FOR AND BIND THE ENTITY IN ORDER TO ACCEPT THE TERMS OF THIS AGREEMENT. THE * LICENSES GRANTED UNDER THIS AGREEMENT ARE EXPRESSLY CONDITIONED UPON ACCEPTANCE * BY SUCH AUTHORIZED PERSONNEL. * * IF YOU HAVE ENTERED INTO A SEPARATE WRITTEN LICENSE AGREEMENT WITH AKIBAN FOR * USE OF THE SOFTWARE, THE TERMS AND CONDITIONS OF SUCH OTHER AGREEMENT SHALL * PREVAIL OVER ANY CONFLICTING TERMS OR CONDITIONS IN THIS AGREEMENT. */ package com.akiban.ais.model; import com.akiban.server.geophile.Space; import com.akiban.server.error.InvalidArgumentTypeException; import java.math.BigInteger; public class SpaceHelper { /** Given the types of latitude and longitude decimal columns, return an appropriate * {@link Space}. */ public static Space latLon(Column latCol, Column lonCol) { if ((latCol.getType() != Types.DECIMAL) || (lonCol.getType() != Types.DECIMAL)) { throw new InvalidArgumentTypeException("Columns must both be DECIMAL"); } long latScale = BigInteger.TEN.pow(latCol.getTypeParameter2().intValue()).longValue(); long lonScale = BigInteger.TEN.pow(lonCol.getTypeParameter2().intValue()).longValue(); // TODO: Maybe there should be subclasses of Space for // different coordinate systems? // Latitude is actually -90 - +90 or 0 - 180, but dims apparently have to be the same. return new Space(new long[] { 0, 0 }, new long[] { 360 * latScale, 360 * lonScale }); } private SpaceHelper() { } }
Allow INT as well as DECIMAL for now.
src/main/java/com/akiban/ais/model/SpaceHelper.java
Allow INT as well as DECIMAL for now.
Java
lgpl-2.1
3680ad9167d76dec34426191c0e29a4c39db3f18
0
gytis/narayana,gytis/narayana,mmusgrov/narayana,jbosstm/narayana,gytis/narayana,mmusgrov/narayana,tomjenkinson/narayana,jbosstm/narayana,gytis/narayana,mmusgrov/narayana,tomjenkinson/narayana,gytis/narayana,tomjenkinson/narayana,jbosstm/narayana,gytis/narayana,mmusgrov/narayana,jbosstm/narayana,tomjenkinson/narayana
/* * Copyright 2013, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. * See the copyright.txt in the distribution for a * full listing of individual contributors. * This copyrighted material is made available to anyone wishing to use, * modify, copy, or redistribute it subject to the terms and conditions * of the GNU Lesser General Public License, v. 2.1. * This program is distributed in the hope that it will be useful, but WITHOUT A * 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, * v.2.1 along with this distribution; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. * * (C) 2013 * @author JBoss Inc. */ package com.arjuna.ats.internal.jta.recovery.arjunacore; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.sql.DataSource; import javax.transaction.xa.Xid; import com.arjuna.ats.arjuna.AtomicAction; import com.arjuna.ats.arjuna.common.Uid; import com.arjuna.ats.arjuna.coordinator.ActionStatus; import com.arjuna.ats.arjuna.exceptions.ObjectStoreException; import com.arjuna.ats.arjuna.logging.tsLogger; import com.arjuna.ats.arjuna.objectstore.ObjectStoreIterator; import com.arjuna.ats.arjuna.objectstore.RecoveryStore; import com.arjuna.ats.arjuna.objectstore.StoreManager; import com.arjuna.ats.arjuna.recovery.RecoveryModule; import com.arjuna.ats.arjuna.recovery.TransactionStatusConnectionManager; import com.arjuna.ats.arjuna.state.InputObjectState; import com.arjuna.ats.arjuna.state.OutputObjectState; import com.arjuna.ats.internal.arjuna.common.UidHelper; import com.arjuna.ats.internal.jta.xa.XID; import com.arjuna.ats.jta.common.JTAEnvironmentBean; import com.arjuna.ats.jta.xa.XidImple; import com.arjuna.common.internal.util.propertyservice.BeanPopulator; /** * This CommitMarkableResourceRecord assumes the following table has been * created: * * create table xids (xid varbinary(255), transactionManagerID varchar(255)) * (ora/syb/mysql) create table xids (xid bytea, transactionManagerID * varchar(255)) (psql) sp_configure "lock scheme",0,datarows (syb) * * The CommitMarkableResourceRecord does not support nested transactions * * TODO you have to set max_allowed_packet for large reaps on mysql */ public class CommitMarkableResourceRecordRecoveryModule implements RecoveryModule { // 'type' within the Object Store for AtomicActions. private static final String ATOMIC_ACTION_TYPE = RecoverConnectableAtomicAction.ATOMIC_ACTION_TYPE; private static final String CONNECTABLE_ATOMIC_ACTION_TYPE = RecoverConnectableAtomicAction.CONNECTABLE_ATOMIC_ACTION_TYPE; private InitialContext context; private List<String> jndiNamesToContact = new ArrayList<String>(); private Map<Xid, String> committedXidsToJndiNames = new HashMap<Xid, String>(); private List<String> queriedResourceManagers = new ArrayList<String>(); // Reference to the Object Store. private static RecoveryStore recoveryStore = null; /** * This map contains items that were in the database, we use it in phase 2 * to work out what we can GC */ private Map<String, Map<Xid, Uid>> jndiNamesToPossibleXidsForGC = new HashMap<String, Map<Xid, Uid>>(); /** * Typically the whereFilter will restrict this node to recovering the * database solely for itself but it is possible to recover for different * nodes. It uses the JTAEnvironmentBean::getXaRecoveryNodes(). */ private String whereFilter; private TransactionStatusConnectionManager transactionStatusConnectionMgr; private static JTAEnvironmentBean jtaEnvironmentBean = BeanPopulator .getDefaultInstance(JTAEnvironmentBean.class); private Map<String, String> commitMarkableResourceTableNameMap = jtaEnvironmentBean .getCommitMarkableResourceTableNameMap(); private Map<String, List<Xid>> completedBranches = new HashMap<String, List<Xid>>(); private boolean inFirstPass; private static String defaultTableName = jtaEnvironmentBean .getDefaultCommitMarkableTableName(); public CommitMarkableResourceRecordRecoveryModule() throws NamingException, ObjectStoreException { context = new InitialContext(); JTAEnvironmentBean jtaEnvironmentBean = BeanPopulator .getDefaultInstance(JTAEnvironmentBean.class); jndiNamesToContact.addAll(jtaEnvironmentBean .getCommitMarkableResourceJNDINames()); List<String> xaRecoveryNodes = jtaEnvironmentBean.getXaRecoveryNodes(); if (xaRecoveryNodes .contains(NodeNameXAResourceOrphanFilter.RECOVER_ALL_NODES)) { whereFilter = ""; } else { StringBuffer buffer = new StringBuffer(); Iterator<String> iterator = xaRecoveryNodes.iterator(); while (iterator.hasNext()) { buffer.append("\'" + iterator.next() + "\',"); } whereFilter = " where transactionManagerID in ( " + buffer.substring(0, buffer.length() - 1) + ")"; } if (recoveryStore == null) { recoveryStore = StoreManager.getRecoveryStore(); } transactionStatusConnectionMgr = new TransactionStatusConnectionManager(); } public void notifyOfCompletedBranch(String commitMarkableResourceJndiName, Xid xid) { synchronized (completedBranches) { List<Xid> completedXids = completedBranches .get(commitMarkableResourceJndiName); if (completedXids == null) { completedXids = new ArrayList<Xid>(); completedBranches.put(commitMarkableResourceJndiName, completedXids); } completedXids.add(xid); } } @Override public synchronized void periodicWorkFirstPass() { if (inFirstPass) { return; } inFirstPass = true; // TODO - this is one shot only due to a // remove in the function, if this delete fails only normal // recovery is possible Map<String, List<Xid>> completedBranches2 = new HashMap<String, List<Xid>>(); synchronized (completedBranches) { Iterator<String> iterator = completedBranches.keySet().iterator(); while (iterator.hasNext()) { String jndiName = iterator.next(); List<Xid> completedXids = completedBranches.remove(jndiName); completedBranches2.put(jndiName, completedXids); } } Iterator<String> iterator2 = completedBranches2.keySet().iterator(); while (iterator2.hasNext()) { String jndiName = iterator2.next(); List<Xid> completedXids = completedBranches2.get(jndiName); delete(jndiName, completedXids); } if (tsLogger.logger.isTraceEnabled()) { tsLogger.logger .trace("CommitMarkableResourceRecordRecoveryModule::periodicWorkFirstPass"); } this.committedXidsToJndiNames.clear(); this.queriedResourceManagers.clear(); this.jndiNamesToPossibleXidsForGC.clear(); // The algorithm occurs in three stages: // 1. We query the database to find all the branches that were committed // 3. We check for previously moved AtomicActions where the resource // manager was offline but is now online and move them back for // processing // 3. We check for in doubt AtomicActions that have incomplete branches // where the resource manager is now online and update them with the // outcome // Stage 1 // Talk to all the known resource managers that support // CommitMarkableResourceRecord to find out what transactions have // committed try { Iterator<String> iterator = jndiNamesToContact.iterator(); while (iterator.hasNext()) { String jndiName = iterator.next(); try { DataSource dataSource = (DataSource) context .lookup(jndiName); Connection connection = dataSource.getConnection(); try { Statement createStatement = connection .createStatement(); try { String tableName = commitMarkableResourceTableNameMap .get(jndiName); if (tableName == null) { tableName = defaultTableName; } ResultSet rs = createStatement .executeQuery("SELECT xid,actionuid from " + tableName + whereFilter); try { int i = 0; while (rs.next()) { i++; byte[] xidAsBytes = rs.getBytes(1); ByteArrayInputStream bais = new ByteArrayInputStream( xidAsBytes); DataInputStream dis = new DataInputStream( bais); XID _theXid = new XID(); _theXid.formatID = dis.readInt(); _theXid.gtrid_length = dis.readInt(); _theXid.bqual_length = dis.readInt(); int dataLength = dis.readInt(); _theXid.data = new byte[dataLength]; dis.read(_theXid.data, 0, dataLength); XidImple xid = new XidImple(_theXid); byte[] actionuidAsBytes = new byte[Uid.UID_SIZE]; byte[] bytes = rs.getBytes(2); System.arraycopy(bytes, 0, actionuidAsBytes, 0, bytes.length); committedXidsToJndiNames.put(xid, jndiName); if (tsLogger.logger.isTraceEnabled()) { tsLogger.logger .trace("committedXidsToJndiNames.put" + xid + " " + jndiName); } // Populate the map of possible GCable Xids Uid actionuid = new Uid(actionuidAsBytes); Map<Xid, Uid> map = jndiNamesToPossibleXidsForGC .get(jndiName); if (map == null) { map = new HashMap<Xid, Uid>(); jndiNamesToPossibleXidsForGC.put( jndiName, map); } map.put(xid, actionuid); } } finally { try { rs.close(); } catch (SQLException e) { tsLogger.logger.warn( "Could not close resultset", e); } } } finally { try { createStatement.close(); } catch (SQLException e) { tsLogger.logger.warn( "Could not close statement", e); } } queriedResourceManagers.add(jndiName); } finally { try { connection.close(); } catch (SQLException e) { tsLogger.logger.warn("Could not close connection", e); } } } catch (NamingException e) { tsLogger.logger .warn("Could not lookup CommitMarkableResource: " + jndiName); tsLogger.logger.debug( "Could not lookup CommitMarkableResource: " + jndiName, e); } catch (SQLException e) { tsLogger.logger.warn("Could not handle connection", e); } catch (IOException e) { tsLogger.logger.warn( "Could not lookup write data to select", e); } } // Stage 2 // Look in the object store for atomic actions that had a connected // resource that was not online in a previous scan but is now. // Also look for CONNECTABLE_ATOMIC_ACTION_TYPE that have a matching // ATOMIC_ACTION_TYPE and remove the CONNECTABLE_ATOMIC_ACTION_TYPE // reference try { ObjectStoreIterator transactionUidEnum = new ObjectStoreIterator( recoveryStore, CONNECTABLE_ATOMIC_ACTION_TYPE); Uid currentUid = transactionUidEnum.iterate(); while (Uid.nullUid().notEquals(currentUid)) { // Make sure it isn't garbage from a failure to move before: InputObjectState state = recoveryStore.read_committed( currentUid, ATOMIC_ACTION_TYPE); if (state != null) { if (!recoveryStore.remove_committed(currentUid, CONNECTABLE_ATOMIC_ACTION_TYPE)) { tsLogger.logger.debug("Could not remove a: " + CONNECTABLE_ATOMIC_ACTION_TYPE + " uid: " + currentUid); } } else { state = recoveryStore.read_committed(currentUid, CONNECTABLE_ATOMIC_ACTION_TYPE); // TX may have been in progress and cleaned up by now if (state != null) { RecoverConnectableAtomicAction rcaa = new RecoverConnectableAtomicAction( CONNECTABLE_ATOMIC_ACTION_TYPE, currentUid, state); if (rcaa.containsIncompleteCommitMarkableResourceRecord()) { String commitMarkableResourceJndiName = rcaa .getCommitMarkableResourceJndiName(); // Check if the resource manager is online yet if (queriedResourceManagers .contains(commitMarkableResourceJndiName)) { // If it is remove the CRR and move it back and // let // the // next stage update it moveRecord(currentUid, CONNECTABLE_ATOMIC_ACTION_TYPE, ATOMIC_ACTION_TYPE); } } } } currentUid = transactionUidEnum.iterate(); } } catch (ObjectStoreException | IOException ex) { tsLogger.logger.warn("Could not query objectstore: ", ex); } // Stage 3 // Look for crashed AtomicActions that had a // CommitMarkableResourceRecord // and see if it is in the list from stage 1, will include all // records // moved in stage 2 if (tsLogger.logger.isDebugEnabled()) { tsLogger.logger.debug("processing " + ATOMIC_ACTION_TYPE + " transactions"); } try { ObjectStoreIterator transactionUidEnum = new ObjectStoreIterator( recoveryStore, ATOMIC_ACTION_TYPE); Uid currentUid = transactionUidEnum.iterate(); while (Uid.nullUid().notEquals(currentUid)) { // Retrieve the transaction status from its // original // process. if (!isTransactionInMidFlight(transactionStatusConnectionMgr .getTransactionStatus(ATOMIC_ACTION_TYPE, currentUid))) { InputObjectState state = recoveryStore.read_committed( currentUid, ATOMIC_ACTION_TYPE); if (state != null) { // Try to load it is a BasicAction that has a // ConnectedResourceRecord RecoverConnectableAtomicAction rcaa = new RecoverConnectableAtomicAction( ATOMIC_ACTION_TYPE, currentUid, state); // Check if it did have a ConnectedResourceRecord if (rcaa.containsIncompleteCommitMarkableResourceRecord()) { String commitMarkableResourceJndiName = rcaa .getCommitMarkableResourceJndiName(); // If it did, check if the resource manager was // online if (!queriedResourceManagers .contains(commitMarkableResourceJndiName)) { // If the resource manager wasn't online, move // it moveRecord(currentUid, ATOMIC_ACTION_TYPE, CONNECTABLE_ATOMIC_ACTION_TYPE); } else { // Update the completed outcome for the 1PC // resource rcaa.updateCommitMarkableResourceRecord(committedXidsToJndiNames.get(rcaa.getXid()) != null); } } } } currentUid = transactionUidEnum.iterate(); } } catch (ObjectStoreException | IOException ex) { tsLogger.logger.warn("Could not query objectstore: ", ex); } } catch (IllegalStateException e) { // Thrown when AS is shutting down and we attempt a lookup tsLogger.logger.debug( "Could not lookup datasource, AS is shutting down: " + e.getMessage(), e); } inFirstPass = false; } @Override public synchronized void periodicWorkSecondPass() { /** * This is the list of AtomicActions that were prepared but not * completed. */ Set<Uid> preparedAtomicActions = new HashSet<Uid>(); InputObjectState aa_uids = new InputObjectState(); try { // Refresh our list of all the indoubt atomic actions if (recoveryStore.allObjUids(ATOMIC_ACTION_TYPE, aa_uids)) { preparedAtomicActions.addAll(convertToList(aa_uids)); // Refresh our list of all the indoubt connectable atomic // actions if (recoveryStore.allObjUids(CONNECTABLE_ATOMIC_ACTION_TYPE, aa_uids)) { preparedAtomicActions.addAll(convertToList(aa_uids)); // Iterate the list that we were able to contact Iterator<String> jndiNames = queriedResourceManagers .iterator(); while (jndiNames.hasNext()) { String jndiName = jndiNames.next(); List<Xid> toDelete = new ArrayList<Xid>(); Map<Xid, Uid> map = jndiNamesToPossibleXidsForGC .get(jndiName); if (map != null) { for (Map.Entry<Xid, Uid> entry : map.entrySet()) { Xid next = entry.getKey(); Uid uid = entry.getValue(); if (!preparedAtomicActions.contains(uid)) { toDelete.add(next); } } } delete(jndiName, toDelete); } } else { tsLogger.logger .warn("Could not read data from object store"); } } else { tsLogger.logger .warn("Could not read " + CONNECTABLE_ATOMIC_ACTION_TYPE + " from object store"); } } catch (ObjectStoreException e) { tsLogger.logger.warn("Could not read " + ATOMIC_ACTION_TYPE + " from object store", e); } } /** * Can only be called after the first phase has executed * * @param xid * @return */ public synchronized boolean wasCommitted(String jndiName, Xid xid) throws ObjectStoreException { if (!queriedResourceManagers.contains(jndiName) || committedXidsToJndiNames.get(xid) == null) { periodicWorkFirstPass(); } if (!queriedResourceManagers.contains(jndiName)) { throw new ObjectStoreException(jndiName + " was not online"); } String committed = committedXidsToJndiNames.get(xid); if (tsLogger.logger.isTraceEnabled()) { tsLogger.logger.trace("wasCommitted" + xid + " " + committed); } return committed != null; } private List<Uid> convertToList(InputObjectState aa_uids) { List<Uid> uids = new ArrayList<Uid>(); boolean moreUids = true; while (moreUids) { Uid theUid = null; try { theUid = UidHelper.unpackFrom(aa_uids); if (theUid.equals(Uid.nullUid())) { moreUids = false; } else { Uid newUid = new Uid(theUid); if (tsLogger.logger.isDebugEnabled()) { tsLogger.logger.debug("found transaction " + newUid); } uids.add(newUid); } } catch (IOException ex) { moreUids = false; } } return uids; } private boolean isTransactionInMidFlight(int status) { boolean inFlight = false; switch (status) { // these states can only come from a process that is still alive case ActionStatus.RUNNING: case ActionStatus.ABORT_ONLY: case ActionStatus.PREPARING: case ActionStatus.COMMITTING: case ActionStatus.ABORTING: case ActionStatus.PREPARED: inFlight = true; break; // the transaction is apparently still there, but has completed its // phase2. should be safe to redo it. case ActionStatus.COMMITTED: case ActionStatus.H_COMMIT: case ActionStatus.H_MIXED: case ActionStatus.H_HAZARD: case ActionStatus.ABORTED: case ActionStatus.H_ROLLBACK: inFlight = false; break; // this shouldn't happen case ActionStatus.INVALID: default: inFlight = false; } return inFlight; } private void moveRecord(Uid uid, String from, String to) throws ObjectStoreException { RecoveryStore recoveryStore = StoreManager.getRecoveryStore(); InputObjectState state = recoveryStore.read_committed(uid, from); if (state != null) { if (!recoveryStore.write_committed(uid, to, new OutputObjectState( state))) { tsLogger.logger.error("Could not move an: " + to + " uid: " + uid); } else if (!recoveryStore.remove_committed(uid, from)) { tsLogger.logger.error("Could not remove a: " + from + " uid: " + uid); } } else { tsLogger.logger .error("Could not read an: " + from + " uid: " + uid); } } private void delete(String jndiName, List<Xid> completedXids) { int batchSize = jtaEnvironmentBean .getCommitMarkableResourceRecordDeleteBatchSize(); Integer integer = jtaEnvironmentBean .getCommitMarkableResourceRecordDeleteBatchSizeMap().get( jndiName); if (integer != null) { batchSize = integer; } try { while (completedXids.size() > 0) { int sendingSize = batchSize < 0 ? completedXids.size() : completedXids.size() < batchSize ? completedXids .size() : batchSize; StringBuffer buffer = new StringBuffer(); for (int i = 0; i < sendingSize; i++) { buffer.append("?,"); } if (buffer.length() > 0) { Connection connection = null; DataSource dataSource = (DataSource) context .lookup(jndiName); try { connection = dataSource.getConnection(); connection.setAutoCommit(false); String tableName = commitMarkableResourceTableNameMap .get(jndiName); if (tableName == null) { tableName = defaultTableName; } String sql = "DELETE from " + tableName + " where xid in (" + buffer.substring(0, buffer.length() - 1) + ")"; if (tsLogger.logger.isTraceEnabled()) { tsLogger.logger .trace("Attempting to delete number of entries: " + buffer.length()); } PreparedStatement prepareStatement = connection .prepareStatement(sql); List<Xid> deleted = new ArrayList<Xid>(); try { for (int i = 0; i < sendingSize; i++) { XidImple xid = (XidImple) completedXids .remove(0); deleted.add(xid); XID toSave = xid.getXID(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream( baos); dos.writeInt(toSave.formatID); dos.writeInt(toSave.gtrid_length); dos.writeInt(toSave.bqual_length); dos.writeInt(toSave.data.length); dos.write(toSave.data); dos.flush(); prepareStatement.setBytes(i + 1, baos.toByteArray()); } int executeUpdate = prepareStatement .executeUpdate(); if (executeUpdate != sendingSize) { tsLogger.logger .error("Update was not successful, expected: " + sendingSize + " actual:" + executeUpdate); connection.rollback(); } else { connection.commit(); Iterator<Xid> iterator = deleted.iterator(); while (iterator.hasNext()) { XidImple xid = (XidImple) iterator.next(); committedXidsToJndiNames.remove(xid); } } } catch (IOException e) { tsLogger.logger .warn("Could not generate prepareStatement paramaters", e); } finally { try { prepareStatement.close(); } catch (SQLException e) { tsLogger.logger .warn("Could not close the prepared statement", e); } } } catch (SQLException e) { tsLogger.logger.warn("Could not handle the connection", e); } finally { if (connection != null) { try { connection.close(); } catch (SQLException e) { tsLogger.logger.warn( "Could not close the connection", e); } } } } } } catch (NamingException e) { tsLogger.logger .warn("Could not lookup commitMarkable: " + jndiName); tsLogger.logger.debug("Could not lookup commitMarkable: " + jndiName, e); } catch (IllegalStateException e) { // Thrown when AS is shutting down and we attempt a lookup tsLogger.logger.debug( "Could not lookup datasource, AS is shutting down: " + e.getMessage(), e); } } }
ArjunaJTA/jta/classes/com/arjuna/ats/internal/jta/recovery/arjunacore/CommitMarkableResourceRecordRecoveryModule.java
/* * Copyright 2013, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. * See the copyright.txt in the distribution for a * full listing of individual contributors. * This copyrighted material is made available to anyone wishing to use, * modify, copy, or redistribute it subject to the terms and conditions * of the GNU Lesser General Public License, v. 2.1. * This program is distributed in the hope that it will be useful, but WITHOUT A * 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, * v.2.1 along with this distribution; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. * * (C) 2013 * @author JBoss Inc. */ package com.arjuna.ats.internal.jta.recovery.arjunacore; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.sql.DataSource; import javax.transaction.xa.Xid; import com.arjuna.ats.arjuna.AtomicAction; import com.arjuna.ats.arjuna.common.Uid; import com.arjuna.ats.arjuna.coordinator.ActionStatus; import com.arjuna.ats.arjuna.exceptions.ObjectStoreException; import com.arjuna.ats.arjuna.logging.tsLogger; import com.arjuna.ats.arjuna.objectstore.ObjectStoreIterator; import com.arjuna.ats.arjuna.objectstore.RecoveryStore; import com.arjuna.ats.arjuna.objectstore.StoreManager; import com.arjuna.ats.arjuna.recovery.RecoveryModule; import com.arjuna.ats.arjuna.recovery.TransactionStatusConnectionManager; import com.arjuna.ats.arjuna.state.InputObjectState; import com.arjuna.ats.arjuna.state.OutputObjectState; import com.arjuna.ats.internal.arjuna.common.UidHelper; import com.arjuna.ats.internal.jta.xa.XID; import com.arjuna.ats.jta.common.JTAEnvironmentBean; import com.arjuna.ats.jta.xa.XidImple; import com.arjuna.common.internal.util.propertyservice.BeanPopulator; /** * This CommitMarkableResourceRecord assumes the following table has been * created: * * create table xids (xid varbinary(255), transactionManagerID varchar(255)) * (ora/syb/mysql) create table xids (xid bytea, transactionManagerID * varchar(255)) (psql) sp_configure "lock scheme",0,datarows (syb) * * The CommitMarkableResourceRecord does not support nested transactions * * TODO you have to set max_allowed_packet for large reaps on mysql */ public class CommitMarkableResourceRecordRecoveryModule implements RecoveryModule { // 'type' within the Object Store for AtomicActions. private static final String ATOMIC_ACTION_TYPE = RecoverConnectableAtomicAction.ATOMIC_ACTION_TYPE; private static final String CONNECTABLE_ATOMIC_ACTION_TYPE = RecoverConnectableAtomicAction.CONNECTABLE_ATOMIC_ACTION_TYPE; private InitialContext context; private List<String> jndiNamesToContact = new ArrayList<String>(); private Map<Xid, String> committedXidsToJndiNames = new HashMap<Xid, String>(); private List<String> queriedResourceManagers = new ArrayList<String>(); // Reference to the Object Store. private static RecoveryStore recoveryStore = null; /** * This map contains items that were in the database, we use it in phase 2 * to work out what we can GC */ private Map<String, Map<Xid, Uid>> jndiNamesToPossibleXidsForGC = new HashMap<String, Map<Xid, Uid>>(); /** * Typically the whereFilter will restrict this node to recovering the * database solely for itself but it is possible to recover for different * nodes. It uses the JTAEnvironmentBean::getXaRecoveryNodes(). */ private String whereFilter; private TransactionStatusConnectionManager transactionStatusConnectionMgr; private static JTAEnvironmentBean jtaEnvironmentBean = BeanPopulator .getDefaultInstance(JTAEnvironmentBean.class); private Map<String, String> commitMarkableResourceTableNameMap = jtaEnvironmentBean .getCommitMarkableResourceTableNameMap(); private Map<String, List<Xid>> completedBranches = new HashMap<String, List<Xid>>(); private static String defaultTableName = jtaEnvironmentBean .getDefaultCommitMarkableTableName(); public CommitMarkableResourceRecordRecoveryModule() throws NamingException, ObjectStoreException { context = new InitialContext(); JTAEnvironmentBean jtaEnvironmentBean = BeanPopulator .getDefaultInstance(JTAEnvironmentBean.class); jndiNamesToContact.addAll(jtaEnvironmentBean .getCommitMarkableResourceJNDINames()); List<String> xaRecoveryNodes = jtaEnvironmentBean.getXaRecoveryNodes(); if (xaRecoveryNodes .contains(NodeNameXAResourceOrphanFilter.RECOVER_ALL_NODES)) { whereFilter = ""; } else { StringBuffer buffer = new StringBuffer(); Iterator<String> iterator = xaRecoveryNodes.iterator(); while (iterator.hasNext()) { buffer.append("\'" + iterator.next() + "\',"); } whereFilter = " where transactionManagerID in ( " + buffer.substring(0, buffer.length() - 1) + ")"; } if (recoveryStore == null) { recoveryStore = StoreManager.getRecoveryStore(); } transactionStatusConnectionMgr = new TransactionStatusConnectionManager(); } public void notifyOfCompletedBranch(String commitMarkableResourceJndiName, Xid xid) { synchronized (completedBranches) { List<Xid> completedXids = completedBranches .get(commitMarkableResourceJndiName); if (completedXids == null) { completedXids = new ArrayList<Xid>(); completedBranches.put(commitMarkableResourceJndiName, completedXids); } completedXids.add(xid); } } @Override public void periodicWorkFirstPass() { // TODO - this is one shot only due to a // remove in the function, if this delete fails only normal // recovery is possible Map<String, List<Xid>> completedBranches2 = new HashMap<String, List<Xid>>(); synchronized (completedBranches) { Iterator<String> iterator = completedBranches.keySet().iterator(); while (iterator.hasNext()) { String jndiName = iterator.next(); List<Xid> completedXids = completedBranches.remove(jndiName); completedBranches2.put(jndiName, completedXids); } } Iterator<String> iterator2 = completedBranches2.keySet().iterator(); while (iterator2.hasNext()) { String jndiName = iterator2.next(); List<Xid> completedXids = completedBranches2.get(jndiName); delete(jndiName, completedXids); } if (tsLogger.logger.isTraceEnabled()) { tsLogger.logger .trace("CommitMarkableResourceRecordRecoveryModule::periodicWorkFirstPass"); } this.committedXidsToJndiNames.clear(); this.queriedResourceManagers.clear(); this.jndiNamesToPossibleXidsForGC.clear(); // The algorithm occurs in three stages: // 1. We query the database to find all the branches that were committed // 3. We check for previously moved AtomicActions where the resource // manager was offline but is now online and move them back for // processing // 3. We check for in doubt AtomicActions that have incomplete branches // where the resource manager is now online and update them with the // outcome // Stage 1 // Talk to all the known resource managers that support // CommitMarkableResourceRecord to find out what transactions have // committed try { Iterator<String> iterator = jndiNamesToContact.iterator(); while (iterator.hasNext()) { String jndiName = iterator.next(); try { DataSource dataSource = (DataSource) context .lookup(jndiName); Connection connection = dataSource.getConnection(); try { Statement createStatement = connection .createStatement(); try { String tableName = commitMarkableResourceTableNameMap .get(jndiName); if (tableName == null) { tableName = defaultTableName; } ResultSet rs = createStatement .executeQuery("SELECT xid,actionuid from " + tableName + whereFilter); try { int i = 0; while (rs.next()) { i++; byte[] xidAsBytes = rs.getBytes(1); ByteArrayInputStream bais = new ByteArrayInputStream( xidAsBytes); DataInputStream dis = new DataInputStream( bais); XID _theXid = new XID(); _theXid.formatID = dis.readInt(); _theXid.gtrid_length = dis.readInt(); _theXid.bqual_length = dis.readInt(); int dataLength = dis.readInt(); _theXid.data = new byte[dataLength]; dis.read(_theXid.data, 0, dataLength); XidImple xid = new XidImple(_theXid); byte[] actionuidAsBytes = new byte[Uid.UID_SIZE]; byte[] bytes = rs.getBytes(2); System.arraycopy(bytes, 0, actionuidAsBytes, 0, bytes.length); committedXidsToJndiNames.put(xid, jndiName); if (tsLogger.logger.isTraceEnabled()) { tsLogger.logger .trace("committedXidsToJndiNames.put" + xid + " " + jndiName); } // Populate the map of possible GCable Xids Uid actionuid = new Uid(actionuidAsBytes); Map<Xid, Uid> map = jndiNamesToPossibleXidsForGC .get(jndiName); if (map == null) { map = new HashMap<Xid, Uid>(); jndiNamesToPossibleXidsForGC.put( jndiName, map); } map.put(xid, actionuid); } } finally { try { rs.close(); } catch (SQLException e) { tsLogger.logger.warn( "Could not close resultset", e); } } } finally { try { createStatement.close(); } catch (SQLException e) { tsLogger.logger.warn( "Could not close statement", e); } } queriedResourceManagers.add(jndiName); } finally { try { connection.close(); } catch (SQLException e) { tsLogger.logger.warn("Could not close connection", e); } } } catch (NamingException e) { tsLogger.logger .warn("Could not lookup CommitMarkableResource: " + jndiName); tsLogger.logger.debug( "Could not lookup CommitMarkableResource: " + jndiName, e); } catch (SQLException e) { tsLogger.logger.warn("Could not handle connection", e); } catch (IOException e) { tsLogger.logger.warn( "Could not lookup write data to select", e); } } // Stage 2 // Look in the object store for atomic actions that had a connected // resource that was not online in a previous scan but is now. // Also look for CONNECTABLE_ATOMIC_ACTION_TYPE that have a matching // ATOMIC_ACTION_TYPE and remove the CONNECTABLE_ATOMIC_ACTION_TYPE // reference try { ObjectStoreIterator transactionUidEnum = new ObjectStoreIterator( recoveryStore, CONNECTABLE_ATOMIC_ACTION_TYPE); Uid currentUid = transactionUidEnum.iterate(); while (Uid.nullUid().notEquals(currentUid)) { // Make sure it isn't garbage from a failure to move before: InputObjectState state = recoveryStore.read_committed( currentUid, ATOMIC_ACTION_TYPE); if (state != null) { if (!recoveryStore.remove_committed(currentUid, CONNECTABLE_ATOMIC_ACTION_TYPE)) { tsLogger.logger.debug("Could not remove a: " + CONNECTABLE_ATOMIC_ACTION_TYPE + " uid: " + currentUid); } } else { state = recoveryStore.read_committed(currentUid, CONNECTABLE_ATOMIC_ACTION_TYPE); // TX may have been in progress and cleaned up by now if (state != null) { RecoverConnectableAtomicAction rcaa = new RecoverConnectableAtomicAction( CONNECTABLE_ATOMIC_ACTION_TYPE, currentUid, state); if (rcaa.containsIncompleteCommitMarkableResourceRecord()) { String commitMarkableResourceJndiName = rcaa .getCommitMarkableResourceJndiName(); // Check if the resource manager is online yet if (queriedResourceManagers .contains(commitMarkableResourceJndiName)) { // If it is remove the CRR and move it back and // let // the // next stage update it moveRecord(currentUid, CONNECTABLE_ATOMIC_ACTION_TYPE, ATOMIC_ACTION_TYPE); } } } } currentUid = transactionUidEnum.iterate(); } } catch (ObjectStoreException | IOException ex) { tsLogger.logger.warn("Could not query objectstore: ", ex); } // Stage 3 // Look for crashed AtomicActions that had a // CommitMarkableResourceRecord // and see if it is in the list from stage 1, will include all // records // moved in stage 2 if (tsLogger.logger.isDebugEnabled()) { tsLogger.logger.debug("processing " + ATOMIC_ACTION_TYPE + " transactions"); } try { ObjectStoreIterator transactionUidEnum = new ObjectStoreIterator( recoveryStore, ATOMIC_ACTION_TYPE); Uid currentUid = transactionUidEnum.iterate(); while (Uid.nullUid().notEquals(currentUid)) { // Retrieve the transaction status from its // original // process. if (!isTransactionInMidFlight(transactionStatusConnectionMgr .getTransactionStatus(ATOMIC_ACTION_TYPE, currentUid))) { InputObjectState state = recoveryStore.read_committed( currentUid, ATOMIC_ACTION_TYPE); if (state != null) { // Try to load it is a BasicAction that has a // ConnectedResourceRecord RecoverConnectableAtomicAction rcaa = new RecoverConnectableAtomicAction( ATOMIC_ACTION_TYPE, currentUid, state); // Check if it did have a ConnectedResourceRecord if (rcaa.containsIncompleteCommitMarkableResourceRecord()) { String commitMarkableResourceJndiName = rcaa .getCommitMarkableResourceJndiName(); // If it did, check if the resource manager was // online if (!queriedResourceManagers .contains(commitMarkableResourceJndiName)) { // If the resource manager wasn't online, move // it moveRecord(currentUid, ATOMIC_ACTION_TYPE, CONNECTABLE_ATOMIC_ACTION_TYPE); } else { // Update the completed outcome for the 1PC // resource rcaa.updateCommitMarkableResourceRecord(wasCommitted( commitMarkableResourceJndiName, rcaa.getXid())); } } } } currentUid = transactionUidEnum.iterate(); } } catch (ObjectStoreException | IOException ex) { tsLogger.logger.warn("Could not query objectstore: ", ex); } } catch (IllegalStateException e) { // Thrown when AS is shutting down and we attempt a lookup tsLogger.logger.debug( "Could not lookup datasource, AS is shutting down: " + e.getMessage(), e); } } @Override public void periodicWorkSecondPass() { /** * This is the list of AtomicActions that were prepared but not * completed. */ Set<Uid> preparedAtomicActions = new HashSet<Uid>(); InputObjectState aa_uids = new InputObjectState(); try { // Refresh our list of all the indoubt atomic actions if (recoveryStore.allObjUids(ATOMIC_ACTION_TYPE, aa_uids)) { preparedAtomicActions.addAll(convertToList(aa_uids)); // Refresh our list of all the indoubt connectable atomic // actions if (recoveryStore.allObjUids(CONNECTABLE_ATOMIC_ACTION_TYPE, aa_uids)) { preparedAtomicActions.addAll(convertToList(aa_uids)); // Iterate the list that we were able to contact Iterator<String> jndiNames = queriedResourceManagers .iterator(); while (jndiNames.hasNext()) { String jndiName = jndiNames.next(); List<Xid> toDelete = new ArrayList<Xid>(); Map<Xid, Uid> map = jndiNamesToPossibleXidsForGC .get(jndiName); if (map != null) { for (Map.Entry<Xid, Uid> entry : map.entrySet()) { Xid next = entry.getKey(); Uid uid = entry.getValue(); if (!preparedAtomicActions.contains(uid)) { toDelete.add(next); } } } delete(jndiName, toDelete); } } else { tsLogger.logger .warn("Could not read data from object store"); } } else { tsLogger.logger .warn("Could not read " + CONNECTABLE_ATOMIC_ACTION_TYPE + " from object store"); } } catch (ObjectStoreException e) { tsLogger.logger.warn("Could not read " + ATOMIC_ACTION_TYPE + " from object store", e); } } /** * Can only be called after the first phase has executed * * @param xid * @return */ public boolean wasCommitted(String jndiName, Xid xid) throws ObjectStoreException { if (!queriedResourceManagers.contains(jndiName)) { throw new ObjectStoreException(jndiName + " was not online"); } String committed = committedXidsToJndiNames.get(xid); if (tsLogger.logger.isTraceEnabled()) { tsLogger.logger.trace("wasCommitted" + xid + " " + committed); } return committed != null; } private List<Uid> convertToList(InputObjectState aa_uids) { List<Uid> uids = new ArrayList<Uid>(); boolean moreUids = true; while (moreUids) { Uid theUid = null; try { theUid = UidHelper.unpackFrom(aa_uids); if (theUid.equals(Uid.nullUid())) { moreUids = false; } else { Uid newUid = new Uid(theUid); if (tsLogger.logger.isDebugEnabled()) { tsLogger.logger.debug("found transaction " + newUid); } uids.add(newUid); } } catch (IOException ex) { moreUids = false; } } return uids; } private boolean isTransactionInMidFlight(int status) { boolean inFlight = false; switch (status) { // these states can only come from a process that is still alive case ActionStatus.RUNNING: case ActionStatus.ABORT_ONLY: case ActionStatus.PREPARING: case ActionStatus.COMMITTING: case ActionStatus.ABORTING: case ActionStatus.PREPARED: inFlight = true; break; // the transaction is apparently still there, but has completed its // phase2. should be safe to redo it. case ActionStatus.COMMITTED: case ActionStatus.H_COMMIT: case ActionStatus.H_MIXED: case ActionStatus.H_HAZARD: case ActionStatus.ABORTED: case ActionStatus.H_ROLLBACK: inFlight = false; break; // this shouldn't happen case ActionStatus.INVALID: default: inFlight = false; } return inFlight; } private void moveRecord(Uid uid, String from, String to) throws ObjectStoreException { RecoveryStore recoveryStore = StoreManager.getRecoveryStore(); InputObjectState state = recoveryStore.read_committed(uid, from); if (state != null) { if (!recoveryStore.write_committed(uid, to, new OutputObjectState( state))) { tsLogger.logger.error("Could not move an: " + to + " uid: " + uid); } else if (!recoveryStore.remove_committed(uid, from)) { tsLogger.logger.error("Could not remove a: " + from + " uid: " + uid); } } else { tsLogger.logger .error("Could not read an: " + from + " uid: " + uid); } } private void delete(String jndiName, List<Xid> completedXids) { int batchSize = jtaEnvironmentBean .getCommitMarkableResourceRecordDeleteBatchSize(); Integer integer = jtaEnvironmentBean .getCommitMarkableResourceRecordDeleteBatchSizeMap().get( jndiName); if (integer != null) { batchSize = integer; } try { while (completedXids.size() > 0) { int sendingSize = batchSize < 0 ? completedXids.size() : completedXids.size() < batchSize ? completedXids .size() : batchSize; StringBuffer buffer = new StringBuffer(); for (int i = 0; i < sendingSize; i++) { buffer.append("?,"); } if (buffer.length() > 0) { Connection connection = null; DataSource dataSource = (DataSource) context .lookup(jndiName); try { connection = dataSource.getConnection(); connection.setAutoCommit(false); String tableName = commitMarkableResourceTableNameMap .get(jndiName); if (tableName == null) { tableName = defaultTableName; } String sql = "DELETE from " + tableName + " where xid in (" + buffer.substring(0, buffer.length() - 1) + ")"; if (tsLogger.logger.isTraceEnabled()) { tsLogger.logger .trace("Attempting to delete number of entries: " + buffer.length()); } PreparedStatement prepareStatement = connection .prepareStatement(sql); List<Xid> deleted = new ArrayList<Xid>(); try { for (int i = 0; i < sendingSize; i++) { XidImple xid = (XidImple) completedXids .remove(0); deleted.add(xid); XID toSave = xid.getXID(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream( baos); dos.writeInt(toSave.formatID); dos.writeInt(toSave.gtrid_length); dos.writeInt(toSave.bqual_length); dos.writeInt(toSave.data.length); dos.write(toSave.data); dos.flush(); prepareStatement.setBytes(i + 1, baos.toByteArray()); } int executeUpdate = prepareStatement .executeUpdate(); if (executeUpdate != sendingSize) { tsLogger.logger .error("Update was not successful, expected: " + sendingSize + " actual:" + executeUpdate); connection.rollback(); } else { connection.commit(); Iterator<Xid> iterator = deleted.iterator(); while (iterator.hasNext()) { XidImple xid = (XidImple) iterator.next(); committedXidsToJndiNames.remove(xid); } } } catch (IOException e) { tsLogger.logger .warn("Could not generate prepareStatement paramaters", e); } finally { try { prepareStatement.close(); } catch (SQLException e) { tsLogger.logger .warn("Could not close the prepared statement", e); } } } catch (SQLException e) { tsLogger.logger.warn("Could not handle the connection", e); } finally { if (connection != null) { try { connection.close(); } catch (SQLException e) { tsLogger.logger.warn( "Could not close the connection", e); } } } } } } catch (NamingException e) { tsLogger.logger .warn("Could not lookup commitMarkable: " + jndiName); tsLogger.logger.debug("Could not lookup commitMarkable: " + jndiName, e); } catch (IllegalStateException e) { // Thrown when AS is shutting down and we attempt a lookup tsLogger.logger.debug( "Could not lookup datasource, AS is shutting down: " + e.getMessage(), e); } } }
JBTM-2186 Make sure that when checking if a CMR was committed we do a scan on the CMR resource
ArjunaJTA/jta/classes/com/arjuna/ats/internal/jta/recovery/arjunacore/CommitMarkableResourceRecordRecoveryModule.java
JBTM-2186 Make sure that when checking if a CMR was committed we do a scan on the CMR resource
Java
lgpl-2.1
e654059cad135e6db3a4e7fc11275b9b7b1aa33e
0
cacheonix/cacheonix-core,cacheonix/cacheonix-core,cacheonix/cacheonix-core
/* * Cacheonix Systems licenses this file to You under the LGPL 2.1 * (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.cacheonix.org/products/cacheonix/license-lgpl-2.1.htm * * 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.cacheonix.impl.util; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.PrintStream; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.UnknownHostException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.List; import java.util.Locale; import java.util.Set; import java.util.StringTokenizer; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.cacheonix.impl.util.array.Hash; import org.cacheonix.impl.util.array.HashSet; import org.cacheonix.impl.util.array.IntArrayList; import static org.cacheonix.impl.util.exception.ExceptionUtils.ignoreException; /** * Common string utilities */ public final class StringUtils { private static final char[] HEX_DIGITS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; private static final char CHAR_SINGLE_QUOTE = '\''; private static final char CHAR_DOUBLE_QUOTE = '\"'; private static final int BASELENGTH = 255; private static final int LOOKUPLENGTH = 64; private static final int TWENTYFOURBITGROUP = 24; private static final int EIGHTBIT = 8; private static final int SIXTEENBIT = 16; private static final int FOURBYTE = 4; private static final int SIGN = -128; private static final byte PAD = (byte) '='; private static final byte[] base64Alphabet = new byte[BASELENGTH]; private static final byte[] lookUpBase64Alphabet = new byte[LOOKUPLENGTH]; private static final String STRING_TRUE = "true"; private static final String STRING_YES = "yes"; private static final String STRING_ENABLED = "enabled"; private static final String NO = "No"; private static final String YES = "Yes"; private static final String NULL_AS_STRING = "null"; private static final int KILO_BYTE = 1024; private static final int MEGA_BYTE = KILO_BYTE << 10; private static final int GIGA_BYTE = 1073741824; /** * A pattern used to parse time. */ private static final Pattern TIME_PATTERN = Pattern.compile("([0-9]+)(milliseconds|millis|ms|seconds|secs|s|minutes|min)"); /** * A pattern used to parse bytes. */ private static final Pattern BYTES_PATTERN = Pattern.compile("([0-9]+)(bytes|kilobytes|k|kb|megabytes|mb|m|gigabytes|gb|g|%)"); /** * A helper constant used to typify conversation from a list to an array. */ private static final String[] STRING_ARRAY_TEMPLATE = new String[0]; private StringUtils() { } static { for (int i = 0; i < BASELENGTH; i++) { base64Alphabet[i] = (byte) -1; } for (int i = (int) 'Z'; i >= (int) 'A'; i--) { base64Alphabet[i] = (byte) (i - (int) 'A'); } for (int i = (int) 'z'; i >= (int) 'a'; i--) { base64Alphabet[i] = (byte) (i - (int) 'a' + 26); } for (int i = (int) '9'; i >= (int) '0'; i--) { base64Alphabet[i] = (byte) (i - (int) '0' + 52); } base64Alphabet[(int) '+'] = (byte) 62; base64Alphabet[(int) '/'] = (byte) 63; for (int i = 0; i <= 25; i++) { lookUpBase64Alphabet[i] = (byte) ((int) 'A' + i); } for (int i = 26, j = 0; i <= 51; i++, j++) { lookUpBase64Alphabet[i] = (byte) ((int) 'a' + j); } for (int i = 52, j = 0; i <= 61; i++, j++) { lookUpBase64Alphabet[i] = (byte) ((int) '0' + j); } lookUpBase64Alphabet[62] = (byte) '+'; lookUpBase64Alphabet[63] = (byte) '/'; } /** * Returns <code>true</code> if string is null */ public static boolean isNull(final String string) { return string == null; } /** * Returns <code>true</code> if string is blank * * @throws NullPointerException if string is null */ public static boolean isBlank(final String string) { if (isNull(string)) { return true; } final int length = string.length(); if (length == 0) { return true; } for (int i = 0; i < length; i++) { if (string.charAt(i) > ' ') { return false; } } return true; } /** * Makes word duration. */ public static StringBuffer durationToString(final long seconds, final boolean fullWords) { final StringBuffer result = new StringBuffer(30); long secondsLeft = seconds; final long durationDays = secondsLeft / 86400L; if (durationDays > 0L) { result.append(Long.toString(durationDays)).append(fullWords ? " days " : "d "); secondsLeft %= 86400L; } final long durationHours = secondsLeft / 3600L; if (durationHours > 0L) { result.append(durationHours < 10L ? "0" : "").append(Long.toString(durationHours)).append( fullWords ? " hours " : "h "); secondsLeft %= 3600L; } if (durationDays > 0L) { return result; } final long durationMinutes = secondsLeft / 60L; if (durationMinutes > 0L) { result.append(durationMinutes < 10L ? "0" : "").append( Long.toString(durationMinutes)).append(fullWords ? " minutes " : "m "); secondsLeft %= 60L; } if (durationHours > 0L) { return result; } if (secondsLeft < 10L) { result.append('0'); } return result.append(Long.toString(secondsLeft)).append(fullWords ? " seconds " : "s "); } /** * Cleans up exception from the exception name. * * @param e the exception which message must be cleanup. * @return exception message without the prefixing exception name. */ public static String toString(final Throwable e) { final String message = e.toString(); final int i = message.indexOf("ion: "); String result = null; if (i >= 0) { result = message.substring(i + 5).trim(); } else { result = message.trim(); } if (isBlank(result)) { result = e.getMessage(); } return result; } /** * Returns <code>true</code> if parameter is a valid string representation of integer value */ public static boolean isValidInteger(final String s) { if (isBlank(s)) { return false; } try { Integer.parseInt(s); return true; } catch (final Exception ignored) { return false; } } /** * Returns <code>true</code> if parameter is a valid string representation of long value */ public static boolean isValidLong(final String s) { if (isBlank(s)) { return false; } try { Long.parseLong(s); return true; } catch (final Exception ignored) { return false; } } /** * Validates if the name is a strict name */ public static boolean isValidStrictName(final String name) { return Pattern.compile("[a-zA-Z][-a-zA-Z_0-9]*").matcher(name).matches(); } /** * Extracts a stack trace from Throwable to a String */ public static String stackTraceToString(final Throwable th) { ByteArrayOutputStream baos = null; try { baos = new ByteArrayOutputStream(1000); final PrintStream ps = new PrintStream(baos); th.printStackTrace(ps); return baos.toString(); } finally { if (baos != null) { try { baos.flush(); baos.close(); } catch (final IOException e) { ignoreException(e, "doesn't make sense to report at close"); } } } } /** * Formats date in accordance with given format * * @param date Date to format * @param format String format used to format Date * @return String with formatted date */ public static String formatDate(final Date date, final String format) { return new SimpleDateFormat(format, Locale.US).format(date); } /** * Gets file name out of file path */ public static String extractNameFromFilePath(final String filePath) { final int lastSlash = filePath.lastIndexOf((int) '/'); return filePath.substring(lastSlash + 1); } /** * Gets file name out of file path */ public static String extractPathFromFilePath(final String filePath) { final int lastSlash = filePath.lastIndexOf((int) '/'); if (lastSlash == -1) { return ""; } else { return filePath.substring(0, lastSlash); } } /** * Converts array of int representing an int-encoded string to a String */ public static String intArrayToString(final int[] array) { final StringBuilder result = new StringBuilder(array.length); for (final int anArray : array) { result.append((char) anArray); } return result.toString(); } /** * Returns <code>true</code> if first character of the string is a letter */ public static boolean isFirstLetter(final String s) { return !isBlank(s) && Pattern.compile("[a-zA-Z]").matcher(s.substring(0, 1)).matches(); } /** * @return <code>true</code> if system property is set and equals given value. */ public static boolean systemPropertyEquals(final String name, final String value) { final String property = System.getProperty(name); return property != null && property.equalsIgnoreCase(value); } /** * @return <code>true</code> this string pattern is empty */ public static boolean patternIsEmpty(final String pattern) { return isBlank(pattern) || !new StringTokenizer(pattern, "\n \r", false).hasMoreTokens(); } /** * Breaks a possibly multiline string to a list of lines. Empty lines are excluded from the list. */ public static List multilineStringToList(final String multilineString) { final List result = new ArrayList(3); if (isBlank(multilineString)) { return result; } for (final StringTokenizer st = new StringTokenizer(multilineString, "\n\r", false); st.hasMoreTokens(); ) { final String s = st.nextToken(); if (isBlank(s)) { continue; } result.add(s.trim()); } return result; } /** * Converts a list of Strings to a String containing items of the list as lines separated by "\n". */ public static String linesToString(final List stringList) { final StringBuilder result = new StringBuilder(300); for (final Object aStringList : stringList) { result.append((String) aStringList).append('\n'); } return result.toString(); } public static String[] toStringArray(final List stringList) { return (String[]) stringList.toArray(STRING_ARRAY_TEMPLATE); } /** * Returns a byte array from a string of hexadecimal digits. */ public static byte[] decodeFromHex(final String hex) { final int len = hex.length(); final byte[] buf = new byte[len + 1 >> 1]; int i = 0; int j = 0; if (len % 2 == 1) { buf[j++] = (byte) fromDigit(hex.charAt(i++)); } while (i < len) { buf[j++] = (byte) (fromDigit(hex.charAt(i++)) << 4 | fromDigit(hex.charAt(i++))); } return buf; } /** * Returns the number from 0 to 15 corresponding to the hex digit <i>ch</i>. */ private static int fromDigit(final char ch) { if (ch >= '0' && ch <= '9') { return (int) ch - (int) '0'; } if (ch >= 'A' && ch <= 'F') { return (int) ch - (int) 'A' + 10; } if (ch >= 'a' && ch <= 'f') { return (int) ch - (int) 'a' + 10; } throw new IllegalArgumentException("invalid hex digit '" + ch + '\''); } /** * Returns a string of hexadecimal digits from a byte array. Each byte is converted to 2 hex symbols. */ public static String encodeToHex( final byte[] ba) { // NOPMD - "A user given array is stored directly" - we do NOT store anything. final int length = ba.length; final char[] buf = new char[length << 1]; for (int i = 0, j = 0; i < length; ) { final int k = ba[i++]; buf[j++] = HEX_DIGITS[k >>> 4 & 0x0F]; buf[j++] = HEX_DIGITS[k & 0x0F]; } return String.valueOf(buf); } /** * Digests password with MD5 and encodes it as a hex String. * * @param password to digest. * @return hex encoded password digest. */ public static String digest(final String password) throws NoSuchAlgorithmException { final MessageDigest messageDigest = MessageDigest.getInstance("MD5"); messageDigest.reset(); messageDigest.update(password.trim().toLowerCase().getBytes()); return encodeToHex(messageDigest.digest()); } public static long daysToMillis(final int days) { return (long) days * 24L * 60L * 60L * 1000L; } /** * Truncates string to maxLen. * * @param in input string * @param maxLen max length */ public static String truncate(final String in, final int maxLen) { if (in == null || in.length() <= maxLen) { return in; } else { return in.substring(0, maxLen); } } public static void appendWithNewLineIfNotNull(final StringBuffer sb, final String label, final String value) { if (!isBlank(value)) { sb.append(label).append(' ').append(value); sb.append("/n"); } } /** * Puts string into double quotes. Other leading and trailing quotes are removed first. * * @param stringToProcess String to quote, trimmed before quoting. * @return double-quoted string. */ public static String putIntoDoubleQuotes(final String stringToProcess) { final char[] dd = stringToProcess.trim().toCharArray(); final int len = dd.length; int st = 0; for (; st < len; st++) { final char c = dd[st]; if (c != CHAR_DOUBLE_QUOTE && c != CHAR_SINGLE_QUOTE) { break; } } int en = len; for (; en > st; en--) { final char c = dd[en - 1]; if (c != CHAR_DOUBLE_QUOTE && c != CHAR_SINGLE_QUOTE) { break; } } return '\"' + stringToProcess.substring(st, en) + '\"'; } public static String removeDoubleQuotes(final String stringToProcess) { if (stringToProcess.startsWith("\"") && stringToProcess.endsWith("\"")) { return stringToProcess.substring(1, stringToProcess.length() - 1); } else { return stringToProcess; } } public static List split(final String value, final int maxLength) { final List parts = new ArrayList(23); final int originalLength = value.length(); if (originalLength > maxLength) { // split it if necessary final int splitCount = originalLength / maxLength; for (int splitIndex = 0; splitIndex < splitCount; splitIndex++) { parts.add(value.substring(splitIndex * maxLength, (splitIndex + 1) * maxLength)); } // process last piece if any final int leftOverLength = originalLength - splitCount * maxLength; if (leftOverLength > 0) { parts.add(value.substring(originalLength - leftOverLength, originalLength)); } } else { parts.add(value); } return parts; } public static String formatWithTrailingZeroes(final int value, final int zeroes) { final String stringValue = Integer.toString(value); final StringBuilder result = new StringBuilder(5); final int numberOfZeroesToAdd = zeroes - stringValue.length(); for (int i = 0; i < numberOfZeroesToAdd; i++) { result.append('0'); } result.append(stringValue); return result.toString(); } /** * Makes pattern array of compiled regex patterns. */ public static Pattern[] makeRegexPatternsFromMultilineString(final String customPatterns) { final Set result = new HashSet(5); for (final StringTokenizer st = new StringTokenizer(customPatterns, "\n", false); st.hasMoreTokens(); ) { final String pattern = st.nextToken().trim(); if (isRegex(pattern)) { result.add(Pattern.compile(pattern)); } } return (Pattern[]) result.toArray(new Pattern[result.size()]); } /** * @param pattern * @return <code>true</code> if pattern starts with '^' and ends with '$' */ public static boolean isRegex(final String pattern) { return !isBlank(pattern) && pattern.charAt(0) == '^' && pattern.endsWith("$"); } public static boolean isBase64(final String isValidString) { return isArrayByteBase64(isValidString.getBytes()); } public static boolean isBase64(final byte octect) { //shall we ignore white space? JEFF?? return octect == PAD || base64Alphabet[(int) octect] != (byte) -1; } public static boolean isArrayByteBase64(final byte[] arrayOctect) { final int length = arrayOctect.length; if (length == 0) { // shouldn't a 0 length array be valid base64 data? // return false; return true; } for (final byte anArrayOctect : arrayOctect) { if (!isBase64(anArrayOctect)) { return false; } } return true; } /** * Encodes hex octects into Base64. * * @param binaryData Array containing binary data to encode. * @return Base64-encoded data. */ public static byte[] encode(final byte[] binaryData) { final int lengthDataBits = binaryData.length * EIGHTBIT; final int fewerThan24bits = lengthDataBits % TWENTYFOURBITGROUP; final int numberTriplets = lengthDataBits / TWENTYFOURBITGROUP; byte[] encodedData = null; if (fewerThan24bits == 0) { // 16 or 8 bit encodedData = new byte[numberTriplets << 2]; } else { //data not divisible by 24 bit encodedData = new byte[(numberTriplets + 1 << 2)]; } byte k = (byte) 0; byte l = (byte) 0; byte b1 = (byte) 0; byte b2 = (byte) 0; byte b3 = (byte) 0; int encodedIndex = 0; int dataIndex = 0; int i = 0; //log.debug("number of triplets = " + numberTriplets); for (i = 0; i < numberTriplets; i++) { dataIndex = i * 3; b1 = binaryData[dataIndex]; b2 = binaryData[dataIndex + 1]; b3 = binaryData[dataIndex + 2]; //log.debug("b1= " + b1 +", b2= " + b2 + ", b3= " + b3); l = (byte) (b2 & 0x0f); k = (byte) (b1 & 0x03); encodedIndex = i << 2; final byte val1 = (b1 & SIGN) == 0 ? (byte) (b1 >> 2) : (byte) (b1 >> 2 ^ 0xc0); final byte val2 = (b2 & SIGN) == 0 ? (byte) (b2 >> 4) : (byte) (b2 >> 4 ^ 0xf0); final byte val3 = (b3 & SIGN) == 0 ? (byte) (b3 >> 6) : (byte) (b3 >> 6 ^ 0xfc); encodedData[encodedIndex] = lookUpBase64Alphabet[(int) val1]; encodedData[encodedIndex + 1] = lookUpBase64Alphabet[val2 | k << 4]; encodedData[encodedIndex + 2] = lookUpBase64Alphabet[l << 2 | val3]; encodedData[encodedIndex + 3] = lookUpBase64Alphabet[b3 & 0x3f]; } // form integral number of 6-bit groups final int dataIndex1 = i * 3; final int encodedIndex1 = i << 2; if (fewerThan24bits == EIGHTBIT) { final byte b11 = binaryData[dataIndex1]; final byte k1 = (byte) (b11 & 0x03); final byte val1 = (b11 & SIGN) == 0 ? (byte) (b11 >> 2) : (byte) (b11 >> 2 ^ 0xc0); encodedData[encodedIndex1] = lookUpBase64Alphabet[(int) val1]; encodedData[encodedIndex1 + 1] = lookUpBase64Alphabet[k1 << 4]; encodedData[encodedIndex1 + 2] = PAD; encodedData[encodedIndex1 + 3] = PAD; } else if (fewerThan24bits == SIXTEENBIT) { final byte b11 = binaryData[dataIndex1]; final byte b21 = binaryData[dataIndex1 + 1]; final byte l1 = (byte) (b21 & 0x0f); final byte k1 = (byte) (b11 & 0x03); final byte val1 = (b11 & SIGN) == 0 ? (byte) (b11 >> 2) : (byte) (b11 >> 2 ^ 0xc0); final byte val2 = (b21 & SIGN) == 0 ? (byte) (b21 >> 4) : (byte) (b21 >> 4 ^ 0xf0); encodedData[encodedIndex1] = lookUpBase64Alphabet[(int) val1]; encodedData[encodedIndex1 + 1] = lookUpBase64Alphabet[val2 | k1 << 4]; encodedData[encodedIndex1 + 2] = lookUpBase64Alphabet[l1 << 2]; encodedData[encodedIndex1 + 3] = PAD; } return encodedData; } /** * Decodes Base64 data into octects * * @param base64Data Byte array containing Base64 data * @return Array containing decoded data. */ public static byte[] decode(final byte[] base64Data) { //noinspection ZeroLengthArrayAllocation final byte[] emptyByteArray = {}; // NOPMD // handle the edge case, so we don't have to worry about it later if (base64Data.length == 0) { return emptyByteArray; } // NOPMD final int numberQuadruple = base64Data.length / FOURBYTE; // Throw away anything not in base64Data // this sizes the output array properly - rlw int lastData = base64Data.length; // ignore the '=' padding while (base64Data[lastData - 1] == PAD) { if (--lastData == 0) { return emptyByteArray; // NOPMD } } final byte[] decodedData = new byte[lastData - numberQuadruple]; int dataIndex = 0; int encodedIndex = 0; byte marker1 = (byte) 0; byte marker0 = (byte) 0; byte b4 = (byte) 0; byte b3 = (byte) 0; byte b2 = (byte) 0; byte b1 = (byte) 0; for (int i = 0; i < numberQuadruple; i++) { dataIndex = i << 2; marker0 = base64Data[dataIndex + 2]; marker1 = base64Data[dataIndex + 3]; b1 = base64Alphabet[base64Data[dataIndex]]; b2 = base64Alphabet[base64Data[dataIndex + 1]]; if (marker0 != PAD && marker1 != PAD) { //No PAD e.g 3cQl b3 = base64Alphabet[(int) marker0]; b4 = base64Alphabet[(int) marker1]; decodedData[encodedIndex] = (byte) (b1 << 2 | b2 >> 4); decodedData[encodedIndex + 1] = (byte) ((b2 & 0xf) << 4 | b3 >> 2 & 0xf); decodedData[encodedIndex + 2] = (byte) (b3 << 6 | b4); } else if (marker0 == PAD) { //Two PAD e.g. 3c[Pad][Pad] decodedData[encodedIndex] = (byte) (b1 << 2 | b2 >> 4); } else if (marker1 == PAD) { //One PAD e.g. 3cQ[Pad] b3 = base64Alphabet[(int) marker0]; decodedData[encodedIndex] = (byte) (b1 << 2 | b2 >> 4); decodedData[encodedIndex + 1] = (byte) ((b2 & 0xf) << 4 | b3 >> 2 & 0xf); } encodedIndex += 3; } return decodedData; } /** * Helper method. * * @param s * @return */ public static List makeList(final String s) { final List result = new ArrayList(1); result.add(s); return result; } public static StringBuffer appendChars(final StringBuffer buf, final int charCount, final char c) { for (int i = 0; i < charCount; i++) { buf.append(c); } return buf; } /** * Helper method. * * @param value * @return */ public static boolean toBoolean(final String value) { return value.equalsIgnoreCase(STRING_TRUE) || value.equalsIgnoreCase(STRING_YES) || value.equalsIgnoreCase(STRING_ENABLED); } /** * Transform InetAddress to a pretty-printed string. * * @param address InetAddress to transform. * @return InetAddress as a pretty-printed string. */ public static String toString(final InetAddress address) { return removeLeadingSlash(address.toString()); } public static String toString(final InetSocketAddress endpoint) { return removeLeadingSlash(endpoint.toString()); } /** * Helper method to transform a boolean value to as "YES" or "NO" string. * * @param value boolean value to transform. * @return a String containing "YES" or "NO". * @see #YES * @see #NO */ public static String toYesNo(final boolean value) { return value ? YES : NO; } public static String toString(final Object[] objects) { if (objects == null) { return NULL_AS_STRING; } final StringBuilder sb = new StringBuilder(50); sb.append('['); for (int i = 0; i < objects.length; i++) { final Object o = objects[i]; sb.append(o); if (i < objects.length - 1) { sb.append(", "); } } sb.append(']'); return sb.toString(); } public static void dump(final byte[] b, final PrintStream out) { for (int i = 0; i < b.length; ++i) { if (i % 16 == 0) { out.print(Integer.toHexString(i & 0xFFFF | 0x10000).substring(1, 5) + " - "); } out.print(Integer.toHexString(b[i] & 0xFF | 0x100).substring(1, 3) + ' '); if (i % 16 == 15 || i == b.length - 1) { int j; for (j = 16 - i % 16; j > 1; --j) { out.print(" "); } out.print(" - "); final int start = i / 16 * 16; final int end = b.length < i + 1 ? b.length : i + 1; for (j = start; j < end; ++j) { if (b[j] >= 32 && b[j] <= 126) { out.print((char) b[j]); } else { out.print("."); } } out.println(); } } out.println(); } public static String toString(final IntArrayList list) { final StringBuilder sb = new StringBuilder(20); if (list == null) { sb.append("null"); } else { sb.append('['); sb.append("size:"); final int listSize = list.size(); sb.append(Integer.toString(listSize)); if (!list.isEmpty()) { sb.append("; "); for (int i = 0; i < listSize; i++) { final Object o = list.get(i); sb.append(o); if (i < listSize - 1) { sb.append(','); } } } sb.append(']'); } return sb.toString(); } public static String toShortName(final Class clazz) { final String name = clazz.getName(); return name.substring(name.lastIndexOf('.') + 1); } public static String sizeToString(final Collection collection) { if (collection == null) { return "null"; } else { return Integer.toString(collection.size()); } } public static String sizeToString(final Hash hash) { return hash == null ? "null" : Integer.toString(hash.size()); } public static String sizeToString(final IntArrayList intArrayList) { return intArrayList == null ? "null" : Integer.toString(intArrayList.size()); } public static long readTime(final String stringTime) throws IllegalArgumentException { final Matcher matcher = TIME_PATTERN.matcher(stringTime); if (matcher.matches()) { final String stringValue = matcher.group(1); final String stringMeasure = matcher.group(2).toLowerCase(); final long multiplier; if ("milliseconds".equals(stringMeasure) || "millis".equals(stringMeasure) || "ms".equals(stringMeasure)) { multiplier = 1; } else if ("seconds".equals(stringMeasure) || "secs".equals(stringMeasure) || "s".equals(stringMeasure)) { multiplier = 1000; } else if ("minutes".equals(stringMeasure) || "min".equals(stringMeasure)) { multiplier = 60000; } else { throw new IllegalArgumentException("Unknown measure: " + stringTime); } return Long.parseLong(stringValue) * multiplier; } else { throw new IllegalArgumentException("Unknown time format: " + stringTime); } } /** * Parses a size in bytes. Cacheonix supports bytes, kilobytes (k, kb), megabytes (mb) and gigabytes (gb) as a unit * of measure. Example: parsing "5mb" will return 5000000. * * @param stringBytes the size in bytes. Cacheonix supports bytes, kilobytes (k, kb), megabytes (mb) and gigabytes * (gb) as a unit of measure. Example: "5mb". * @return the size in bytes. Example: parsing "5mb" will return 5000000. * @throws IllegalArgumentException if the stringBytes cannot be parsed. */ public static long readBytes(final String stringBytes) throws IllegalArgumentException { final Matcher matcher = BYTES_PATTERN.matcher(stringBytes); if (!matcher.matches()) { throw new IllegalArgumentException("Unknown byte size format: " + stringBytes); } final String stringValue = matcher.group(1); final String stringMeasure = matcher.group(2).toLowerCase(); if ("b".equals(stringMeasure) || "bytes".equals(stringMeasure)) { return Long.parseLong(stringValue); } else if ("k".equals(stringMeasure) || "kb".equals(stringMeasure) || "kilobytes".equals(stringMeasure)) { return Long.parseLong(stringValue) * KILO_BYTE; } else if ("m".equals(stringMeasure) || "mb".equals(stringMeasure) || "megabytes".equals(stringMeasure)) { return Long.parseLong(stringValue) * MEGA_BYTE; } else if ("g".equals(stringMeasure) || "gb".equals(stringMeasure) || "gigabytes".equals(stringMeasure)) { return Long.parseLong(stringValue) * GIGA_BYTE; } else if ("%".equals(stringMeasure)) { final int percent = Integer.parseInt(stringValue); final int normalizedPercent = percent > 100 ? 100 : percent < 0 ? 0 : percent; return (long) ((double) Runtime.getRuntime().maxMemory() * ((double) normalizedPercent / (double) 100)); } else { throw new IllegalArgumentException("Unknown measure: " + stringBytes); } } private static String removeLeadingSlash(final String str) { final int i = str.indexOf('/'); return i >= 0 ? str.substring(i + 1) : str; } public static InetAddress readInetAddress(final String stringInetAddress) throws IllegalArgumentException { try { return InetAddress.getByName(stringInetAddress); } catch (final UnknownHostException e) { throw new IllegalArgumentException(e); } } }
src/org/cacheonix/impl/util/StringUtils.java
/* * Cacheonix Systems licenses this file to You under the LGPL 2.1 * (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.cacheonix.org/products/cacheonix/license-lgpl-2.1.htm * * 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.cacheonix.impl.util; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.PrintStream; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.UnknownHostException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.List; import java.util.Locale; import java.util.Set; import java.util.StringTokenizer; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.cacheonix.impl.util.array.Hash; import org.cacheonix.impl.util.array.HashSet; import org.cacheonix.impl.util.array.IntArrayList; import static org.cacheonix.impl.util.exception.ExceptionUtils.ignoreException; /** * Common string utilities */ public final class StringUtils { private static final char[] HEX_DIGITS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; private static final char CHAR_SINGLE_QUOTE = '\''; private static final char CHAR_DOUBLE_QUOTE = '\"'; private static final int BASELENGTH = 255; private static final int LOOKUPLENGTH = 64; private static final int TWENTYFOURBITGROUP = 24; private static final int EIGHTBIT = 8; private static final int SIXTEENBIT = 16; private static final int FOURBYTE = 4; private static final int SIGN = -128; private static final byte PAD = (byte) '='; private static final byte[] base64Alphabet = new byte[BASELENGTH]; private static final byte[] lookUpBase64Alphabet = new byte[LOOKUPLENGTH]; private static final String STRING_TRUE = "true"; private static final String STRING_YES = "yes"; private static final String STRING_ENABLED = "enabled"; private static final String NO = "No"; private static final String YES = "Yes"; private static final String NULL_AS_STRING = "null"; private static final int KILO_BYTE = 1024; private static final int MEGA_BYTE = KILO_BYTE << 10; private static final int GIGA_BYTE = 1073741824; /** * A pattern used to parse time. */ private static final Pattern TIME_PATTERN = Pattern.compile("([0-9]+)(milliseconds|millis|ms|seconds|secs|s|minutes|min)"); /** * A pattern used to parse bytes. */ private static final Pattern BYTES_PATTERN = Pattern.compile("([0-9]+)(bytes|kilobytes|k|kb|megabytes|mb|m|gigabytes|gb|g|%)"); /** * A helper constant used to typify conversation from a list to an array. */ private static final String[] STRING_ARRAY_TEMPLATE = new String[0]; private StringUtils() { } static { for (int i = 0; i < BASELENGTH; i++) { base64Alphabet[i] = (byte) -1; } for (int i = (int) 'Z'; i >= (int) 'A'; i--) { base64Alphabet[i] = (byte) (i - (int) 'A'); } for (int i = (int) 'z'; i >= (int) 'a'; i--) { base64Alphabet[i] = (byte) (i - (int) 'a' + 26); } for (int i = (int) '9'; i >= (int) '0'; i--) { base64Alphabet[i] = (byte) (i - (int) '0' + 52); } base64Alphabet[(int) '+'] = (byte) 62; base64Alphabet[(int) '/'] = (byte) 63; for (int i = 0; i <= 25; i++) { lookUpBase64Alphabet[i] = (byte) ((int) 'A' + i); } for (int i = 26, j = 0; i <= 51; i++, j++) { lookUpBase64Alphabet[i] = (byte) ((int) 'a' + j); } for (int i = 52, j = 0; i <= 61; i++, j++) { lookUpBase64Alphabet[i] = (byte) ((int) '0' + j); } lookUpBase64Alphabet[62] = (byte) '+'; lookUpBase64Alphabet[63] = (byte) '/'; } /** * Returns <code>true</code> if string is null */ public static boolean isNull(final String string) { return string == null; } /** * Returns <code>true</code> if string is blank * * @throws NullPointerException if string is null */ public static boolean isBlank(final String string) { if (isNull(string)) { return true; } final int length = string.length(); if (length == 0) { return true; } for (int i = 0; i < length; i++) { if (string.charAt(i) > ' ') { return false; } } return true; } /** * Makes word duration. */ public static StringBuffer durationToString(final long seconds, final boolean fullWords) { final StringBuffer result = new StringBuffer(30); long secondsLeft = seconds; final long durationDays = secondsLeft / 86400L; if (durationDays > 0L) { result.append(Long.toString(durationDays)).append(fullWords ? " days " : "d "); secondsLeft %= 86400L; } final long durationHours = secondsLeft / 3600L; if (durationHours > 0L) { result.append(durationHours < 10L ? "0" : "").append(Long.toString(durationHours)).append( fullWords ? " hours " : "h "); secondsLeft %= 3600L; } if (durationDays > 0L) { return result; } final long durationMinutes = secondsLeft / 60L; if (durationMinutes > 0L) { result.append(durationMinutes < 10L ? "0" : "").append( Long.toString(durationMinutes)).append(fullWords ? " minutes " : "m "); secondsLeft %= 60L; } if (durationHours > 0L) { return result; } if (secondsLeft < 10L) { result.append('0'); } return result.append(Long.toString(secondsLeft)).append(fullWords ? " seconds " : "s "); } /** * Cleans up exception from the exception name. * * @param e the exception which message must be cleanup. * @return exception message without the prefixing exception name. */ public static String toString(final Throwable e) { final String message = e.toString(); final int i = message.indexOf("ion: "); String result = null; if (i >= 0) { result = message.substring(i + 5).trim(); } else { result = message.trim(); } if (isBlank(result)) { result = e.getMessage(); } return result; } /** * Returns <code>true</code> if parameter is a valid string representation of integer value */ public static boolean isValidInteger(final String s) { if (isBlank(s)) { return false; } try { Integer.parseInt(s); return true; } catch (final Exception ignored) { return false; } } /** * Returns <code>true</code> if parameter is a valid string representation of long value */ public static boolean isValidLong(final String s) { if (isBlank(s)) { return false; } try { Long.parseLong(s); return true; } catch (final Exception ignored) { return false; } } /** * Validates if the name is a strict name */ public static boolean isValidStrictName(final String name) { return Pattern.compile("[a-zA-Z][-a-zA-Z_0-9]*").matcher(name).matches(); } /** * Extracts a stack trace from Throwable to a String */ public static String stackTraceToString(final Throwable th) { ByteArrayOutputStream baos = null; try { baos = new ByteArrayOutputStream(1000); final PrintStream ps = new PrintStream(baos); th.printStackTrace(ps); return baos.toString(); } finally { if (baos != null) { try { baos.flush(); baos.close(); } catch (final IOException e) { ignoreException(e, "doesn't make sense to report at close"); } } } } /** * Formats date in accordance with given format * * @param date Date to format * @param format String format used to format Date * @return String with formatted date */ public static String formatDate(final Date date, final String format) { return new SimpleDateFormat(format, Locale.US).format(date); } /** * Gets file name out of file path */ public static String extractNameFromFilePath(final String filePath) { final int lastSlash = filePath.lastIndexOf((int) '/'); return filePath.substring(lastSlash + 1); } /** * Gets file name out of file path */ public static String extractPathFromFilePath(final String filePath) { final int lastSlash = filePath.lastIndexOf((int) '/'); if (lastSlash == -1) { return ""; } else { return filePath.substring(0, lastSlash); } } /** * Converts array of int representing an int-encoded string to a String */ public static String intArrayToString(final int[] array) { final StringBuilder result = new StringBuilder(array.length); for (final int anArray : array) { result.append((char) anArray); } return result.toString(); } /** * Returns <code>true</code> if first character of the string is a letter */ public static boolean isFirstLetter(final String s) { return !isBlank(s) && Pattern.compile("[a-zA-Z]").matcher(s.substring(0, 1)).matches(); } /** * @return <code>true</code> if system property is set and equals given value. */ public static boolean systemPropertyEquals(final String name, final String value) { final String property = System.getProperty(name); return property != null && property.equalsIgnoreCase(value); } /** * @return <code>true</code> this string pattern is empty */ public static boolean patternIsEmpty(final String pattern) { return isBlank(pattern) || !new StringTokenizer(pattern, "\n \r", false).hasMoreTokens(); } /** * Breaks a possibly multiline string to a list of lines. Empty lines are excluded from the list. */ public static List multilineStringToList(final String multilineString) { final List result = new ArrayList(3); if (isBlank(multilineString)) { return result; } for (final StringTokenizer st = new StringTokenizer(multilineString, "\n\r", false); st.hasMoreTokens(); ) { final String s = st.nextToken(); if (isBlank(s)) { continue; } result.add(s.trim()); } return result; } /** * Converts a list of Strings to a String containing items of the list as lines separated by "\n". */ public static String linesToString(final List stringList) { final StringBuilder result = new StringBuilder(300); for (final Object aStringList : stringList) { result.append((String) aStringList).append('\n'); } return result.toString(); } public static String[] toStringArray(final List stringList) { return (String[]) stringList.toArray(STRING_ARRAY_TEMPLATE); } /** * Returns a byte array from a string of hexadecimal digits. */ public static byte[] decodeFromHex(final String hex) { final int len = hex.length(); final byte[] buf = new byte[len + 1 >> 1]; int i = 0; int j = 0; if (len % 2 == 1) { buf[j++] = (byte) fromDigit(hex.charAt(i++)); } while (i < len) { buf[j++] = (byte) (fromDigit(hex.charAt(i++)) << 4 | fromDigit(hex.charAt(i++))); } return buf; } /** * Returns the number from 0 to 15 corresponding to the hex digit <i>ch</i>. */ private static int fromDigit(final char ch) { if (ch >= '0' && ch <= '9') { return (int) ch - (int) '0'; } if (ch >= 'A' && ch <= 'F') { return (int) ch - (int) 'A' + 10; } if (ch >= 'a' && ch <= 'f') { return (int) ch - (int) 'a' + 10; } throw new IllegalArgumentException("invalid hex digit '" + ch + '\''); } /** * Returns a string of hexadecimal digits from a byte array. Each byte is converted to 2 hex symbols. */ public static String encodeToHex( final byte[] ba) { // NOPMD - "A user given array is stored directly" - we do NOT store anything. final int length = ba.length; final char[] buf = new char[length << 1]; for (int i = 0, j = 0; i < length; ) { final int k = ba[i++]; buf[j++] = HEX_DIGITS[k >>> 4 & 0x0F]; buf[j++] = HEX_DIGITS[k & 0x0F]; } return String.valueOf(buf); } /** * Digests password with MD5 and encodes it as a hex String. * * @param password to digest. * @return hex encoded password digest. */ public static String digest(final String password) throws NoSuchAlgorithmException { final MessageDigest messageDigest = MessageDigest.getInstance("MD5"); messageDigest.reset(); messageDigest.update(password.trim().toLowerCase().getBytes()); return encodeToHex(messageDigest.digest()); } public static long daysToMillis(final int days) { return (long) days * 24L * 60L * 60L * 1000L; } /** * Truncates string to maxLen. * * @param in input string * @param maxLen max length */ public static String truncate(final String in, final int maxLen) { if (in == null || in.length() <= maxLen) { return in; } else { return in.substring(0, maxLen); } } public static void appendWithNewLineIfNotNull(final StringBuffer sb, final String label, final String value) { if (!isBlank(value)) { sb.append(label).append(' ').append(value); sb.append("/n"); } } /** * Puts string into double quotes. Other leading and trailing quotes are removed first. * * @param stringToProcess String to quote, trimmed before quoting. * @return double-quoted string. */ public static String putIntoDoubleQuotes(final String stringToProcess) { final char[] dd = stringToProcess.trim().toCharArray(); final int len = dd.length; int st = 0; for (; st < len; st++) { final char c = dd[st]; if (c != CHAR_DOUBLE_QUOTE && c != CHAR_SINGLE_QUOTE) { break; } } int en = len; for (; en > st; en--) { final char c = dd[en - 1]; if (c != CHAR_DOUBLE_QUOTE && c != CHAR_SINGLE_QUOTE) { break; } } //if (log.isDebugEnabled()) log.debug("st: " + st); //if (log.isDebugEnabled()) log.debug("en: " + en); //if (log.isDebugEnabled()) log.debug("stringToProcess: " + "\"" + stringToProcess + "\""); return '\"' + stringToProcess.substring(st, en) + '\"'; } public static String removeDoubleQuotes(final String stringToProcess) { if (stringToProcess.startsWith("\"") && stringToProcess.endsWith("\"")) { return stringToProcess.substring(1, stringToProcess.length() - 1); } else { return stringToProcess; } } public static List split(final String value, final int maxLength) { final List parts = new ArrayList(23); final int originalLength = value.length(); if (originalLength > maxLength) { // split it if necessary final int splitCount = originalLength / maxLength; for (int splitIndex = 0; splitIndex < splitCount; splitIndex++) { parts.add(value.substring(splitIndex * maxLength, (splitIndex + 1) * maxLength)); } // process last piece if any final int leftOverLength = originalLength - splitCount * maxLength; if (leftOverLength > 0) { parts.add(value.substring(originalLength - leftOverLength, originalLength)); } } else { parts.add(value); } return parts; } public static String formatWithTrailingZeroes(final int value, final int zeroes) { final String stringValue = Integer.toString(value); final StringBuilder result = new StringBuilder(5); final int numberOfZeroesToAdd = zeroes - stringValue.length(); for (int i = 0; i < numberOfZeroesToAdd; i++) { result.append('0'); } result.append(stringValue); return result.toString(); } /** * Makes pattern array of compiled regex patterns. */ public static Pattern[] makeRegexPatternsFromMultilineString(final String customPatterns) { final Set result = new HashSet(5); for (final StringTokenizer st = new StringTokenizer(customPatterns, "\n", false); st.hasMoreTokens(); ) { final String pattern = st.nextToken().trim(); if (isRegex(pattern)) { result.add(Pattern.compile(pattern)); } } return (Pattern[]) result.toArray(new Pattern[result.size()]); } /** * @param pattern * @return <code>true</code> if pattern starts with '^' and ends with '$' */ public static boolean isRegex(final String pattern) { return !isBlank(pattern) && pattern.charAt(0) == '^' && pattern.endsWith("$"); } public static boolean isBase64(final String isValidString) { return isArrayByteBase64(isValidString.getBytes()); } public static boolean isBase64(final byte octect) { //shall we ignore white space? JEFF?? return octect == PAD || base64Alphabet[(int) octect] != (byte) -1; } public static boolean isArrayByteBase64(final byte[] arrayOctect) { final int length = arrayOctect.length; if (length == 0) { // shouldn't a 0 length array be valid base64 data? // return false; return true; } for (final byte anArrayOctect : arrayOctect) { if (!isBase64(anArrayOctect)) { return false; } } return true; } /** * Encodes hex octects into Base64. * * @param binaryData Array containing binary data to encode. * @return Base64-encoded data. */ public static byte[] encode(final byte[] binaryData) { final int lengthDataBits = binaryData.length * EIGHTBIT; final int fewerThan24bits = lengthDataBits % TWENTYFOURBITGROUP; final int numberTriplets = lengthDataBits / TWENTYFOURBITGROUP; byte[] encodedData = null; if (fewerThan24bits == 0) { // 16 or 8 bit encodedData = new byte[numberTriplets << 2]; } else { //data not divisible by 24 bit encodedData = new byte[(numberTriplets + 1 << 2)]; } byte k = (byte) 0; byte l = (byte) 0; byte b1 = (byte) 0; byte b2 = (byte) 0; byte b3 = (byte) 0; int encodedIndex = 0; int dataIndex = 0; int i = 0; //log.debug("number of triplets = " + numberTriplets); for (i = 0; i < numberTriplets; i++) { dataIndex = i * 3; b1 = binaryData[dataIndex]; b2 = binaryData[dataIndex + 1]; b3 = binaryData[dataIndex + 2]; //log.debug("b1= " + b1 +", b2= " + b2 + ", b3= " + b3); l = (byte) (b2 & 0x0f); k = (byte) (b1 & 0x03); encodedIndex = i << 2; final byte val1 = (b1 & SIGN) == 0 ? (byte) (b1 >> 2) : (byte) (b1 >> 2 ^ 0xc0); final byte val2 = (b2 & SIGN) == 0 ? (byte) (b2 >> 4) : (byte) (b2 >> 4 ^ 0xf0); final byte val3 = (b3 & SIGN) == 0 ? (byte) (b3 >> 6) : (byte) (b3 >> 6 ^ 0xfc); encodedData[encodedIndex] = lookUpBase64Alphabet[(int) val1]; //log.debug( "val2 = " + val2 ); //log.debug( "k4 = " + (k<<4) ); //log.debug( "vak = " + (val2 | (k<<4)) ); encodedData[encodedIndex + 1] = lookUpBase64Alphabet[val2 | k << 4]; encodedData[encodedIndex + 2] = lookUpBase64Alphabet[l << 2 | val3]; encodedData[encodedIndex + 3] = lookUpBase64Alphabet[b3 & 0x3f]; } // form integral number of 6-bit groups final int dataIndex1 = i * 3; final int encodedIndex1 = i << 2; if (fewerThan24bits == EIGHTBIT) { final byte b11 = binaryData[dataIndex1]; final byte k1 = (byte) (b11 & 0x03); //log.debug("b1=" + b1); //log.debug("b1<<2 = " + (b1>>2) ); final byte val1 = (b11 & SIGN) == 0 ? (byte) (b11 >> 2) : (byte) (b11 >> 2 ^ 0xc0); encodedData[encodedIndex1] = lookUpBase64Alphabet[(int) val1]; encodedData[encodedIndex1 + 1] = lookUpBase64Alphabet[k1 << 4]; encodedData[encodedIndex1 + 2] = PAD; encodedData[encodedIndex1 + 3] = PAD; } else if (fewerThan24bits == SIXTEENBIT) { final byte b11 = binaryData[dataIndex1]; final byte b21 = binaryData[dataIndex1 + 1]; final byte l1 = (byte) (b21 & 0x0f); final byte k1 = (byte) (b11 & 0x03); final byte val1 = (b11 & SIGN) == 0 ? (byte) (b11 >> 2) : (byte) (b11 >> 2 ^ 0xc0); final byte val2 = (b21 & SIGN) == 0 ? (byte) (b21 >> 4) : (byte) (b21 >> 4 ^ 0xf0); encodedData[encodedIndex1] = lookUpBase64Alphabet[(int) val1]; encodedData[encodedIndex1 + 1] = lookUpBase64Alphabet[val2 | k1 << 4]; encodedData[encodedIndex1 + 2] = lookUpBase64Alphabet[l1 << 2]; encodedData[encodedIndex1 + 3] = PAD; } return encodedData; } /** * Decodes Base64 data into octects * * @param base64Data Byte array containing Base64 data * @return Array containing decoded data. */ public static byte[] decode(final byte[] base64Data) { //noinspection ZeroLengthArrayAllocation final byte[] emptyByteArray = {}; // NOPMD // handle the edge case, so we don't have to worry about it later if (base64Data.length == 0) { return emptyByteArray; } // NOPMD final int numberQuadruple = base64Data.length / FOURBYTE; // Throw away anything not in base64Data // this sizes the output array properly - rlw int lastData = base64Data.length; // ignore the '=' padding while (base64Data[lastData - 1] == PAD) { if (--lastData == 0) { return emptyByteArray; // NOPMD } } final byte[] decodedData = new byte[lastData - numberQuadruple]; int dataIndex = 0; int encodedIndex = 0; byte marker1 = (byte) 0; byte marker0 = (byte) 0; byte b4 = (byte) 0; byte b3 = (byte) 0; byte b2 = (byte) 0; byte b1 = (byte) 0; for (int i = 0; i < numberQuadruple; i++) { dataIndex = i << 2; marker0 = base64Data[dataIndex + 2]; marker1 = base64Data[dataIndex + 3]; b1 = base64Alphabet[base64Data[dataIndex]]; b2 = base64Alphabet[base64Data[dataIndex + 1]]; if (marker0 != PAD && marker1 != PAD) { //No PAD e.g 3cQl b3 = base64Alphabet[(int) marker0]; b4 = base64Alphabet[(int) marker1]; decodedData[encodedIndex] = (byte) (b1 << 2 | b2 >> 4); decodedData[encodedIndex + 1] = (byte) ((b2 & 0xf) << 4 | b3 >> 2 & 0xf); decodedData[encodedIndex + 2] = (byte) (b3 << 6 | b4); } else if (marker0 == PAD) { //Two PAD e.g. 3c[Pad][Pad] decodedData[encodedIndex] = (byte) (b1 << 2 | b2 >> 4); } else if (marker1 == PAD) { //One PAD e.g. 3cQ[Pad] b3 = base64Alphabet[(int) marker0]; decodedData[encodedIndex] = (byte) (b1 << 2 | b2 >> 4); decodedData[encodedIndex + 1] = (byte) ((b2 & 0xf) << 4 | b3 >> 2 & 0xf); } encodedIndex += 3; } return decodedData; } /** * Helper method. * * @param s * @return */ public static List makeList(final String s) { final List result = new ArrayList(1); result.add(s); return result; } public static StringBuffer appendChars(final StringBuffer buf, final int charCount, final char c) { for (int i = 0; i < charCount; i++) { buf.append(c); } return buf; } /** * Helper method. * * @param value * @return */ public static boolean toBoolean(final String value) { return value.equalsIgnoreCase(STRING_TRUE) || value.equalsIgnoreCase(STRING_YES) || value.equalsIgnoreCase(STRING_ENABLED); } /** * Transform InetAddress to a pretty-printed string. * * @param address InetAddress to transform. * @return InetAddress as a pretty-printed string. */ public static String toString(final InetAddress address) { return removeLeadingSlash(address.toString()); } public static String toString(final InetSocketAddress endpoint) { return removeLeadingSlash(endpoint.toString()); } /** * Helper method to transform a boolean value to as "YES" or "NO" string. * * @param value boolean value to transform. * @return a String containing "YES" or "NO". * @see #YES * @see #NO */ public static String toYesNo(final boolean value) { return value ? YES : NO; } public static String toString(final Object[] objects) { if (objects == null) { return NULL_AS_STRING; } final StringBuilder sb = new StringBuilder(50); sb.append('['); for (int i = 0; i < objects.length; i++) { final Object o = objects[i]; sb.append(o); if (i < objects.length - 1) { sb.append(", "); } } sb.append(']'); return sb.toString(); } public static void dump(final byte[] b, final PrintStream out) { for (int i = 0; i < b.length; ++i) { if (i % 16 == 0) { out.print(Integer.toHexString(i & 0xFFFF | 0x10000).substring(1, 5) + " - "); } out.print(Integer.toHexString(b[i] & 0xFF | 0x100).substring(1, 3) + ' '); if (i % 16 == 15 || i == b.length - 1) { int j; for (j = 16 - i % 16; j > 1; --j) { out.print(" "); } out.print(" - "); final int start = i / 16 * 16; final int end = b.length < i + 1 ? b.length : i + 1; for (j = start; j < end; ++j) { if (b[j] >= 32 && b[j] <= 126) { out.print((char) b[j]); } else { out.print("."); } } out.println(); } } out.println(); } public static String toString(final IntArrayList list) { final StringBuilder sb = new StringBuilder(20); if (list == null) { sb.append("null"); } else { sb.append('['); sb.append("size:"); final int listSize = list.size(); sb.append(Integer.toString(listSize)); if (!list.isEmpty()) { sb.append("; "); for (int i = 0; i < listSize; i++) { final Object o = list.get(i); sb.append(o); if (i < listSize - 1) { sb.append(','); } } } sb.append(']'); } return sb.toString(); } public static String toShortName(final Class clazz) { final String name = clazz.getName(); return name.substring(name.lastIndexOf('.') + 1); } public static String sizeToString(final Collection collection) { if (collection == null) { return "null"; } else { return Integer.toString(collection.size()); } } public static String sizeToString(final Hash hash) { return hash == null ? "null" : Integer.toString(hash.size()); } public static String sizeToString(final IntArrayList intArrayList) { return intArrayList == null ? "null" : Integer.toString(intArrayList.size()); } public static long readTime(final String stringTime) throws IllegalArgumentException { final Matcher matcher = TIME_PATTERN.matcher(stringTime); if (matcher.matches()) { final String stringValue = matcher.group(1); final String stringMeasure = matcher.group(2).toLowerCase(); final long multiplier; if ("milliseconds".equals(stringMeasure) || "millis".equals(stringMeasure) || "ms".equals(stringMeasure)) { multiplier = 1; } else if ("seconds".equals(stringMeasure) || "secs".equals(stringMeasure) || "s".equals(stringMeasure)) { multiplier = 1000; } else if ("minutes".equals(stringMeasure) || "min".equals(stringMeasure)) { multiplier = 60000; } else { throw new IllegalArgumentException("Unknown measure: " + stringTime); } return Long.parseLong(stringValue) * multiplier; } else { throw new IllegalArgumentException("Unknown time format: " + stringTime); } } /** * Parses a size in bytes. Cacheonix supports bytes, kilobytes (k, kb), megabytes (mb) and gigabytes (gb) as a unit * of measure. Example: parsing "5mb" will return 5000000. * * @param stringBytes the size in bytes. Cacheonix supports bytes, kilobytes (k, kb), megabytes (mb) and gigabytes * (gb) as a unit of measure. Example: "5mb". * @return the size in bytes. Example: parsing "5mb" will return 5000000. * @throws IllegalArgumentException if the stringBytes cannot be parsed. */ public static long readBytes(final String stringBytes) throws IllegalArgumentException { final Matcher matcher = BYTES_PATTERN.matcher(stringBytes); if (!matcher.matches()) { throw new IllegalArgumentException("Unknown byte size format: " + stringBytes); } final String stringValue = matcher.group(1); final String stringMeasure = matcher.group(2).toLowerCase(); if ("b".equals(stringMeasure) || "bytes".equals(stringMeasure)) { return Long.parseLong(stringValue); } else if ("k".equals(stringMeasure) || "kb".equals(stringMeasure) || "kilobytes".equals(stringMeasure)) { return Long.parseLong(stringValue) * KILO_BYTE; } else if ("m".equals(stringMeasure) || "mb".equals(stringMeasure) || "megabytes".equals(stringMeasure)) { return Long.parseLong(stringValue) * MEGA_BYTE; } else if ("g".equals(stringMeasure) || "gb".equals(stringMeasure) || "gigabytes".equals(stringMeasure)) { return Long.parseLong(stringValue) * GIGA_BYTE; } else if ("%".equals(stringMeasure)) { final int percent = Integer.parseInt(stringValue); final int normalizedPercent = percent > 100 ? 100 : percent < 0 ? 0 : percent; return (long) ((double) Runtime.getRuntime().maxMemory() * ((double) normalizedPercent / (double) 100)); } else { throw new IllegalArgumentException("Unknown measure: " + stringBytes); } } private static String removeLeadingSlash(final String str) { final int i = str.indexOf('/'); return i >= 0 ? str.substring(i + 1) : str; } public static InetAddress readInetAddress(final String stringInetAddress) throws IllegalArgumentException { try { return InetAddress.getByName(stringInetAddress); } catch (final UnknownHostException e) { throw new IllegalArgumentException(e); } } }
Refactoring: removed commented out code.
src/org/cacheonix/impl/util/StringUtils.java
Refactoring: removed commented out code.
Java
lgpl-2.1
02e67eef2778709a87f692092af8f9d8ce11cc33
0
brunobuzzi/orbeon-forms,wesley1001/orbeon-forms,evlist/orbeon-forms,joansmith/orbeon-forms,orbeon/orbeon-forms,evlist/orbeon-forms,brunobuzzi/orbeon-forms,orbeon/orbeon-forms,evlist/orbeon-forms,tanbo800/orbeon-forms,tanbo800/orbeon-forms,wesley1001/orbeon-forms,wesley1001/orbeon-forms,joansmith/orbeon-forms,joansmith/orbeon-forms,martinluther/orbeon-forms,tanbo800/orbeon-forms,martinluther/orbeon-forms,joansmith/orbeon-forms,ajw625/orbeon-forms,ajw625/orbeon-forms,martinluther/orbeon-forms,orbeon/orbeon-forms,orbeon/orbeon-forms,ajw625/orbeon-forms,ajw625/orbeon-forms,evlist/orbeon-forms,wesley1001/orbeon-forms,tanbo800/orbeon-forms,martinluther/orbeon-forms,brunobuzzi/orbeon-forms,brunobuzzi/orbeon-forms,evlist/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.sql; import org.apache.log4j.Logger; import org.dom4j.*; import org.jaxen.Function; import org.jaxen.UnresolvableException; import org.jaxen.VariableContext; import org.orbeon.oxf.common.OXFException; import org.orbeon.oxf.common.ValidationException; import org.orbeon.oxf.pipeline.api.PipelineContext; import org.orbeon.oxf.processor.*; import org.orbeon.oxf.resources.OXFProperties; import org.orbeon.oxf.util.*; import org.orbeon.oxf.xml.*; import org.orbeon.oxf.xml.dom4j.LocationData; import org.orbeon.oxf.xml.dom4j.LocationSAXWriter; import org.orbeon.saxon.dom4j.DocumentWrapper; import org.orbeon.saxon.xpath.*; import org.orbeon.saxon.xpath.XPathException; import org.xml.sax.Attributes; import org.xml.sax.ContentHandler; import org.xml.sax.Locator; import org.xml.sax.SAXException; import org.xml.sax.helpers.NamespaceSupport; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.sax.SAXResult; import java.io.InputStream; import java.io.OutputStream; import java.io.Reader; import java.math.BigDecimal; import java.sql.*; import java.sql.Date; import java.util.*; /** * This is the SQL processor implementation. * <p/> * TODO: * <p/> * o batch for mass updates when supported * o esql:use-limit-clause, esql:skip-rows, esql:max-rows * <p/> * o The position() and last() functions are not implemented within * sql:for-each it does not appear to be trivial to implement them, because * they are already defined by default. Probably that playing with the Jaxen * Context object will allow a correct implementation. * <p/> * o debugging facilities, i.e. output full query with replaced parameters (even on PreparedStatement) * o support more types in replace mode * <p/> * o sql:choose, sql:if * o sql:variable * o define variables such as: * o $sql:results (?) * o $sql:column-count * o $sql:update-count * <p/> * o esql:error-results//esql:get-message * o esql:error-results//esql:to-string * o esql:error-results//esql:get-stacktrace * <p/> * o multiple results * o caching options */ public class SQLProcessor extends ProcessorImpl { static Logger logger = LoggerFactory.createLogger(SQLProcessor.class); public static final String SQL_NAMESPACE_URI = "http://orbeon.org/oxf/xml/sql"; private static final String INPUT_DATASOURCE = "datasource"; public static final String SQL_DATASOURCE_URI = "http://www.orbeon.org/oxf/sql-datasource"; // private static final String SQL_TYPE_VARCHAR = "varchar"; private static final String SQL_TYPE_CLOB = "clob"; private static final String SQL_TYPE_BLOB = "blob"; private static final String SQL_TYPE_XMLTYPE = "xmltype"; public SQLProcessor() { // Mandatory config input addInputInfo(new ProcessorInputOutputInfo(INPUT_CONFIG, SQL_NAMESPACE_URI)); // Optional datasource input addInputInfo(new ProcessorInputOutputInfo(INPUT_DATASOURCE, SQL_DATASOURCE_URI)); // Optional data input and output addInputInfo(new ProcessorInputOutputInfo(INPUT_DATA)); // For now don't declare it, because it causes problems // addOutputInfo(new ProcessorInputOutputInfo(OUTPUT_DATA)); } public ProcessorOutput createOutput(String name) { // This will be called only if there is an output ProcessorOutput output = new ProcessorOutputImpl(getClass(), name) { public void readImpl(PipelineContext context, ContentHandler contentHandler) { execute(context, contentHandler); } }; addOutput(name, output); return output; } public void start(PipelineContext context) { // This will be called only if no output is connected execute(context, new NullSerializer.NullContentHandler()); } private static class Config { public Config(SAXStore configInput, boolean useXPathExpressions, List xpathExpressions) { this.configInput = configInput; this.useXPathExpressions = useXPathExpressions; this.xpathExpressions = xpathExpressions; } public SAXStore configInput; public boolean useXPathExpressions; public List xpathExpressions; } protected void execute(final PipelineContext context, ContentHandler contentHandler) { try { // Cache, read and interpret the config input Config config = (Config) readCacheInputAsObject(context, getInputByName(INPUT_CONFIG), new CacheableInputReader() { public Object read(PipelineContext context, ProcessorInput input) { // Read the config input document Node config = readInputAsDOM4J(context, input); Document configDocument = config.getDocument(); // Extract XPath expressions and also check whether any XPath expression is used at all // NOTE: This could be done through streaming below as well // NOTE: For now, just match <sql:param select="/*" type="xs:base64Binary"/> List xpathExpressions = new ArrayList(); boolean useXPathExpressions = false; for (Iterator i = XPathUtils.selectIterator(configDocument, "//*[namespace-uri() = '" + SQL_NAMESPACE_URI + "' and @select]"); i.hasNext();) { Element element = (Element) i.next(); useXPathExpressions = true; String typeAttribute = element.attributeValue("type"); if ("xs:base64Binary".equals(typeAttribute)) { String selectAttribute = element.attributeValue("select"); xpathExpressions.add(selectAttribute); } } // Normalize spaces. What this does is to coalesce adjacent text nodes, and to remove // resulting empty text, unless the text is contained within a sql:text element. configDocument.accept(new VisitorSupport() { private boolean endTextSequence(Element element, Text previousText) { if (previousText != null) { String value = previousText.getText(); if (value == null || value.trim().equals("")) { element.remove(previousText); return true; } } return false; } public void visit(Element element) { // Don't touch text within sql:text elements if (!SQL_NAMESPACE_URI.equals(element.getNamespaceURI()) || !"text".equals(element.getName())) { Text previousText = null; for (int i = 0, size = element.nodeCount(); i < size;) { Node node = element.node(i); if (node instanceof Text) { Text text = (Text) node; if (previousText != null) { previousText.appendText(text.getText()); element.remove(text); } else { String value = text.getText(); // Remove empty text nodes if (value == null || value.length() < 1) { element.remove(text); } else { previousText = text; i++; } } } else { if (!endTextSequence(element, previousText)) i++; previousText = null; } } endTextSequence(element, previousText); } } }); // Create SAXStore try { SAXStore store = new SAXStore(); LocationSAXWriter saxw = new LocationSAXWriter(); saxw.setContentHandler(store); saxw.write(configDocument); // Return the normalized document return new Config(store, useXPathExpressions, xpathExpressions); } catch (SAXException e) { throw new OXFException(e); } } }); // Either read the whole input as a DOM, or try to serialize Node data = null; XPathContentHandler xpathContentHandler = null; // Check if the data input is connected boolean hasDataInput = getConnectedInputs().get(INPUT_DATA) != null; if (!hasDataInput && config.useXPathExpressions) throw new OXFException("The data input must be connected when the configuration uses XPath expressions."); if (!hasDataInput || !config.useXPathExpressions) { // Just use an empty document data = XMLUtils.NULL_DOCUMENT; } else { // There is a data input connected and there are some XPath epxressions operating on it boolean useXPathContentHandler = false; if (config.xpathExpressions.size() > 0) { // Create XPath content handler final XPathContentHandler _xpathContentHandler = new XPathContentHandler(); // Add expressions and check whether we can try to stream useXPathContentHandler = true; for (Iterator i = config.xpathExpressions.iterator(); i.hasNext();) { String expression = (String) i.next(); boolean canStream = _xpathContentHandler.addExpresssion(expression, false);// FIXME: boolean nodeSet if (!canStream) { useXPathContentHandler = false; break; } } // Finish setting up the XPathContentHandler if (useXPathContentHandler) { _xpathContentHandler.setReadInputCallback(new Runnable() { public void run() { readInputAsSAX(context, INPUT_DATA, _xpathContentHandler); } }); xpathContentHandler = _xpathContentHandler; } } // If we can't stream, read everything in if (!useXPathContentHandler) data = readInputAsDOM4J(context, INPUT_DATA); } // Try to read datasource input if any Datasource datasource = null; { List datasourceInputs = (List) getConnectedInputs().get(INPUT_DATASOURCE); if (datasourceInputs != null) { if (datasourceInputs.size() > 1) throw new OXFException("At most one one datasource input can be connected."); ProcessorInput datasourceInput = (ProcessorInput) datasourceInputs.get(0); datasource = Datasource.getDatasource(context, this, datasourceInput); } } // Replay the config SAX store through the interpreter config.configInput.replay(new RootInterpreter(context, getPropertySet(), data, datasource, xpathContentHandler, contentHandler)); } catch (OXFException e) { throw e; } catch (Exception e) { throw new OXFException(e); } } private static class ExecuteInterpreter extends InterpreterContentHandler { public ExecuteInterpreter(SQLProcessorInterpreterContext interpreterContext) { super(interpreterContext, true); } public void start(String uri, String localname, String qName, Attributes attributes) throws SAXException { SQLProcessorInterpreterContext interpreterContext = getInterpreterContext(); interpreterContext.pushResultSet(); addElementHandler(new QueryInterpreter(interpreterContext, QueryInterpreter.QUERY), SQL_NAMESPACE_URI, "query"); addElementHandler(new QueryInterpreter(interpreterContext, QueryInterpreter.UPDATE), SQL_NAMESPACE_URI, "update"); addElementHandler(new ResultsInterpreter(interpreterContext), SQL_NAMESPACE_URI, "results"); addElementHandler(new NoResultsInterpreter(interpreterContext), SQL_NAMESPACE_URI, "no-results"); ValueOfCopyOfInterpreter valueOfCopyOfInterpreter = new ValueOfCopyOfInterpreter(interpreterContext); addElementHandler(valueOfCopyOfInterpreter, SQL_NAMESPACE_URI, "value-of"); addElementHandler(valueOfCopyOfInterpreter, SQL_NAMESPACE_URI, "copy-of"); addElementHandler(new TextInterpreter(interpreterContext), SQL_NAMESPACE_URI, "text"); addElementHandler(new ForEachInterpreter(getInterpreterContext(), getElementHandlers()), SQL_NAMESPACE_URI, "for-each"); } public void end(String uri, String localname, String qName) throws SAXException { SQLProcessorInterpreterContext interpreterContext = getInterpreterContext(); PreparedStatement stmt = interpreterContext.getStatement(0); if (stmt != null) { try { stmt.close(); } catch (SQLException e) { throw new ValidationException(e, new LocationData(getDocumentLocator())); } } interpreterContext.popResultSet(); } } private static class ResultsInterpreter extends InterpreterContentHandler { public ResultsInterpreter(SQLProcessorInterpreterContext interpreterContext) { super(interpreterContext, false); } public void start(String uri, String localname, String qName, Attributes attributes) throws SAXException { if (!getInterpreterContext().isEmptyResultSet()) { setForward(true); addElementHandler(new RowResultsInterpreter(getInterpreterContext()), SQL_NAMESPACE_URI, "row-results"); ValueOfCopyOfInterpreter valueOfCopyOfInterpreter = new ValueOfCopyOfInterpreter(getInterpreterContext()); addElementHandler(valueOfCopyOfInterpreter, SQL_NAMESPACE_URI, "value-of"); addElementHandler(valueOfCopyOfInterpreter, SQL_NAMESPACE_URI, "copy-of"); addElementHandler(new TextInterpreter(getInterpreterContext()), SQL_NAMESPACE_URI, "text"); // We must not be able to have a RowResultsInterpreter within the for-each // This must be checked in the schema addElementHandler(new ForEachInterpreter(getInterpreterContext(), getElementHandlers()), SQL_NAMESPACE_URI, "for-each"); } } public void end(String uri, String localname, String qName) throws SAXException { SQLProcessorInterpreterContext interpreterContext = getInterpreterContext(); PreparedStatement stmt = interpreterContext.getStatement(0); if (stmt != null) { try { stmt.close(); interpreterContext.setStatement(null); } catch (SQLException e) { throw new ValidationException(e, new LocationData(getDocumentLocator())); } } } } private static class GetterInterpreter extends InterpreterContentHandler { private ResultSetMetaData metadata; public GetterInterpreter(SQLProcessorInterpreterContext interpreterContext) { super(interpreterContext, false); } /** * Return a Clob or Clob object or a String */ public static Object interpretSimpleGetter(SQLProcessorInterpreterContext interpreterContext, Locator locator, String getterName, String columnName, int level) { try { ResultSet resultSet = interpreterContext.getResultSet(level); int columnType = resultSet.getMetaData().getColumnType(resultSet.findColumn(columnName)); if (columnType == Types.CLOB) { // The actual column is a CLOB if ("get-string".equals(getterName)) { return resultSet.getClob(columnName); } else { throw new ValidationException("Illegal getter type for CLOB: " + getterName, new LocationData(locator)); } } else if (columnType == Types.BLOB) { // The actual column is a BLOB if ("get-base64binary".equals(getterName)) { return resultSet.getBlob(columnName); } else { throw new ValidationException("Illegal getter type for BLOB: " + getterName, new LocationData(locator)); } } else if (columnType == Types.BINARY || columnType == Types.VARBINARY || columnType == Types.LONGVARBINARY) { // The actual column is binary if ("get-base64binary".equals(getterName)) { return resultSet.getBinaryStream(columnName); } else { throw new ValidationException("Illegal getter type for BINARY, VARBINARY or LONGVARBINARY column: " + getterName, new LocationData(locator)); } } else { // The actual column is not a CLOB or BLOB, in which case we use regular ResultSet getters if ("get-string".equals(getterName)) { return resultSet.getString(columnName); } else if ("get-int".equals(getterName)) { int value = resultSet.getInt(columnName); if (resultSet.wasNull()) return null; return Integer.toString(value); } else if ("get-double".equals(getterName)) { double value = resultSet.getDouble(columnName); // For XPath 1.0, we have to get rid of the scientific notation return resultSet.wasNull() ? null : XMLUtils.removeScientificNotation(value); } else if ("get-float".equals(getterName)) { float value = resultSet.getFloat(columnName); // For XPath 1.0, we have to get rid of the scientific notation return resultSet.wasNull() ? null : XMLUtils.removeScientificNotation(value); } else if ("get-decimal".equals(getterName)) { BigDecimal value = resultSet.getBigDecimal(columnName); return (resultSet.wasNull()) ? null : value.toString(); } else if ("get-boolean".equals(getterName)) { boolean value = resultSet.getBoolean(columnName); if (resultSet.wasNull()) return null; return value ? "true" : "false"; } else if ("get-date".equals(getterName)) { Date value = resultSet.getDate(columnName); if (value == null) return null; return ISODateUtils.formatDate(value, ISODateUtils.XS_DATE); } else if ("get-timestamp".equals(getterName)) { Timestamp value = resultSet.getTimestamp(columnName); if (value == null) return null; return ISODateUtils.formatDate(value, ISODateUtils.XS_DATE_TIME_LONG); } else { throw new ValidationException("Illegal getter name: " + getterName, new LocationData(locator)); } } } catch (SQLException e) { throw new ValidationException("Exception while getting column: " + columnName + " at " + e.toString() , new LocationData(locator)); } } private static final Map typesToGetterNames = new HashMap(); static { typesToGetterNames.put("xs:string", "get-string"); typesToGetterNames.put("xs:int", "get-int"); typesToGetterNames.put("xs:boolean", "get-boolean"); typesToGetterNames.put("xs:decimal", "get-decimal"); typesToGetterNames.put("xs:float", "get-float"); typesToGetterNames.put("xs:double", "get-double"); typesToGetterNames.put("xs:dateTime", "get-timestamp"); typesToGetterNames.put("xs:date", "get-date"); typesToGetterNames.put("xs:base64Binary", "get-base64binary"); } /** * Return a Clob or Blob object or a String */ public static Object interpretGenericGetter(SQLProcessorInterpreterContext interpreterContext, Locator locator, String type, String columnName, int level) { String getterName = (String) typesToGetterNames.get(type); if (getterName == null) throw new ValidationException("Incorrect or missing type attribute for sql:get-column: " + type, new LocationData(locator)); return interpretSimpleGetter(interpreterContext, locator, getterName, columnName, level); } private int getColumnsLevel; private String getColumnsFormat; private String getColumnsPrefix; private boolean getColumnsAllElements; private boolean inExclude; private StringBuffer getColumnsCurrentExclude; private Map getColumnsExcludes; public void characters(char[] chars, int start, int length) throws SAXException { if (inExclude) getColumnsCurrentExclude.append(chars, start, length); else super.characters(chars, start, length); } public void start(String uri, String localname, String qName, Attributes attributes) throws SAXException { final SQLProcessorInterpreterContext interpreterContext = getInterpreterContext(); interpreterContext.getNamespaceSupport().pushContext(); try { String levelString = attributes.getValue("ancestor"); int level = (levelString == null) ? 0 : Integer.parseInt(levelString); ResultSet rs = interpreterContext.getResultSet(level); if ("get-columns".equals(localname)) { // Remember attributes getColumnsLevel = level; getColumnsFormat = attributes.getValue("format"); getColumnsPrefix = attributes.getValue("prefix"); getColumnsAllElements = "true".equals(attributes.getValue("all-elements")); } else if ("get-column".equals(localname)) { String type = attributes.getValue("type"); String columnName = attributes.getValue("column"); if ("oxf:xmlFragment".equals(type)) { // XML fragment if (metadata == null) metadata = rs.getMetaData(); int columnIndex = rs.findColumn(columnName); int columnType = metadata.getColumnType(columnIndex); String columnTypeName = metadata.getColumnTypeName(columnIndex); if (columnType == Types.CLOB) { // The fragment is stored as a Clob Clob clob = rs.getClob(columnName); if (clob != null) { Reader reader = clob.getCharacterStream(); try { XMLUtils.parseDocumentFragment(reader, interpreterContext.getOutput()); } finally { reader.close(); } } } else if (interpreterContext.getDelegate().isXMLType(columnType, columnTypeName)) { // The fragment is stored as a native XMLType org.w3c.dom.Node node = interpreterContext.getDelegate().getDOM(rs, columnName); if (node != null) { TransformerUtils.getIdentityTransformer().transform(new DOMSource(node), new SAXResult(new ForwardingContentHandler() { protected ContentHandler getContentHandler() { return interpreterContext.getOutput(); } public void endDocument() { } public void startDocument() { } })); } } else { // The fragment is stored as a String String value = rs.getString(columnName); if (value != null) XMLUtils.parseDocumentFragment(value, interpreterContext.getOutput()); } } else { // xs:* Object o = interpretGenericGetter(interpreterContext, getDocumentLocator(), type, columnName, level); if (o != null) { if (o instanceof Clob) { Reader reader = ((Clob) o).getCharacterStream(); try { XMLUtils.readerToCharacters(reader, interpreterContext.getOutput()); } finally { reader.close(); } } else if (o instanceof Blob) { InputStream is = ((Blob) o).getBinaryStream(); try { XMLUtils.inputStreamToBase64Characters(is, interpreterContext.getOutput()); } finally { is.close(); } } else if (o instanceof InputStream) { InputStream is = (InputStream) o; try { XMLUtils.inputStreamToBase64Characters(is, interpreterContext.getOutput()); } finally { is.close(); } } else { XMLUtils.objectToCharacters(o, interpreterContext.getOutput()); } } } } else { // Simple getter (deprecated) Object o = interpretSimpleGetter(interpreterContext, getDocumentLocator(), localname, attributes.getValue("column"), level); if (o != null) { if (o instanceof Clob) { Reader reader = ((Clob) o).getCharacterStream(); try { XMLUtils.readerToCharacters(reader, interpreterContext.getOutput()); } finally { reader.close(); } } else if (o instanceof Blob) { InputStream is = ((Blob) o).getBinaryStream(); try { XMLUtils.inputStreamToBase64Characters(is, interpreterContext.getOutput()); } finally { is.close(); } } else if (o instanceof InputStream) { InputStream is = (InputStream) o; try { XMLUtils.inputStreamToBase64Characters(is, interpreterContext.getOutput()); } finally { is.close(); } } else { XMLUtils.objectToCharacters(o, interpreterContext.getOutput()); } } } } catch (Exception e) { throw new ValidationException(e, new LocationData(getDocumentLocator())); } } public void startElement(String uri, String localname, String qName, Attributes attributes) throws SAXException { if ("exclude".equals(localname)) { // Collect excludes if (getColumnsExcludes == null) getColumnsExcludes = new HashMap(); getColumnsCurrentExclude = new StringBuffer(); inExclude = true; } } public void endElement(String uri, String localname, String qName) throws SAXException { if ("exclude".equals(localname)) { // Add current exclude String value = getColumnsCurrentExclude.toString().toLowerCase(); getColumnsExcludes.put(value, value); inExclude = false; } } public void end(String uri, String localname, String qName) throws SAXException { SQLProcessorInterpreterContext interpreterContext = getInterpreterContext(); try { if ("get-columns".equals(localname)) { // Do nothing except collect sql:exclude ResultSet resultSet = interpreterContext.getResultSet(getColumnsLevel); if (metadata == null) metadata = resultSet.getMetaData(); NamespaceSupport namespaceSupport = interpreterContext.getNamespaceSupport(); // for (Enumeration e = namespaceSupport.getPrefixes(); e.hasMoreElements();) { // String p = (String) e.nextElement(); // String u = namespaceSupport.getURI(p); // System.out.println("Prefix: " + p + " -> " + u); // } // Get format once for all columns // Get URI once for all columns String outputElementURI = (getColumnsPrefix == null) ? "" : namespaceSupport.getURI(getColumnsPrefix); if (outputElementURI == null) throw new ValidationException("Invalid namespace prefix: " + getColumnsPrefix, new LocationData(getDocumentLocator())); // Iterate through all columns for (int i = 1; i <= metadata.getColumnCount(); i++) { // Get column name String columnName = metadata.getColumnName(i); // Make sure it is not excluded if (getColumnsExcludes != null && getColumnsExcludes.get(columnName.toLowerCase()) != null) continue; // Process column int columnType = metadata.getColumnType(i); String stringValue = null; Clob clobValue = null; Blob blobValue = null; if (columnType == Types.DATE) { Date value = resultSet.getDate(i); if (value != null) stringValue = ISODateUtils.formatDate(value, ISODateUtils.XS_DATE); } else if (columnType == Types.TIMESTAMP) { Timestamp value = resultSet.getTimestamp(i); if (value != null) stringValue = ISODateUtils.formatDate(value, ISODateUtils.XS_DATE_TIME_LONG); } else if (columnType == Types.DECIMAL || columnType == Types.NUMERIC) { BigDecimal value = resultSet.getBigDecimal(i); stringValue = (resultSet.wasNull()) ? null : value.toString(); } else if (columnType == 16) {// Types.BOOLEAN is present from JDK 1.4 only boolean value = resultSet.getBoolean(i); stringValue = (resultSet.wasNull()) ? null : (value ? "true" : "false"); } else if (columnType == Types.INTEGER || columnType == Types.SMALLINT || columnType == Types.TINYINT || columnType == Types.BIGINT) { long value = resultSet.getLong(i); stringValue = (resultSet.wasNull()) ? null : Long.toString(value); } else if (columnType == Types.DOUBLE || columnType == Types.FLOAT || columnType == Types.REAL) { double value = resultSet.getDouble(i); // For XPath 1.0, we have to get rid of the scientific notation stringValue = resultSet.wasNull() ? null : XMLUtils.removeScientificNotation(value); } else if (columnType == Types.CLOB) { clobValue = resultSet.getClob(i); } else if (columnType == Types.BLOB) { blobValue = resultSet.getBlob(i); } else { // Assume the type is compatible with getString() stringValue = resultSet.getString(i); } final boolean nonNullValue = stringValue != null || clobValue != null || blobValue != null; if (nonNullValue || getColumnsAllElements) { // Format element name String elementName = columnName; if ("xml".equals(getColumnsFormat)) { elementName = elementName.toLowerCase(); elementName = elementName.replace('_', '-'); } else if (getColumnsFormat != null) throw new ValidationException("Invalid get-columns format: " + getColumnsFormat, new LocationData(getDocumentLocator())); String elementQName = (outputElementURI.equals("")) ? elementName : getColumnsPrefix + ":" + elementName; ContentHandler output = interpreterContext.getOutput(); output.startElement(outputElementURI, elementName, elementQName, XMLUtils.EMPTY_ATTRIBUTES); // Output value if non-null if (nonNullValue) { if (clobValue == null && blobValue == null) { // Just output the String value as characters char[] localCharValue = stringValue.toCharArray(); output.characters(localCharValue, 0, localCharValue.length); } else if (clobValue != null) { // Clob: convert the Reader into characters Reader reader = clobValue.getCharacterStream(); try { XMLUtils.readerToCharacters(reader, output); } finally { reader.close(); } } else { // Blob: convert the InputStream into characters in Base64 InputStream is = blobValue.getBinaryStream(); try { XMLUtils.inputStreamToBase64Characters(is, output); } finally { is.close(); } } } output.endElement(outputElementURI, elementName, elementQName); } } } } catch (Exception e) { throw new ValidationException(e, new LocationData(getDocumentLocator())); } interpreterContext.getNamespaceSupport().popContext(); } } private static class ValueOfCopyOfInterpreter extends InterpreterContentHandler { DocumentWrapper wrapper; public ValueOfCopyOfInterpreter(SQLProcessorInterpreterContext interpreterContext) { super(interpreterContext, false); this.wrapper = new DocumentWrapper(interpreterContext.getCurrentNode().getDocument(), null); } public void start(String uri, String localname, String qName, Attributes attributes) throws SAXException { final SQLProcessorInterpreterContext interpreterContext = getInterpreterContext(); NamespaceSupport namespaceSupport = interpreterContext.getNamespaceSupport(); ContentHandler output = interpreterContext.getOutput(); namespaceSupport.pushContext(); try { String selectString = attributes.getValue("select"); // Variable context (obsolete) VariableContext variableContext = new VariableContext() { public Object getVariableValue(String namespaceURI, String prefix, String localName) throws UnresolvableException { if (!SQL_NAMESPACE_URI.equals(namespaceURI)) throw new UnresolvableException("Unbound variable: {" + namespaceURI + "}" + localName); if ("row-position".equals(localName)) { return new Integer(interpreterContext.getRowPosition()); } else throw new UnresolvableException("Unbound variable: {" + namespaceURI + "}" + localName); } }; // Interpret expression Object result = XPathUtils.selectObjectValue(interpreterContext.getCurrentNode(), selectString, interpreterContext.getPrefixesMap(), variableContext, interpreterContext.getFunctionContext()); if ("value-of".equals(localname) || "copy-of".equals(localname)) { // Case of Number and String if (result instanceof Number) { String stringValue; if (result instanceof Float || result instanceof Double) { stringValue = XMLUtils.removeScientificNotation(((Number) result).doubleValue()); } else { stringValue = Long.toString(((Number) result).longValue()); } // FIXME: what about BigDecimal and BigInteger: can they be returned? output.characters(stringValue.toCharArray(), 0, stringValue.length()); } else if (result instanceof String) { String stringValue = (String) result; output.characters(stringValue.toCharArray(), 0, stringValue.length()); } else if (result instanceof List) { if ("value-of".equals(localname)) { // Get string value // String stringValue = interpreterContext.getInput().createXPath(".").valueOf(result); // String stringValue = XPathCache.createCacheXPath(null, ".").valueOf(result); PooledXPathExpression expr = XPathCache.getXPathExpression(interpreterContext.getPipelineContext(), wrapper.wrap(result), "string(.)"); String stringValue; try { stringValue = (String)expr.evaluateSingle(); } catch (XPathException e) { throw new OXFException(e); } finally { if(expr != null) expr.returnToPool(); } output.characters(stringValue.toCharArray(), 0, stringValue.length()); } else { LocationSAXWriter saxw = new LocationSAXWriter(); saxw.setContentHandler(output); for (Iterator i = ((List) result).iterator(); i.hasNext();) { Node node = (Node) i.next(); saxw.write(node); } } } else if (result instanceof Node) { if ("value-of".equals(localname)) { // Get string value // String stringValue = interpreterContext.getInput().createXPath(".").valueOf(result); // String stringValue = XPathCache.createCacheXPath(null, ".").valueOf(result); PooledXPathExpression expr = XPathCache.getXPathExpression(interpreterContext.getPipelineContext(), wrapper.wrap(result), "string(.)"); String stringValue; try { stringValue = (String)expr.evaluateSingle(); } catch (XPathException e) { throw new OXFException(e); } finally { if(expr != null) expr.returnToPool(); } output.characters(stringValue.toCharArray(), 0, stringValue.length()); } else { LocationSAXWriter saxw = new LocationSAXWriter(); saxw.setContentHandler(output); saxw.write((Node) result); } } else throw new OXFException("Unexpected XPath result type: " + result.getClass()); } else { throw new OXFException("Invalid element: " + qName); } } catch (Exception e) { throw new ValidationException(e, new LocationData(getDocumentLocator())); } } public void end(String uri, String localname, String qName) throws SAXException { getInterpreterContext().getNamespaceSupport().popContext(); } } private static class RowResultsInterpreter extends InterpreterContentHandler { private SAXStore saxStore; private ContentHandler savedOutput; private class Group { private String columnName; private String columnValue; private SAXStore footer = new SAXStore(); private boolean showHeader; public Group(String columnName, ResultSet resultSet) throws SQLException { this.columnName = columnName; this.columnValue = resultSet.getString(columnName); } public boolean columnChanged(ResultSet resultSet) throws SQLException { String newValue = resultSet.getString(columnName); return (columnValue != null && !columnValue.equals(newValue)) || (newValue != null && !newValue.equals(columnValue)); } public void setColumnValue(ResultSet resultSet) throws SQLException { this.columnValue = resultSet.getString(columnName); } public boolean isShowHeader() { return showHeader; } public void setShowHeader(boolean showHeader) { this.showHeader = showHeader; } public SAXStore getFooter() { return footer; } } public RowResultsInterpreter(SQLProcessorInterpreterContext interpreterContext) { super(interpreterContext, false); } public void start(String uri, String localname, String qName, Attributes attributes) throws SAXException { // Only forward if the result set is not empty if (!getInterpreterContext().isEmptyResultSet()) { saxStore = new SAXStore(); saxStore.setDocumentLocator(getDocumentLocator()); savedOutput = getInterpreterContext().getOutput(); getInterpreterContext().setOutput(saxStore); setForward(true); } } public void end(String uri, String localname, String qName) throws SAXException { if (saxStore != null) { final SQLProcessorInterpreterContext interpreterContext = getInterpreterContext(); interpreterContext.setOutput(savedOutput); final ResultSet resultSet = interpreterContext.getResultSet(0); try { boolean hasNext = true; final int[] rowNum = {1}; final int[] groupCount = {0}; final List groups = new ArrayList(); // Interpret row-results for each result-set row InterpreterContentHandler contentHandler = new InterpreterContentHandler(interpreterContext, true) { public void startPrefixMapping(String prefix, String uri) throws SAXException { super.startPrefixMapping(prefix, uri); interpreterContext.declarePrefix(prefix, uri); } private boolean hiding; public void startElement(String uri, String localname, String qName, Attributes attributes) throws SAXException { if (!isInElementHandler() && SQL_NAMESPACE_URI.equals(uri)) { if (localname.equals("group")) { try { ResultSet resultSet = interpreterContext.getResultSet(0); // Save group information if first row if (rowNum[0] == 1) { groups.add(new Group(attributes.getValue("column"), resultSet)); } // Get current group information Group currentGroup = (Group) groups.get(groupCount[0]); if (rowNum[0] == 1 || columnChanged(resultSet, groups, groupCount[0])) { // Need to display group's header and footer currentGroup.setShowHeader(true); hiding = false; currentGroup.setColumnValue(resultSet); } else { // Hide group's header currentGroup.setShowHeader(false); hiding = true; } groupCount[0]++; } catch (SQLException e) { throw new ValidationException(e, new LocationData(getDocumentLocator())); } } else if (localname.equals("member")) { hiding = false; } else if (!hiding) { super.startElement(uri, localname, qName, attributes); } } else if (!hiding) { super.startElement(uri, localname, qName, attributes); } } public void endElement(String uri, String localname, String qName) throws SAXException { if (!isInElementHandler() && SQL_NAMESPACE_URI.equals(uri)) { if (localname.equals("group")) { groupCount[0]--; // Restore sending to the regular output Group currentGroup = (Group) groups.get(groupCount[0]); if (currentGroup.isShowHeader()) interpreterContext.setOutput(savedOutput); } else if (localname.equals("member")) { Group currentGroup = (Group) groups.get(groupCount[0] - 1); // The first time, everything is sent to the footer SAXStore if (currentGroup.isShowHeader()) { savedOutput = interpreterContext.getOutput(); interpreterContext.setOutput(currentGroup.getFooter()); hiding = false; } else hiding = true; } else if (!hiding) { super.endElement(uri, localname, qName); } } else if (!hiding) { super.endElement(uri, localname, qName); } } public void characters(char[] chars, int start, int length) throws SAXException { if (!hiding) { // Output only if the string is non-blank [FIXME: Incorrect white space handling!] // String s = new String(chars, start, length); // if (!s.trim().equals("")) super.characters(chars, start, length); } } }; // Initialize the content handler contentHandler.addElementHandler(new ExecuteInterpreter(interpreterContext), SQL_NAMESPACE_URI, "execute"); GetterInterpreter getterInterpreter = new GetterInterpreter(interpreterContext); contentHandler.addElementHandler(getterInterpreter, SQL_NAMESPACE_URI, "get-string"); contentHandler.addElementHandler(getterInterpreter, SQL_NAMESPACE_URI, "get-int"); contentHandler.addElementHandler(getterInterpreter, SQL_NAMESPACE_URI, "get-double"); contentHandler.addElementHandler(getterInterpreter, SQL_NAMESPACE_URI, "get-decimal"); contentHandler.addElementHandler(getterInterpreter, SQL_NAMESPACE_URI, "get-date"); contentHandler.addElementHandler(getterInterpreter, SQL_NAMESPACE_URI, "get-timestamp"); contentHandler.addElementHandler(getterInterpreter, SQL_NAMESPACE_URI, "get-column"); contentHandler.addElementHandler(getterInterpreter, SQL_NAMESPACE_URI, "get-columns"); ValueOfCopyOfInterpreter valueOfCopyOfInterpreter = new ValueOfCopyOfInterpreter(interpreterContext); contentHandler.addElementHandler(valueOfCopyOfInterpreter, SQL_NAMESPACE_URI, "value-of"); contentHandler.addElementHandler(valueOfCopyOfInterpreter, SQL_NAMESPACE_URI, "copy-of"); contentHandler.addElementHandler(new TextInterpreter(interpreterContext), SQL_NAMESPACE_URI, "text"); contentHandler.addElementHandler(new ForEachInterpreter(getInterpreterContext(), contentHandler.getElementHandlers()), SQL_NAMESPACE_URI, "for-each"); // Functions in this context Map functions = new HashMap(); functions.put("{" + SQL_NAMESPACE_URI + "}" + "row-position", new Function() { public Object call(org.jaxen.Context context, List args) { return new Integer(interpreterContext.getRowPosition()); } }); interpreterContext.pushFunctions(functions); try { // Iterate through the result set while (hasNext) { // Output footers that need it if (groups != null) { for (int i = groups.size() - 1; i >= 0; i--) { Group g1 = (Group) groups.get(i); if (columnChanged(resultSet, groups, i)) { g1.getFooter().replay(interpreterContext.getOutput()); g1.getFooter().clear(); } } groupCount[0] = 0; } // Set variables interpreterContext.setRowPosition(rowNum[0]); // Interpret row saxStore.replay(contentHandler); // Go to following row hasNext = resultSet.next(); rowNum[0]++; } // Output last footers for (int i = groups.size() - 1; i >= 0; i--) { Group group = (Group) groups.get(i); group.getFooter().replay(interpreterContext.getOutput()); group.getFooter().clear(); } } finally { interpreterContext.popFunctions(); } } catch (Exception e) { throw new ValidationException(e, new LocationData(getDocumentLocator())); } } } private boolean columnChanged(ResultSet resultSet, List groups, int level) throws SQLException { for (int i = level; i >= 0; i--) { Group group = (Group) groups.get(i); if (group.columnChanged(resultSet)) return true; } return false; } } private static class ForEachInterpreter extends InterpreterContentHandler { private Map elementHandlers; private SAXStore saxStore; private ContentHandler savedOutput; private String select; public ForEachInterpreter(SQLProcessorInterpreterContext interpreterContext, Map elementHandlers) { super(interpreterContext, false); this.elementHandlers = elementHandlers; } public void start(String uri, String localname, String qName, Attributes attributes) throws SAXException { // Everything will be stored in a SAXStore saxStore = new SAXStore(); saxStore.setDocumentLocator(getDocumentLocator()); savedOutput = getInterpreterContext().getOutput(); getInterpreterContext().setOutput(saxStore); setForward(true); // Get attributes select = attributes.getValue("select"); } public void end(String uri, String localname, String qName) throws SAXException { if (saxStore != null) { final SQLProcessorInterpreterContext interpreterContext = getInterpreterContext(); // Restore the regular output interpreterContext.setOutput(savedOutput); try { // Create a new InterpreterContentHandler with the same handlers as our parent InterpreterContentHandler contentHandler = new InterpreterContentHandler(interpreterContext, true); contentHandler.setElementHandlers(elementHandlers); // Scope functions final Node[] currentNode = new Node[1]; final int[] currentPosition = new int[1]; Map functions = new HashMap(); functions.put("current", new Function() { public Object call(org.jaxen.Context context, List args) { return currentNode[0]; } }); // FIXME: position() won't work because it will override // the default XPath position() function // We probably need to create a Jaxen Context directly to fix this // functions.put("position", new Function() { // public Object call(org.jaxen.Context context, List args) throws FunctionCallException { // return new Integer(currentPosition[0]); // } // }); interpreterContext.pushFunctions(functions); try { // Iterate through the result set int nodeCount = 1; for (Iterator i = XPathUtils.selectIterator(interpreterContext.getCurrentNode(), select, interpreterContext.getPrefixesMap(), null, interpreterContext.getFunctionContext()); i.hasNext(); nodeCount++) { currentNode[0] = (Node) i.next(); currentPosition[0] = nodeCount; // Interpret iteration interpreterContext.pushCurrentNode(currentNode[0]); saxStore.replay(contentHandler); interpreterContext.popCurrentNode(); } } finally { interpreterContext.popFunctions(); } } catch (Exception e) { throw new ValidationException(e, new LocationData(getDocumentLocator())); } } } } private static class NoResultsInterpreter extends InterpreterContentHandler { public NoResultsInterpreter(SQLProcessorInterpreterContext interpreterContext) { super(interpreterContext, false); } public void start(String uri, String localname, String qName, Attributes attributes) throws SAXException { // Only forward if the result set is empty if (getInterpreterContext().isEmptyResultSet()) { setForward(true); addElementHandler(new ExecuteInterpreter(getInterpreterContext()), SQL_NAMESPACE_URI, "execute"); ValueOfCopyOfInterpreter valueOfCopyOfInterpreter = new ValueOfCopyOfInterpreter(getInterpreterContext()); addElementHandler(valueOfCopyOfInterpreter, SQL_NAMESPACE_URI, "value-of"); addElementHandler(valueOfCopyOfInterpreter, SQL_NAMESPACE_URI, "copy-of"); addElementHandler(new TextInterpreter(getInterpreterContext()), SQL_NAMESPACE_URI, "text"); addElementHandler(new ForEachInterpreter(getInterpreterContext(), getElementHandlers()), SQL_NAMESPACE_URI, "for-each"); } } } private static class QueryInterpreter extends InterpreterContentHandler { public static final int QUERY = 0; public static final int UPDATE = 1; private int type; private StringBuffer query; private List queryParameters; private boolean hasReplaceOrSeparator; private Iterator nodeIterator; private String debugString; public QueryInterpreter(SQLProcessorInterpreterContext interpreterContext, int type) { super(interpreterContext, false); this.type = type; } public void characters(char[] chars, int start, int length) throws SAXException { if (query == null) query = new StringBuffer(); query.append(chars, start, length); } public void startElement(String uri, String localname, String qName, Attributes attributes) throws SAXException { super.startElement(uri, localname, qName, attributes); if (SQL_NAMESPACE_URI.equals(uri)) { if (localname.equals("param") || localname.equals("parameter")) { if (query == null) query = new StringBuffer(); // Add parameter information String direction = attributes.getValue("direction"); String type = attributes.getValue("type"); String sqlType = attributes.getValue("sql-type"); String select = attributes.getValue("select"); String separator = attributes.getValue("separator"); boolean replace = new Boolean(attributes.getValue("replace")).booleanValue(); String nullIf = attributes.getValue("null-if"); if (replace || separator != null) { // Remember that we have to replace at least once hasReplaceOrSeparator = true; } else { // Add question mark for prepared statement query.append(" ? "); } // Remember parameter if (queryParameters == null) queryParameters = new ArrayList(); queryParameters.add(new QueryParameter(direction, type, sqlType, select, separator, replace, nullIf, query.length(), new LocationData(getDocumentLocator()))); } else { // This must be either a get-column or a simple getter (deprecated) boolean isGetColumn = localname.equals("get-column"); String levelString = attributes.getValue("ancestor"); String columnName = attributes.getValue("column"); // Level defaults to 1 in query int level = (levelString == null) ? 1 : Integer.parseInt(levelString); if (level < 1) throw new ValidationException("Attribute level must be 1 or greater in query", new LocationData(getDocumentLocator())); // Set value try { Object value; if (isGetColumn) { String type = attributes.getValue("type"); ResultSet rs = getInterpreterContext().getResultSet(level); if ("oxf:xmlFragment".equals(type)) { ResultSetMetaData metadata = rs.getMetaData(); int columnType = metadata.getColumnType(rs.findColumn(columnName)); if (columnType == Types.CLOB) { value = rs.getClob(columnName); } else if (columnType == Types.BLOB) { throw new ValidationException("Cannot read a Blob as an oxf:xmlFragment", new LocationData(getDocumentLocator())); } else { value = rs.getString(columnName); } } else value = GetterInterpreter.interpretGenericGetter(getInterpreterContext(), getDocumentLocator(), type, columnName, level); } else { value = GetterInterpreter.interpretSimpleGetter(getInterpreterContext(), getDocumentLocator(), localname, columnName, level); } ((QueryParameter) queryParameters.get(queryParameters.size() - 1)).setValue(value); } catch (Exception e) { throw new ValidationException(e, new LocationData(getDocumentLocator())); } } } } public void start(String uri, String localname, String qName, Attributes attributes) throws SAXException { // Get select attribute String selectString = attributes.getValue("select"); if (selectString != null) { if (type != UPDATE) throw new ValidationException("select attribute is valid only on update element", new LocationData(getDocumentLocator())); nodeIterator = XPathUtils.selectIterator(getInterpreterContext().getCurrentNode(), selectString, getInterpreterContext().getPrefixesMap(), null, getInterpreterContext().getFunctionContext()); } // Get debug attribute debugString = attributes.getValue("debug"); } public void end(String uri, String localname, String qName) throws SAXException { // Validate query if (query == null) throw new ValidationException("Missing query", new LocationData(getDocumentLocator())); // Execute query try { // Create a single PreparedStatement if the query is not modified at each iteration PreparedStatement stmt = null; if (!hasReplaceOrSeparator) { String queryString = query.toString(); stmt = getInterpreterContext().getConnection().prepareStatement(queryString); getInterpreterContext().setStatementString(queryString); } getInterpreterContext().setStatement(stmt); int nodeCount = 1; // Iterate through all source nodes (only one if "select" attribute is missing) for (Iterator j = (nodeIterator != null) ? nodeIterator : Collections.singletonList(getInterpreterContext().getCurrentNode()).iterator(); j.hasNext(); nodeCount++) { final Node currentNode = (Node) j.next(); final int _nodeCount = nodeCount; // LocationData locationData = (currentNode instanceof Element) // ? (LocationData) ((Element) currentNode).getData() : null; // Scope sql:position variable (deprecated) Map prefixesMap = getInterpreterContext().getPrefixesMap(); VariableContext variableContext = new VariableContext() { public Object getVariableValue(String namespaceURI, String prefix, String localName) throws UnresolvableException { if (!SQL_NAMESPACE_URI.equals(namespaceURI)) throw new UnresolvableException("Unbound variable: {" + namespaceURI + "}" + localName); if ("position".equals(localName)) { return new Integer(_nodeCount); } else throw new UnresolvableException("Unbound variable: {" + namespaceURI + "}" + localName); } }; // Scope sql:current(), sql:position() and sql:get-column functions Map functions = new HashMap(); functions.put("{" + SQL_NAMESPACE_URI + "}" + "current", new Function() { public Object call(org.jaxen.Context context, List args) { return currentNode; } }); functions.put("{" + SQL_NAMESPACE_URI + "}" + "position", new Function() { public Object call(org.jaxen.Context context, List args) { return new Integer(_nodeCount); } }); functions.put("{" + SQL_NAMESPACE_URI + "}" + "get-column", new Function() { public Object call(org.jaxen.Context context, List args) { int argc = args.size(); if (argc < 1 || argc > 2) throw new OXFException("sql:get-column expects one or two parameters"); String colname = (String) args.get(0); String levelString = (argc == 2) ? (String) args.get(1) : null; int level = (levelString == null) ? 1 : Integer.parseInt(levelString); if (level < 1) throw new OXFException("Attribute level must be 1 or greater in query"); ResultSet rs = getInterpreterContext().getResultSet(level); try { return rs.getString(colname); } catch (SQLException e) { throw new OXFException(e); } } }); try { getInterpreterContext().pushFunctions(functions); // Replace inline parameters StringBuffer replacedQuery = query; if (hasReplaceOrSeparator) { replacedQuery = new StringBuffer(); String queryString = query.toString(); int firstIndex = 0; for (Iterator i = queryParameters.iterator(); i.hasNext();) { QueryParameter parameter = (QueryParameter) i.next(); try { String select = parameter.getSelect(); String separator = parameter.getSeparator(); if (parameter.isReplace() || separator != null) { // Handle query modification for this parameter int secondIndex = parameter.getReplaceIndex(); replacedQuery.append(queryString.substring(firstIndex, secondIndex)); // Create List of either strings or nodes List values; if (separator == null) { // Read the expression as a string if there is a select, otherwise get parameter value as string Object objectValue; if (select != null) { objectValue = XPathUtils.selectStringValue(currentNode, parameter.getSelect(), prefixesMap, variableContext, getInterpreterContext().getFunctionContext()); } else { objectValue = (parameter.getValue() == null) ? null : parameter.getValue().toString(); } values = Collections.singletonList(objectValue); } else { // Accept only a node or node-set if there is a separator, in which case a select is mandatory Object objectValue = XPathUtils.selectObjectValue(currentNode, parameter.getSelect(), prefixesMap, variableContext, getInterpreterContext().getFunctionContext()); if (objectValue instanceof List) { values = (List) objectValue; } else if (objectValue instanceof Node) { values = Collections.singletonList(objectValue); } else { throw new OXFException("sql:parameter with separator requires an expression returning a node-set"); } // Set values on the parameter if they are not replaced immediately if (!parameter.isReplace()) parameter.setValues(values); } if (parameter.isReplace()) { // Replace in the query for (Iterator k = values.iterator(); k.hasNext();) { Object objectValue = k.next(); // Get value as a string String stringValue = (objectValue instanceof Node) ? XPathUtils.selectStringValue((Node) objectValue, ".") : (String) objectValue; // null values are prohibited if (stringValue == null) throw new OXFException("Cannot replace value with null result"); if ("int".equals(parameter.getType()) || "xs:int".equals(parameter.getType())) { replacedQuery.append(Integer.parseInt(stringValue)); } else if ("literal-string".equals(parameter.getType()) || "oxf:literalString".equals(parameter.getType())) { replacedQuery.append(stringValue); } else throw new ValidationException("Unsupported parameter type: " + parameter.getType(), parameter.getLocationData()); // Append separator if needed if (k.hasNext()) replacedQuery.append(separator); } } else { // Update prepared statement for (int k = 0; k < values.size(); k++) { if (k > 0) replacedQuery.append(separator); replacedQuery.append(" ? "); } } firstIndex = secondIndex; } } catch (ValidationException e) { throw e; } catch (Exception e) { throw new ValidationException(e, parameter.getLocationData()); } } if (firstIndex < queryString.length()) { replacedQuery.append(queryString.substring(firstIndex)); } // We create a new PreparedStatement for each iteration String replacedQueryString = replacedQuery.toString(); if (stmt != null) { stmt.close(); } stmt = getInterpreterContext().getConnection().prepareStatement(replacedQueryString); getInterpreterContext().setStatement(stmt); getInterpreterContext().setStatementString(replacedQueryString); } // Output debug if needed if (debugString != null) logger.info("PreparedStatement (debug=\"" + debugString + "\"):\n" + getInterpreterContext().getStatementString()); // Set prepared statement parameters if (queryParameters != null) { int index = 1; for (Iterator i = queryParameters.iterator(); i.hasNext();) { QueryParameter parameter = (QueryParameter) i.next(); try { if (!parameter.isReplace()) { String select = parameter.getSelect(); String type = parameter.getType(); boolean doSetNull = parameter.getNullIf() != null && XPathUtils.selectBooleanValue(currentNode, parameter.getNullIf(), prefixesMap, variableContext, getInterpreterContext().getFunctionContext()).booleanValue(); if ("string".equals(type) || "xs:string".equals(type) || "oxf:xmlFragment".equals(type)) { // Set a string or XML Fragment // List of Clobs, strings or nodes List values; if (parameter.getValues() != null) values = parameter.getValues(); else if (select != null) values = Collections.singletonList(XPathUtils.selectObjectValue(currentNode, parameter.getSelect(), prefixesMap, variableContext, getInterpreterContext().getFunctionContext())); else values = Collections.singletonList(parameter.getValue()); // Iterate through all values for (Iterator k = values.iterator(); k.hasNext(); index++) { Object objectValue = k.next(); // Get Clob, String or Element Object value = null; if (!doSetNull) { if (objectValue instanceof Clob || objectValue instanceof Blob || objectValue instanceof String) { // Leave unchanged value = objectValue; } else if ("oxf:xmlFragment".equals(type)) { // Case of XML Fragment // Get an Element or a String if (objectValue instanceof Element) value = objectValue; else if (objectValue instanceof List) { List list = ((List) objectValue); if (list.size() == 0) value = null; else if (list.get(0) instanceof Element) value = list.get(0); else throw new OXFException("oxf:xmlFragment type expects a node-set an element node in first position"); } else if (objectValue != null) throw new OXFException("oxf:xmlFragment type expects a node, a node-set or a string"); } else { // Case of String if (objectValue instanceof Node) value = XPathUtils.selectStringValue((Node) objectValue, "."); else if (objectValue instanceof List) { List list = ((List) objectValue); if (list.size() == 0) value = null; else if (list.get(0) instanceof Node) value = XPathUtils.selectStringValue((Node) list.get(0), "."); else throw new OXFException("Invalid type: " + objectValue.getClass()); } else if (objectValue != null) throw new OXFException("Invalid type: " + objectValue.getClass()); } } String sqlType = parameter.getSqlType(); if (value == null) { if (SQL_TYPE_CLOB.equals(sqlType)) stmt.setNull(index, Types.CLOB); else if (SQL_TYPE_BLOB.equals(sqlType)) stmt.setNull(index, Types.BLOB); else stmt.setNull(index, Types.VARCHAR); } else if (value instanceof Clob) { Clob clob = (Clob) value; if (SQL_TYPE_CLOB.equals(sqlType)) { // Set Clob as Clob stmt.setClob(index, clob); } else { // Set Clob as String long clobLength = clob.length(); if (clobLength > (long) Integer.MAX_VALUE) throw new OXFException("CLOB length can't be larger than 2GB"); stmt.setString(index, clob.getSubString(1, (int) clob.length())); } // TODO: Check BLOB: should we be able to set a String as a Blob? } else if (value instanceof String || value instanceof Element) { // Make sure we create a Document from the Element if we have one Document xmlFragmentDocument = (value instanceof Element) ? DocumentHelper.createDocument(((Element) value).createCopy()) : null; // Convert document into an XML String if necessary if (value instanceof Element && !SQL_TYPE_XMLTYPE.equals(sqlType)) { // Convert Document into a String boolean serializeXML11 = getInterpreterContext().getPropertySet().getBoolean("serialize-xml-11", false).booleanValue(); value = XMLUtils.domToString(XMLUtils.adjustNamespaces(xmlFragmentDocument, serializeXML11), false, false); } if (SQL_TYPE_XMLTYPE.equals(sqlType)) { // Set DOM using native XML type if (value instanceof Element) { // We have a Document - convert it to DOM // TEMP HACK: We can't seem to be able to convert directly from dom4j to regular DOM (NAMESPACE_ERR from Xerces) // DOMResult domResult = new DOMResult(); // TransformerUtils.getIdentityTransformer().transform(new DocumentSource(xmlFragmentDocument), domResult);xxx // org.w3c.dom.Node node = domResult.getNode(); boolean serializeXML11 = getInterpreterContext().getPropertySet().getBoolean("serialize-xml-11", false).booleanValue(); String stringValue = XMLUtils.domToString(XMLUtils.adjustNamespaces(xmlFragmentDocument, serializeXML11), false, false); // TEMP HACK: Oracle seems to have a problem with XMLType instanciated from a DOM, so we pass a String // org.w3c.dom.Node node = XMLUtils.stringToDOM(stringValue); // if (!(node instanceof org.w3c.dom.Document)) { // // FIXME: Is this necessary? Why wouldn't we always get a Document from the transformation? // org.w3c.dom.Document document = XMLUtils.createDocument(); // document.appendChild(node); // node = document; // } // getInterpreterContext().getDelegate().setDOM(stmt, index, (org.w3c.dom.Document) node); getInterpreterContext().getDelegate().setDOM(stmt, index, stringValue); } else { // We have a String - create a DOM from it // FIXME: Do we need this? throw new UnsupportedOperationException("Setting native XML type from a String is not yet supported. Please report this usage."); } } else if (SQL_TYPE_CLOB.equals(sqlType)) { // Set String as Clob String stringValue = (String) value; getInterpreterContext().getDelegate().setClob(stmt, index, stringValue); // TODO: Check BLOB: should we be able to set a String as a Blob? } else { // Set String as String stmt.setString(index, (String) value); } } else throw new OXFException("Invalid parameter type: " + parameter.getType()); } } else if ("xs:base64Binary".equals(type)) { // We are writing binary data encoded in Base 64. The only target supported // is Blob // For now, only support passing a string from the input document String sqlType = parameter.getSqlType(); if (sqlType != null && !SQL_TYPE_CLOB.equals(sqlType)) throw new OXFException("Invalid sql-type attribute: " + sqlType); if (select == null) throw new UnsupportedOperationException("Setting BLOB requires a select attribute."); // Base64 XPathContentHandler xpathContentHandler = getInterpreterContext().getXPathContentHandler(); if (xpathContentHandler != null && xpathContentHandler.containsExpression(parameter.getSelect())) { // Handle streaming if possible OutputStream blobOutputStream = getInterpreterContext().getDelegate().getBlobOutputStream(stmt, index); xpathContentHandler.selectContentHandler(parameter.getSelect(), new Base64ContentHandler(blobOutputStream)); blobOutputStream.close(); } else { String base64Value = XPathUtils.selectStringValue(currentNode, parameter.getSelect(), prefixesMap, variableContext, getInterpreterContext().getFunctionContext()); getInterpreterContext().getDelegate().setBlob(stmt, index, XMLUtils.base64StringToByteArray(base64Value)); } } else { // Simple cases // List of strings or nodes List values; if (parameter.getValues() != null) values = parameter.getValues(); else if (select != null) values = Collections.singletonList(XPathUtils.selectStringValue(currentNode, parameter.getSelect(), prefixesMap, variableContext, getInterpreterContext().getFunctionContext())); else values = Collections.singletonList(parameter.getValue()); // Iterate through all values for (Iterator k = values.iterator(); k.hasNext(); index++) { Object objectValue = k.next(); // Get String value String stringValue = null; if (!doSetNull) { if (objectValue instanceof String) stringValue = (String) objectValue; else if (objectValue != null) stringValue = XPathUtils.selectStringValue((Node) objectValue, "."); } // For the specific type, set to null or convert String value if ("int".equals(type) || "xs:int".equals(type)) { if (stringValue == null) stmt.setNull(index, Types.INTEGER); else stmt.setInt(index, new Integer(stringValue).intValue()); } else if ("date".equals(type) || "xs:date".equals(type)) { if (stringValue == null) { stmt.setNull(index, Types.DATE); } else { java.sql.Date date = new java.sql.Date(ISODateUtils.parseDate(stringValue).getTime()); stmt.setDate(index, date); } } else if ("xs:dateTime".equals(type)) { if (stringValue == null) { stmt.setNull(index, Types.TIMESTAMP); } else { java.sql.Timestamp timestamp = new java.sql.Timestamp(ISODateUtils.parseDate(stringValue).getTime()); stmt.setTimestamp(index, timestamp); } } else if ("xs:boolean".equals(type)) { if (stringValue == null) stmt.setNull(index, Types.INTEGER); // Types.BOOLEAN is present from JDK 1.4 only else stmt.setBoolean(index, "true".equals(stringValue)); } else if ("xs:decimal".equals(type)) { if (stringValue == null) stmt.setNull(index, Types.DECIMAL); else stmt.setBigDecimal(index, new BigDecimal(stringValue)); } else if ("xs:float".equals(type)) { if (stringValue == null) stmt.setNull(index, Types.FLOAT); else stmt.setFloat(index, Float.parseFloat(stringValue)); } else if ("xs:double".equals(type)) { if (stringValue == null) stmt.setNull(index, Types.DOUBLE); else stmt.setDouble(index, Double.parseDouble(stringValue)); } else if ("xs:anyURI".equals(type)) { String sqlType = parameter.getSqlType(); if (sqlType != null && !SQL_TYPE_CLOB.equals(sqlType)) throw new OXFException("Invalid sql-type attribute: " + sqlType); if (stringValue == null) { stmt.setNull(index, Types.BLOB); } else { // Dereference the URI and write to the BLOB OutputStream blobOutputStream = getInterpreterContext().getDelegate().getBlobOutputStream(stmt, index); XMLUtils.anyURIToOutputStream(stringValue, blobOutputStream); blobOutputStream.close(); } } else throw new ValidationException("Unsupported parameter type: " + type, parameter.getLocationData()); } } } } catch (ValidationException e) { throw e; } catch (Exception e) { throw new ValidationException(e, parameter.getLocationData()); } } } } finally { getInterpreterContext().popFunctions(); } if (type == QUERY) { if (nodeCount > 1) throw new ValidationException("More than one iteration on query element", new LocationData(getDocumentLocator())); ResultSet resultSet = stmt.executeQuery(); boolean hasNext = resultSet.next(); getInterpreterContext().setEmptyResultSet(!hasNext); // Close result set and statement immediately if possible if (getInterpreterContext().isEmptyResultSet()) { stmt.close(); resultSet = null; stmt = null; getInterpreterContext().setStatement(null); } // Remember result set and statement getInterpreterContext().setResultSet(resultSet); } else if (type == UPDATE) { int updateCount = stmt.executeUpdate(); getInterpreterContext().setUpdateCount(updateCount);//FIXME: should add? } } } catch (Exception e) { // FIXME: should store exception so that it can be retrieved // Actually, we'll need a global exception mechanism for pipelines, so this may end up being done // in XPL or BPEL. // Log closest query related to the exception if we can find it String statementString = getInterpreterContext().getStatementString(); logger.error("PreparedStatement:\n" + statementString); // And throw throw new ValidationException(e, new LocationData(getDocumentLocator())); } } } private static class ConfigInterpreter extends InterpreterContentHandler { public ConfigInterpreter(SQLProcessorInterpreterContext interpreterContext) { super(interpreterContext, true); final SQLProcessorInterpreterContext _interpreterContext = interpreterContext; addElementHandler(new InterpreterContentHandler(interpreterContext, true) { public void start(String uri, String localname, String qName, Attributes attributes) { addElementHandler(new InterpreterContentHandler() { StringBuffer datasourceName; public void characters(char[] chars, int start, int length) { if (datasourceName == null) datasourceName = new StringBuffer(); datasourceName.append(chars, start, length); } public void end(String uri, String localname, String qName) { // Validate datasource element if (datasourceName == null) throw new ValidationException("Missing datasource name in datasource element", new LocationData(getDocumentLocator())); // Get the connection from the datasource and set in context try { _interpreterContext.setConnection(getDocumentLocator(), datasourceName.toString()); } catch (Exception e) { throw new ValidationException(e, new LocationData(getDocumentLocator())); } } }, SQL_NAMESPACE_URI, "datasource"); addElementHandler(new ExecuteInterpreter(getInterpreterContext()), SQL_NAMESPACE_URI, "execute"); ValueOfCopyOfInterpreter valueOfCopyOfInterpreter = new ValueOfCopyOfInterpreter(getInterpreterContext()); addElementHandler(valueOfCopyOfInterpreter, SQL_NAMESPACE_URI, "value-of"); addElementHandler(valueOfCopyOfInterpreter, SQL_NAMESPACE_URI, "copy-of"); addElementHandler(new TextInterpreter(getInterpreterContext()), SQL_NAMESPACE_URI, "text"); addElementHandler(new ForEachInterpreter(getInterpreterContext(), getElementHandlers()), SQL_NAMESPACE_URI, "for-each"); } public void end(String uri, String localname, String qName) { // Close connection // NOTE: Don't do this anymore: the connection will be closed when the context is destroyed } }, SQL_NAMESPACE_URI, "connection"); addElementHandler(new TextInterpreter(interpreterContext), SQL_NAMESPACE_URI, "text"); } public void start(String uri, String localname, String qName, Attributes attributes) throws SAXException { getInterpreterContext().getOutput().startDocument(); } public void end(String uri, String localname, String qName) throws SAXException { getInterpreterContext().getOutput().endDocument(); } } private static class TextInterpreter extends InterpreterContentHandler { private StringBuffer text; public TextInterpreter(SQLProcessorInterpreterContext interpreterContext) { super(interpreterContext, false); } public void characters(char[] chars, int start, int length) throws SAXException { if (text == null) text = new StringBuffer(); text.append(chars, start, length); } public void start(String uri, String localname, String qName, Attributes attributes) throws SAXException { text = null; } public void end(String uri, String localname, String qName) throws SAXException { char[] localText = text.toString().toCharArray(); getInterpreterContext().getOutput().characters(localText, 0, localText.length); } } private static class RootInterpreter extends InterpreterContentHandler { private SQLProcessorInterpreterContext interpreterContext; private NamespaceSupport namespaceSupport = new NamespaceSupport(); public RootInterpreter(PipelineContext context, OXFProperties.PropertySet propertySet, Node input, Datasource datasource, XPathContentHandler xpathContentHandler, ContentHandler output) { super(null, false); interpreterContext = new SQLProcessorInterpreterContext(propertySet); interpreterContext.setPipelineContext(context); interpreterContext.setInput(input); interpreterContext.setDatasource(datasource); interpreterContext.setXPathContentHandler(xpathContentHandler); interpreterContext.setOutput(output); interpreterContext.setNamespaceSupport(namespaceSupport); addElementHandler(new ConfigInterpreter(interpreterContext), SQL_NAMESPACE_URI, "config"); } public void startElement(String uri, String localname, String qName, Attributes attributes) throws SAXException { try { namespaceSupport.pushContext(); super.startElement(uri, localname, qName, attributes); } catch (Exception t) { dispose(); throw new OXFException(t); } } public void endElement(String uri, String localname, String qName) throws SAXException { try { super.endElement(uri, localname, qName); namespaceSupport.popContext(); } catch (Exception t) { dispose(); throw new OXFException(t); } } public void startPrefixMapping(String prefix, String uri) throws SAXException { try { super.startPrefixMapping(prefix, uri); interpreterContext.declarePrefix(prefix, uri); } catch (Exception t) { dispose(); throw new OXFException(t); } } public void characters(char[] chars, int start, int length) throws SAXException { try { super.characters(chars, start, length); } catch (Exception t) { dispose(); throw new OXFException(t); } } public void endDocument() throws SAXException { try { super.endDocument(); } catch (Exception t) { dispose(); throw new OXFException(t); } } public void ignorableWhitespace(char[] chars, int start, int length) throws SAXException { try { super.ignorableWhitespace(chars, start, length); } catch (Exception t) { dispose(); throw new OXFException(t); } } public void processingInstruction(String s, String s1) throws SAXException { try { super.processingInstruction(s, s1); } catch (Exception t) { dispose(); throw new OXFException(t); } } public void skippedEntity(String s) throws SAXException { try { super.skippedEntity(s); } catch (Exception t) { dispose(); throw new OXFException(t); } } public void startDocument() throws SAXException { try { super.startDocument(); } catch (Exception t) { dispose(); throw new OXFException(t); } } public void endPrefixMapping(String s) throws SAXException { try { super.endPrefixMapping(s); } catch (Exception t) { dispose(); throw new OXFException(t); } } public Locator getDocumentLocator() { try { return super.getDocumentLocator(); } catch (Exception t) { dispose(); throw new OXFException(t); } } public void setDocumentLocator(Locator locator) { try { super.setDocumentLocator(locator); } catch (Exception t) { dispose(); throw new OXFException(t); } } private void dispose() { // NOTE: Don't do this anymore: the connection will be closed when the context is destroyed } } private static class InterpreterContentHandler extends ForwardingContentHandler { private SQLProcessorInterpreterContext interpreterContext; private boolean forward; private Locator documentLocator; private Map elementHandlers = new HashMap(); private int forwardingLevel = -1; private InterpreterContentHandler currentHandler; private int level = 0; private String currentKey; public InterpreterContentHandler() { this(null, false); } public InterpreterContentHandler(SQLProcessorInterpreterContext interpreterContext, boolean forward) { this.interpreterContext = interpreterContext; this.forward = forward; } public void addElementHandler(InterpreterContentHandler handler, String uri, String localname) { elementHandlers.put("{" + uri + "}" + localname, handler); } public Map getElementHandlers() { return elementHandlers; } public void setElementHandlers(Map elementHandlers) { this.elementHandlers = elementHandlers; } public void startElement(String uri, String localname, String qName, Attributes attributes) throws SAXException { if (forwardingLevel == -1 && elementHandlers.size() > 0) { String key = "{" + uri + "}" + localname; InterpreterContentHandler elementHandler = (InterpreterContentHandler) elementHandlers.get(key); if (elementHandler != null) { forwardingLevel = level; currentKey = key; currentHandler = elementHandler; elementHandler.setDocumentLocator(documentLocator); elementHandler.start(uri, localname, qName, attributes); } else super.startElement(uri, localname, qName, attributes); } else super.startElement(uri, localname, qName, attributes); level++; } public void endElement(String uri, String localname, String qName) throws SAXException { level--; if (forwardingLevel == level) { String key = "{" + uri + "}" + localname; if (!currentKey.equals(key)) throw new ValidationException("Illegal document: expecting " + key + ", got " + currentKey, new LocationData(getDocumentLocator())); InterpreterContentHandler elementHandler = (InterpreterContentHandler) elementHandlers.get(key); forwardingLevel = -1; currentKey = null; currentHandler = null; elementHandler.end(uri, localname, qName); } else super.endElement(uri, localname, qName); } public void setDocumentLocator(Locator locator) { this.documentLocator = locator; super.setDocumentLocator(locator); } public Locator getDocumentLocator() { return documentLocator; } public void startPrefixMapping(String s, String s1) throws SAXException { super.startPrefixMapping(s, s1); } public void start(String uri, String localname, String qName, Attributes attributes) throws SAXException { } public void end(String uri, String localname, String qName) throws SAXException { } protected boolean isInElementHandler() { return forwardingLevel > -1; } protected ContentHandler getContentHandler() { if (currentHandler != null) return currentHandler; else if (forward) return interpreterContext.getOutput(); else return null; } public void characters(char[] chars, int start, int length) throws SAXException { if (currentHandler == null) { // Output only if the string is non-blank [FIXME: Incorrect white space handling!] // String s = new String(chars, start, length); // if (!s.trim().equals("")) super.characters(chars, start, length); } else { super.characters(chars, start, length); } } public SQLProcessorInterpreterContext getInterpreterContext() { return interpreterContext; } public boolean isForward() { return forward; } public void setForward(boolean forward) { this.forward = forward; } } private static class QueryParameter { private String direction; private String type; private String sqlType; private String select; private String separator; private boolean replace; private String nullIf; private int replaceIndex; private Object value; private List values; private LocationData locationData; public QueryParameter(String direction, String type, String sqlType, String select, String separator, boolean replace, String nullIf, int replaceIndex, LocationData locationData) { this.direction = direction; this.type = type; this.sqlType = sqlType; this.select = select; this.separator = separator; this.replace = replace; this.nullIf = nullIf; this.replaceIndex = replaceIndex; this.locationData = locationData; } public void setValue(Object value) { this.value = value; } public String getDirection() { return direction; } public String getType() { return type; } public String getSqlType() { return sqlType; } public String getSelect() { return select; } public String getSeparator() { return separator; } public boolean isReplace() { return replace; } public String getNullIf() { return nullIf; } public int getReplaceIndex() { return replaceIndex; } public Object getValue() { return value; } public LocationData getLocationData() { return locationData; } public List getValues() { return values; } public void setValues(List values) { this.values = values; } } private static abstract class ForwardingContentHandler implements ContentHandler { public ForwardingContentHandler() { } protected abstract ContentHandler getContentHandler(); public void characters(char[] chars, int start, int length) throws SAXException { ContentHandler contentHandler = getContentHandler(); if (contentHandler != null) contentHandler.characters(chars, start, length); } public void endDocument() throws SAXException { ContentHandler contentHandler = getContentHandler(); if (contentHandler != null) contentHandler.endDocument(); } public void endElement(String uri, String localname, String qName) throws SAXException { ContentHandler contentHandler = getContentHandler(); if (contentHandler != null) contentHandler.endElement(uri, localname, qName); } public void endPrefixMapping(String s) throws SAXException { ContentHandler contentHandler = getContentHandler(); if (contentHandler != null) contentHandler.endPrefixMapping(s); } public void ignorableWhitespace(char[] chars, int start, int length) throws SAXException { ContentHandler contentHandler = getContentHandler(); if (contentHandler != null) contentHandler.ignorableWhitespace(chars, start, length); } public void processingInstruction(String s, String s1) throws SAXException { ContentHandler contentHandler = getContentHandler(); if (contentHandler != null) contentHandler.processingInstruction(s, s1); } public void setDocumentLocator(Locator locator) { ContentHandler contentHandler = getContentHandler(); if (contentHandler != null) contentHandler.setDocumentLocator(locator); } public void skippedEntity(String s) throws SAXException { ContentHandler contentHandler = getContentHandler(); if (contentHandler != null) contentHandler.skippedEntity(s); } public void startDocument() throws SAXException { ContentHandler contentHandler = getContentHandler(); if (contentHandler != null) contentHandler.startDocument(); } public void startElement(String uri, String localname, String qName, Attributes attributes) throws SAXException { ContentHandler contentHandler = getContentHandler(); if (contentHandler != null) contentHandler.startElement(uri, localname, qName, attributes); } public void startPrefixMapping(String s, String s1) throws SAXException { ContentHandler contentHandler = getContentHandler(); if (contentHandler != null) contentHandler.startPrefixMapping(s, s1); } } }
src/java/org/orbeon/oxf/processor/sql/SQLProcessor.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.sql; import org.apache.log4j.Logger; import org.dom4j.*; import org.jaxen.Function; import org.jaxen.UnresolvableException; import org.jaxen.VariableContext; import org.orbeon.oxf.common.OXFException; import org.orbeon.oxf.common.ValidationException; import org.orbeon.oxf.pipeline.api.PipelineContext; import org.orbeon.oxf.processor.*; import org.orbeon.oxf.resources.OXFProperties; import org.orbeon.oxf.util.*; import org.orbeon.oxf.xml.*; import org.orbeon.oxf.xml.dom4j.LocationData; import org.orbeon.oxf.xml.dom4j.LocationSAXWriter; import org.orbeon.saxon.dom4j.DocumentWrapper; import org.orbeon.saxon.xpath.*; import org.orbeon.saxon.xpath.XPathException; import org.xml.sax.Attributes; import org.xml.sax.ContentHandler; import org.xml.sax.Locator; import org.xml.sax.SAXException; import org.xml.sax.helpers.NamespaceSupport; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.sax.SAXResult; import java.io.InputStream; import java.io.OutputStream; import java.io.Reader; import java.math.BigDecimal; import java.sql.*; import java.sql.Date; import java.util.*; /** * This is the SQL processor implementation. * <p/> * TODO: * <p/> * o batch for mass updates when supported * o esql:use-limit-clause, esql:skip-rows, esql:max-rows * <p/> * o The position() and last() functions are not implemented within * sql:for-each it does not appear to be trivial to implement them, because * they are already defined by default. Probably that playing with the Jaxen * Context object will allow a correct implementation. * <p/> * o debugging facilities, i.e. output full query with replaced parameters (even on PreparedStatement) * o support more types in replace mode * <p/> * o sql:choose, sql:if * o sql:variable * o define variables such as: * o $sql:results (?) * o $sql:column-count * o $sql:update-count * <p/> * o esql:error-results//esql:get-message * o esql:error-results//esql:to-string * o esql:error-results//esql:get-stacktrace * <p/> * o multiple results * o caching options */ public class SQLProcessor extends ProcessorImpl { static Logger logger = LoggerFactory.createLogger(SQLProcessor.class); public static final String SQL_NAMESPACE_URI = "http://orbeon.org/oxf/xml/sql"; private static final String INPUT_DATASOURCE = "datasource"; public static final String SQL_DATASOURCE_URI = "http://www.orbeon.org/oxf/sql-datasource"; // private static final String SQL_TYPE_VARCHAR = "varchar"; private static final String SQL_TYPE_CLOB = "clob"; private static final String SQL_TYPE_BLOB = "blob"; private static final String SQL_TYPE_XMLTYPE = "xmltype"; private static final Document EMPTY_DOCUMENT = XMLUtils.createDOM4JDocument(); public SQLProcessor() { // Mandatory config input addInputInfo(new ProcessorInputOutputInfo(INPUT_CONFIG, SQL_NAMESPACE_URI)); // Optional datasource input addInputInfo(new ProcessorInputOutputInfo(INPUT_DATASOURCE, SQL_DATASOURCE_URI)); // Optional data input and output addInputInfo(new ProcessorInputOutputInfo(INPUT_DATA)); // For now don't declare it, because it causes problems // addOutputInfo(new ProcessorInputOutputInfo(OUTPUT_DATA)); } public ProcessorOutput createOutput(String name) { // This will be called only if there is an output ProcessorOutput output = new ProcessorOutputImpl(getClass(), name) { public void readImpl(PipelineContext context, ContentHandler contentHandler) { execute(context, contentHandler); } }; addOutput(name, output); return output; } public void start(PipelineContext context) { // This will be called only if no output is connected execute(context, new NullSerializer.NullContentHandler()); } private static class Config { public Config(SAXStore configInput, boolean useXPathExpressions, List xpathExpressions) { this.configInput = configInput; this.useXPathExpressions = useXPathExpressions; this.xpathExpressions = xpathExpressions; } public SAXStore configInput; public boolean useXPathExpressions; public List xpathExpressions; } protected void execute(final PipelineContext context, ContentHandler contentHandler) { try { // Cache, read and interpret the config input Config config = (Config) readCacheInputAsObject(context, getInputByName(INPUT_CONFIG), new CacheableInputReader() { public Object read(PipelineContext context, ProcessorInput input) { // Read the config input document Node config = readInputAsDOM4J(context, input); Document configDocument = config.getDocument(); // Extract XPath expressions and also check whether any XPath expression is used at all // NOTE: This could be done through streaming below as well // NOTE: For now, just match <sql:param select="/*" type="xs:base64Binary"/> List xpathExpressions = new ArrayList(); boolean useXPathExpressions = false; for (Iterator i = XPathUtils.selectIterator(configDocument, "//*[namespace-uri() = '" + SQL_NAMESPACE_URI + "' and @select]"); i.hasNext();) { Element element = (Element) i.next(); useXPathExpressions = true; String typeAttribute = element.attributeValue("type"); if ("xs:base64Binary".equals(typeAttribute)) { String selectAttribute = element.attributeValue("select"); xpathExpressions.add(selectAttribute); } } // Normalize spaces. What this does is to coalesce adjacent text nodes, and to remove // resulting empty text, unless the text is contained within a sql:text element. configDocument.accept(new VisitorSupport() { private boolean endTextSequence(Element element, Text previousText) { if (previousText != null) { String value = previousText.getText(); if (value == null || value.trim().equals("")) { element.remove(previousText); return true; } } return false; } public void visit(Element element) { // Don't touch text within sql:text elements if (!SQL_NAMESPACE_URI.equals(element.getNamespaceURI()) || !"text".equals(element.getName())) { Text previousText = null; for (int i = 0, size = element.nodeCount(); i < size;) { Node node = element.node(i); if (node instanceof Text) { Text text = (Text) node; if (previousText != null) { previousText.appendText(text.getText()); element.remove(text); } else { String value = text.getText(); // Remove empty text nodes if (value == null || value.length() < 1) { element.remove(text); } else { previousText = text; i++; } } } else { if (!endTextSequence(element, previousText)) i++; previousText = null; } } endTextSequence(element, previousText); } } }); // Create SAXStore try { SAXStore store = new SAXStore(); LocationSAXWriter saxw = new LocationSAXWriter(); saxw.setContentHandler(store); saxw.write(configDocument); // Return the normalized document return new Config(store, useXPathExpressions, xpathExpressions); } catch (SAXException e) { throw new OXFException(e); } } }); // Either read the whole input as a DOM, or try to serialize Node data = null; XPathContentHandler xpathContentHandler = null; // Check if the data input is connected boolean hasDataInput = getConnectedInputs().get(INPUT_DATA) != null; if (!hasDataInput && config.useXPathExpressions) throw new OXFException("The data input must be connected when the configuration uses XPath expressions."); if (!hasDataInput || !config.useXPathExpressions) { // Just use an empty document data = EMPTY_DOCUMENT; } else { // There is a data input connected and there are some XPath epxressions operating on it boolean useXPathContentHandler = false; if (config.xpathExpressions.size() > 0) { // Create XPath content handler final XPathContentHandler _xpathContentHandler = new XPathContentHandler(); // Add expressions and check whether we can try to stream useXPathContentHandler = true; for (Iterator i = config.xpathExpressions.iterator(); i.hasNext();) { String expression = (String) i.next(); boolean canStream = _xpathContentHandler.addExpresssion(expression, false);// FIXME: boolean nodeSet if (!canStream) { useXPathContentHandler = false; break; } } // Finish setting up the XPathContentHandler if (useXPathContentHandler) { _xpathContentHandler.setReadInputCallback(new Runnable() { public void run() { readInputAsSAX(context, INPUT_DATA, _xpathContentHandler); } }); xpathContentHandler = _xpathContentHandler; } } // If we can't stream, read everything in if (!useXPathContentHandler) data = readInputAsDOM4J(context, INPUT_DATA); } // Try to read datasource input if any Datasource datasource = null; { List datasourceInputs = (List) getConnectedInputs().get(INPUT_DATASOURCE); if (datasourceInputs != null) { if (datasourceInputs.size() > 1) throw new OXFException("At most one one datasource input can be connected."); ProcessorInput datasourceInput = (ProcessorInput) datasourceInputs.get(0); datasource = Datasource.getDatasource(context, this, datasourceInput); } } // Replay the config SAX store through the interpreter config.configInput.replay(new RootInterpreter(context, getPropertySet(), data, datasource, xpathContentHandler, contentHandler)); } catch (OXFException e) { throw e; } catch (Exception e) { throw new OXFException(e); } } private static class ExecuteInterpreter extends InterpreterContentHandler { public ExecuteInterpreter(SQLProcessorInterpreterContext interpreterContext) { super(interpreterContext, true); } public void start(String uri, String localname, String qName, Attributes attributes) throws SAXException { SQLProcessorInterpreterContext interpreterContext = getInterpreterContext(); interpreterContext.pushResultSet(); addElementHandler(new QueryInterpreter(interpreterContext, QueryInterpreter.QUERY), SQL_NAMESPACE_URI, "query"); addElementHandler(new QueryInterpreter(interpreterContext, QueryInterpreter.UPDATE), SQL_NAMESPACE_URI, "update"); addElementHandler(new ResultsInterpreter(interpreterContext), SQL_NAMESPACE_URI, "results"); addElementHandler(new NoResultsInterpreter(interpreterContext), SQL_NAMESPACE_URI, "no-results"); ValueOfCopyOfInterpreter valueOfCopyOfInterpreter = new ValueOfCopyOfInterpreter(interpreterContext); addElementHandler(valueOfCopyOfInterpreter, SQL_NAMESPACE_URI, "value-of"); addElementHandler(valueOfCopyOfInterpreter, SQL_NAMESPACE_URI, "copy-of"); addElementHandler(new TextInterpreter(interpreterContext), SQL_NAMESPACE_URI, "text"); addElementHandler(new ForEachInterpreter(getInterpreterContext(), getElementHandlers()), SQL_NAMESPACE_URI, "for-each"); } public void end(String uri, String localname, String qName) throws SAXException { SQLProcessorInterpreterContext interpreterContext = getInterpreterContext(); PreparedStatement stmt = interpreterContext.getStatement(0); if (stmt != null) { try { stmt.close(); } catch (SQLException e) { throw new ValidationException(e, new LocationData(getDocumentLocator())); } } interpreterContext.popResultSet(); } } private static class ResultsInterpreter extends InterpreterContentHandler { public ResultsInterpreter(SQLProcessorInterpreterContext interpreterContext) { super(interpreterContext, false); } public void start(String uri, String localname, String qName, Attributes attributes) throws SAXException { if (!getInterpreterContext().isEmptyResultSet()) { setForward(true); addElementHandler(new RowResultsInterpreter(getInterpreterContext()), SQL_NAMESPACE_URI, "row-results"); ValueOfCopyOfInterpreter valueOfCopyOfInterpreter = new ValueOfCopyOfInterpreter(getInterpreterContext()); addElementHandler(valueOfCopyOfInterpreter, SQL_NAMESPACE_URI, "value-of"); addElementHandler(valueOfCopyOfInterpreter, SQL_NAMESPACE_URI, "copy-of"); addElementHandler(new TextInterpreter(getInterpreterContext()), SQL_NAMESPACE_URI, "text"); // We must not be able to have a RowResultsInterpreter within the for-each // This must be checked in the schema addElementHandler(new ForEachInterpreter(getInterpreterContext(), getElementHandlers()), SQL_NAMESPACE_URI, "for-each"); } } public void end(String uri, String localname, String qName) throws SAXException { SQLProcessorInterpreterContext interpreterContext = getInterpreterContext(); PreparedStatement stmt = interpreterContext.getStatement(0); if (stmt != null) { try { stmt.close(); interpreterContext.setStatement(null); } catch (SQLException e) { throw new ValidationException(e, new LocationData(getDocumentLocator())); } } } } private static class GetterInterpreter extends InterpreterContentHandler { private ResultSetMetaData metadata; public GetterInterpreter(SQLProcessorInterpreterContext interpreterContext) { super(interpreterContext, false); } /** * Return a Clob or Clob object or a String */ public static Object interpretSimpleGetter(SQLProcessorInterpreterContext interpreterContext, Locator locator, String getterName, String columnName, int level) { try { ResultSet resultSet = interpreterContext.getResultSet(level); int columnType = resultSet.getMetaData().getColumnType(resultSet.findColumn(columnName)); if (columnType == Types.CLOB) { // The actual column is a CLOB if ("get-string".equals(getterName)) { return resultSet.getClob(columnName); } else { throw new ValidationException("Illegal getter type for CLOB: " + getterName, new LocationData(locator)); } } else if (columnType == Types.BLOB) { // The actual column is a BLOB if ("get-base64binary".equals(getterName)) { return resultSet.getBlob(columnName); } else { throw new ValidationException("Illegal getter type for BLOB: " + getterName, new LocationData(locator)); } } else if (columnType == Types.BINARY || columnType == Types.VARBINARY || columnType == Types.LONGVARBINARY) { // The actual column is binary if ("get-base64binary".equals(getterName)) { return resultSet.getBinaryStream(columnName); } else { throw new ValidationException("Illegal getter type for BINARY, VARBINARY or LONGVARBINARY column: " + getterName, new LocationData(locator)); } } else { // The actual column is not a CLOB or BLOB, in which case we use regular ResultSet getters if ("get-string".equals(getterName)) { return resultSet.getString(columnName); } else if ("get-int".equals(getterName)) { int value = resultSet.getInt(columnName); if (resultSet.wasNull()) return null; return Integer.toString(value); } else if ("get-double".equals(getterName)) { double value = resultSet.getDouble(columnName); // For XPath 1.0, we have to get rid of the scientific notation return resultSet.wasNull() ? null : XMLUtils.removeScientificNotation(value); } else if ("get-float".equals(getterName)) { float value = resultSet.getFloat(columnName); // For XPath 1.0, we have to get rid of the scientific notation return resultSet.wasNull() ? null : XMLUtils.removeScientificNotation(value); } else if ("get-decimal".equals(getterName)) { BigDecimal value = resultSet.getBigDecimal(columnName); return (resultSet.wasNull()) ? null : value.toString(); } else if ("get-boolean".equals(getterName)) { boolean value = resultSet.getBoolean(columnName); if (resultSet.wasNull()) return null; return value ? "true" : "false"; } else if ("get-date".equals(getterName)) { Date value = resultSet.getDate(columnName); if (value == null) return null; return ISODateUtils.formatDate(value, ISODateUtils.XS_DATE); } else if ("get-timestamp".equals(getterName)) { Timestamp value = resultSet.getTimestamp(columnName); if (value == null) return null; return ISODateUtils.formatDate(value, ISODateUtils.XS_DATE_TIME_LONG); } else { throw new ValidationException("Illegal getter name: " + getterName, new LocationData(locator)); } } } catch (SQLException e) { throw new ValidationException("Exception while getting column: " + columnName + " at " + e.toString() , new LocationData(locator)); } } private static final Map typesToGetterNames = new HashMap(); static { typesToGetterNames.put("xs:string", "get-string"); typesToGetterNames.put("xs:int", "get-int"); typesToGetterNames.put("xs:boolean", "get-boolean"); typesToGetterNames.put("xs:decimal", "get-decimal"); typesToGetterNames.put("xs:float", "get-float"); typesToGetterNames.put("xs:double", "get-double"); typesToGetterNames.put("xs:dateTime", "get-timestamp"); typesToGetterNames.put("xs:date", "get-date"); typesToGetterNames.put("xs:base64Binary", "get-base64binary"); } /** * Return a Clob or Blob object or a String */ public static Object interpretGenericGetter(SQLProcessorInterpreterContext interpreterContext, Locator locator, String type, String columnName, int level) { String getterName = (String) typesToGetterNames.get(type); if (getterName == null) throw new ValidationException("Incorrect or missing type attribute for sql:get-column: " + type, new LocationData(locator)); return interpretSimpleGetter(interpreterContext, locator, getterName, columnName, level); } private int getColumnsLevel; private String getColumnsFormat; private String getColumnsPrefix; private boolean getColumnsAllElements; private boolean inExclude; private StringBuffer getColumnsCurrentExclude; private Map getColumnsExcludes; public void characters(char[] chars, int start, int length) throws SAXException { if (inExclude) getColumnsCurrentExclude.append(chars, start, length); else super.characters(chars, start, length); } public void start(String uri, String localname, String qName, Attributes attributes) throws SAXException { final SQLProcessorInterpreterContext interpreterContext = getInterpreterContext(); interpreterContext.getNamespaceSupport().pushContext(); try { String levelString = attributes.getValue("ancestor"); int level = (levelString == null) ? 0 : Integer.parseInt(levelString); ResultSet rs = interpreterContext.getResultSet(level); if ("get-columns".equals(localname)) { // Remember attributes getColumnsLevel = level; getColumnsFormat = attributes.getValue("format"); getColumnsPrefix = attributes.getValue("prefix"); getColumnsAllElements = "true".equals(attributes.getValue("all-elements")); } else if ("get-column".equals(localname)) { String type = attributes.getValue("type"); String columnName = attributes.getValue("column"); if ("oxf:xmlFragment".equals(type)) { // XML fragment if (metadata == null) metadata = rs.getMetaData(); int columnIndex = rs.findColumn(columnName); int columnType = metadata.getColumnType(columnIndex); String columnTypeName = metadata.getColumnTypeName(columnIndex); if (columnType == Types.CLOB) { // The fragment is stored as a Clob Clob clob = rs.getClob(columnName); if (clob != null) { Reader reader = clob.getCharacterStream(); try { XMLUtils.parseDocumentFragment(reader, interpreterContext.getOutput()); } finally { reader.close(); } } } else if (interpreterContext.getDelegate().isXMLType(columnType, columnTypeName)) { // The fragment is stored as a native XMLType org.w3c.dom.Node node = interpreterContext.getDelegate().getDOM(rs, columnName); if (node != null) { TransformerUtils.getIdentityTransformer().transform(new DOMSource(node), new SAXResult(new ForwardingContentHandler() { protected ContentHandler getContentHandler() { return interpreterContext.getOutput(); } public void endDocument() { } public void startDocument() { } })); } } else { // The fragment is stored as a String String value = rs.getString(columnName); if (value != null) XMLUtils.parseDocumentFragment(value, interpreterContext.getOutput()); } } else { // xs:* Object o = interpretGenericGetter(interpreterContext, getDocumentLocator(), type, columnName, level); if (o != null) { if (o instanceof Clob) { Reader reader = ((Clob) o).getCharacterStream(); try { XMLUtils.readerToCharacters(reader, interpreterContext.getOutput()); } finally { reader.close(); } } else if (o instanceof Blob) { InputStream is = ((Blob) o).getBinaryStream(); try { XMLUtils.inputStreamToBase64Characters(is, interpreterContext.getOutput()); } finally { is.close(); } } else if (o instanceof InputStream) { InputStream is = (InputStream) o; try { XMLUtils.inputStreamToBase64Characters(is, interpreterContext.getOutput()); } finally { is.close(); } } else { XMLUtils.objectToCharacters(o, interpreterContext.getOutput()); } } } } else { // Simple getter (deprecated) Object o = interpretSimpleGetter(interpreterContext, getDocumentLocator(), localname, attributes.getValue("column"), level); if (o != null) { if (o instanceof Clob) { Reader reader = ((Clob) o).getCharacterStream(); try { XMLUtils.readerToCharacters(reader, interpreterContext.getOutput()); } finally { reader.close(); } } else if (o instanceof Blob) { InputStream is = ((Blob) o).getBinaryStream(); try { XMLUtils.inputStreamToBase64Characters(is, interpreterContext.getOutput()); } finally { is.close(); } } else if (o instanceof InputStream) { InputStream is = (InputStream) o; try { XMLUtils.inputStreamToBase64Characters(is, interpreterContext.getOutput()); } finally { is.close(); } } else { XMLUtils.objectToCharacters(o, interpreterContext.getOutput()); } } } } catch (Exception e) { throw new ValidationException(e, new LocationData(getDocumentLocator())); } } public void startElement(String uri, String localname, String qName, Attributes attributes) throws SAXException { if ("exclude".equals(localname)) { // Collect excludes if (getColumnsExcludes == null) getColumnsExcludes = new HashMap(); getColumnsCurrentExclude = new StringBuffer(); inExclude = true; } } public void endElement(String uri, String localname, String qName) throws SAXException { if ("exclude".equals(localname)) { // Add current exclude String value = getColumnsCurrentExclude.toString().toLowerCase(); getColumnsExcludes.put(value, value); inExclude = false; } } public void end(String uri, String localname, String qName) throws SAXException { SQLProcessorInterpreterContext interpreterContext = getInterpreterContext(); try { if ("get-columns".equals(localname)) { // Do nothing except collect sql:exclude ResultSet resultSet = interpreterContext.getResultSet(getColumnsLevel); if (metadata == null) metadata = resultSet.getMetaData(); NamespaceSupport namespaceSupport = interpreterContext.getNamespaceSupport(); // for (Enumeration e = namespaceSupport.getPrefixes(); e.hasMoreElements();) { // String p = (String) e.nextElement(); // String u = namespaceSupport.getURI(p); // System.out.println("Prefix: " + p + " -> " + u); // } // Get format once for all columns // Get URI once for all columns String outputElementURI = (getColumnsPrefix == null) ? "" : namespaceSupport.getURI(getColumnsPrefix); if (outputElementURI == null) throw new ValidationException("Invalid namespace prefix: " + getColumnsPrefix, new LocationData(getDocumentLocator())); // Iterate through all columns for (int i = 1; i <= metadata.getColumnCount(); i++) { // Get column name String columnName = metadata.getColumnName(i); // Make sure it is not excluded if (getColumnsExcludes != null && getColumnsExcludes.get(columnName.toLowerCase()) != null) continue; // Process column int columnType = metadata.getColumnType(i); String stringValue = null; Clob clobValue = null; Blob blobValue = null; if (columnType == Types.DATE) { Date value = resultSet.getDate(i); if (value != null) stringValue = ISODateUtils.formatDate(value, ISODateUtils.XS_DATE); } else if (columnType == Types.TIMESTAMP) { Timestamp value = resultSet.getTimestamp(i); if (value != null) stringValue = ISODateUtils.formatDate(value, ISODateUtils.XS_DATE_TIME_LONG); } else if (columnType == Types.DECIMAL || columnType == Types.NUMERIC) { BigDecimal value = resultSet.getBigDecimal(i); stringValue = (resultSet.wasNull()) ? null : value.toString(); } else if (columnType == 16) {// Types.BOOLEAN is present from JDK 1.4 only boolean value = resultSet.getBoolean(i); stringValue = (resultSet.wasNull()) ? null : (value ? "true" : "false"); } else if (columnType == Types.INTEGER || columnType == Types.SMALLINT || columnType == Types.TINYINT || columnType == Types.BIGINT) { long value = resultSet.getLong(i); stringValue = (resultSet.wasNull()) ? null : Long.toString(value); } else if (columnType == Types.DOUBLE || columnType == Types.FLOAT || columnType == Types.REAL) { double value = resultSet.getDouble(i); // For XPath 1.0, we have to get rid of the scientific notation stringValue = resultSet.wasNull() ? null : XMLUtils.removeScientificNotation(value); } else if (columnType == Types.CLOB) { clobValue = resultSet.getClob(i); } else if (columnType == Types.BLOB) { blobValue = resultSet.getBlob(i); } else { // Assume the type is compatible with getString() stringValue = resultSet.getString(i); } final boolean nonNullValue = stringValue != null || clobValue != null || blobValue != null; if (nonNullValue || getColumnsAllElements) { // Format element name String elementName = columnName; if ("xml".equals(getColumnsFormat)) { elementName = elementName.toLowerCase(); elementName = elementName.replace('_', '-'); } else if (getColumnsFormat != null) throw new ValidationException("Invalid get-columns format: " + getColumnsFormat, new LocationData(getDocumentLocator())); String elementQName = (outputElementURI.equals("")) ? elementName : getColumnsPrefix + ":" + elementName; ContentHandler output = interpreterContext.getOutput(); output.startElement(outputElementURI, elementName, elementQName, XMLUtils.EMPTY_ATTRIBUTES); // Output value if non-null if (nonNullValue) { if (clobValue == null && blobValue == null) { // Just output the String value as characters char[] localCharValue = stringValue.toCharArray(); output.characters(localCharValue, 0, localCharValue.length); } else if (clobValue != null) { // Clob: convert the Reader into characters Reader reader = clobValue.getCharacterStream(); try { XMLUtils.readerToCharacters(reader, output); } finally { reader.close(); } } else { // Blob: convert the InputStream into characters in Base64 InputStream is = blobValue.getBinaryStream(); try { XMLUtils.inputStreamToBase64Characters(is, output); } finally { is.close(); } } } output.endElement(outputElementURI, elementName, elementQName); } } } } catch (Exception e) { throw new ValidationException(e, new LocationData(getDocumentLocator())); } interpreterContext.getNamespaceSupport().popContext(); } } private static class ValueOfCopyOfInterpreter extends InterpreterContentHandler { DocumentWrapper wrapper; public ValueOfCopyOfInterpreter(SQLProcessorInterpreterContext interpreterContext) { super(interpreterContext, false); this.wrapper = new DocumentWrapper(interpreterContext.getCurrentNode().getDocument(), null); } public void start(String uri, String localname, String qName, Attributes attributes) throws SAXException { final SQLProcessorInterpreterContext interpreterContext = getInterpreterContext(); NamespaceSupport namespaceSupport = interpreterContext.getNamespaceSupport(); ContentHandler output = interpreterContext.getOutput(); namespaceSupport.pushContext(); try { String selectString = attributes.getValue("select"); // Variable context (obsolete) VariableContext variableContext = new VariableContext() { public Object getVariableValue(String namespaceURI, String prefix, String localName) throws UnresolvableException { if (!SQL_NAMESPACE_URI.equals(namespaceURI)) throw new UnresolvableException("Unbound variable: {" + namespaceURI + "}" + localName); if ("row-position".equals(localName)) { return new Integer(interpreterContext.getRowPosition()); } else throw new UnresolvableException("Unbound variable: {" + namespaceURI + "}" + localName); } }; // Interpret expression Object result = XPathUtils.selectObjectValue(interpreterContext.getCurrentNode(), selectString, interpreterContext.getPrefixesMap(), variableContext, interpreterContext.getFunctionContext()); if ("value-of".equals(localname) || "copy-of".equals(localname)) { // Case of Number and String if (result instanceof Number) { String stringValue; if (result instanceof Float || result instanceof Double) { stringValue = XMLUtils.removeScientificNotation(((Number) result).doubleValue()); } else { stringValue = Long.toString(((Number) result).longValue()); } // FIXME: what about BigDecimal and BigInteger: can they be returned? output.characters(stringValue.toCharArray(), 0, stringValue.length()); } else if (result instanceof String) { String stringValue = (String) result; output.characters(stringValue.toCharArray(), 0, stringValue.length()); } else if (result instanceof List) { if ("value-of".equals(localname)) { // Get string value // String stringValue = interpreterContext.getInput().createXPath(".").valueOf(result); // String stringValue = XPathCache.createCacheXPath(null, ".").valueOf(result); PooledXPathExpression expr = XPathCache.getXPathExpression(interpreterContext.getPipelineContext(), wrapper.wrap(result), "string(.)"); String stringValue; try { stringValue = (String)expr.evaluateSingle(); } catch (XPathException e) { throw new OXFException(e); } finally { if(expr != null) expr.returnToPool(); } output.characters(stringValue.toCharArray(), 0, stringValue.length()); } else { LocationSAXWriter saxw = new LocationSAXWriter(); saxw.setContentHandler(output); for (Iterator i = ((List) result).iterator(); i.hasNext();) { Node node = (Node) i.next(); saxw.write(node); } } } else if (result instanceof Node) { if ("value-of".equals(localname)) { // Get string value // String stringValue = interpreterContext.getInput().createXPath(".").valueOf(result); // String stringValue = XPathCache.createCacheXPath(null, ".").valueOf(result); PooledXPathExpression expr = XPathCache.getXPathExpression(interpreterContext.getPipelineContext(), wrapper.wrap(result), "string(.)"); String stringValue; try { stringValue = (String)expr.evaluateSingle(); } catch (XPathException e) { throw new OXFException(e); } finally { if(expr != null) expr.returnToPool(); } output.characters(stringValue.toCharArray(), 0, stringValue.length()); } else { LocationSAXWriter saxw = new LocationSAXWriter(); saxw.setContentHandler(output); saxw.write((Node) result); } } else throw new OXFException("Unexpected XPath result type: " + result.getClass()); } else { throw new OXFException("Invalid element: " + qName); } } catch (Exception e) { throw new ValidationException(e, new LocationData(getDocumentLocator())); } } public void end(String uri, String localname, String qName) throws SAXException { getInterpreterContext().getNamespaceSupport().popContext(); } } private static class RowResultsInterpreter extends InterpreterContentHandler { private SAXStore saxStore; private ContentHandler savedOutput; private class Group { private String columnName; private String columnValue; private SAXStore footer = new SAXStore(); private boolean showHeader; public Group(String columnName, ResultSet resultSet) throws SQLException { this.columnName = columnName; this.columnValue = resultSet.getString(columnName); } public boolean columnChanged(ResultSet resultSet) throws SQLException { String newValue = resultSet.getString(columnName); return (columnValue != null && !columnValue.equals(newValue)) || (newValue != null && !newValue.equals(columnValue)); } public void setColumnValue(ResultSet resultSet) throws SQLException { this.columnValue = resultSet.getString(columnName); } public boolean isShowHeader() { return showHeader; } public void setShowHeader(boolean showHeader) { this.showHeader = showHeader; } public SAXStore getFooter() { return footer; } } public RowResultsInterpreter(SQLProcessorInterpreterContext interpreterContext) { super(interpreterContext, false); } public void start(String uri, String localname, String qName, Attributes attributes) throws SAXException { // Only forward if the result set is not empty if (!getInterpreterContext().isEmptyResultSet()) { saxStore = new SAXStore(); saxStore.setDocumentLocator(getDocumentLocator()); savedOutput = getInterpreterContext().getOutput(); getInterpreterContext().setOutput(saxStore); setForward(true); } } public void end(String uri, String localname, String qName) throws SAXException { if (saxStore != null) { final SQLProcessorInterpreterContext interpreterContext = getInterpreterContext(); interpreterContext.setOutput(savedOutput); final ResultSet resultSet = interpreterContext.getResultSet(0); try { boolean hasNext = true; final int[] rowNum = {1}; final int[] groupCount = {0}; final List groups = new ArrayList(); // Interpret row-results for each result-set row InterpreterContentHandler contentHandler = new InterpreterContentHandler(interpreterContext, true) { public void startPrefixMapping(String prefix, String uri) throws SAXException { super.startPrefixMapping(prefix, uri); interpreterContext.declarePrefix(prefix, uri); } private boolean hiding; public void startElement(String uri, String localname, String qName, Attributes attributes) throws SAXException { if (!isInElementHandler() && SQL_NAMESPACE_URI.equals(uri)) { if (localname.equals("group")) { try { ResultSet resultSet = interpreterContext.getResultSet(0); // Save group information if first row if (rowNum[0] == 1) { groups.add(new Group(attributes.getValue("column"), resultSet)); } // Get current group information Group currentGroup = (Group) groups.get(groupCount[0]); if (rowNum[0] == 1 || columnChanged(resultSet, groups, groupCount[0])) { // Need to display group's header and footer currentGroup.setShowHeader(true); hiding = false; currentGroup.setColumnValue(resultSet); } else { // Hide group's header currentGroup.setShowHeader(false); hiding = true; } groupCount[0]++; } catch (SQLException e) { throw new ValidationException(e, new LocationData(getDocumentLocator())); } } else if (localname.equals("member")) { hiding = false; } else if (!hiding) { super.startElement(uri, localname, qName, attributes); } } else if (!hiding) { super.startElement(uri, localname, qName, attributes); } } public void endElement(String uri, String localname, String qName) throws SAXException { if (!isInElementHandler() && SQL_NAMESPACE_URI.equals(uri)) { if (localname.equals("group")) { groupCount[0]--; // Restore sending to the regular output Group currentGroup = (Group) groups.get(groupCount[0]); if (currentGroup.isShowHeader()) interpreterContext.setOutput(savedOutput); } else if (localname.equals("member")) { Group currentGroup = (Group) groups.get(groupCount[0] - 1); // The first time, everything is sent to the footer SAXStore if (currentGroup.isShowHeader()) { savedOutput = interpreterContext.getOutput(); interpreterContext.setOutput(currentGroup.getFooter()); hiding = false; } else hiding = true; } else if (!hiding) { super.endElement(uri, localname, qName); } } else if (!hiding) { super.endElement(uri, localname, qName); } } public void characters(char[] chars, int start, int length) throws SAXException { if (!hiding) { // Output only if the string is non-blank [FIXME: Incorrect white space handling!] // String s = new String(chars, start, length); // if (!s.trim().equals("")) super.characters(chars, start, length); } } }; // Initialize the content handler contentHandler.addElementHandler(new ExecuteInterpreter(interpreterContext), SQL_NAMESPACE_URI, "execute"); GetterInterpreter getterInterpreter = new GetterInterpreter(interpreterContext); contentHandler.addElementHandler(getterInterpreter, SQL_NAMESPACE_URI, "get-string"); contentHandler.addElementHandler(getterInterpreter, SQL_NAMESPACE_URI, "get-int"); contentHandler.addElementHandler(getterInterpreter, SQL_NAMESPACE_URI, "get-double"); contentHandler.addElementHandler(getterInterpreter, SQL_NAMESPACE_URI, "get-decimal"); contentHandler.addElementHandler(getterInterpreter, SQL_NAMESPACE_URI, "get-date"); contentHandler.addElementHandler(getterInterpreter, SQL_NAMESPACE_URI, "get-timestamp"); contentHandler.addElementHandler(getterInterpreter, SQL_NAMESPACE_URI, "get-column"); contentHandler.addElementHandler(getterInterpreter, SQL_NAMESPACE_URI, "get-columns"); ValueOfCopyOfInterpreter valueOfCopyOfInterpreter = new ValueOfCopyOfInterpreter(interpreterContext); contentHandler.addElementHandler(valueOfCopyOfInterpreter, SQL_NAMESPACE_URI, "value-of"); contentHandler.addElementHandler(valueOfCopyOfInterpreter, SQL_NAMESPACE_URI, "copy-of"); contentHandler.addElementHandler(new TextInterpreter(interpreterContext), SQL_NAMESPACE_URI, "text"); contentHandler.addElementHandler(new ForEachInterpreter(getInterpreterContext(), contentHandler.getElementHandlers()), SQL_NAMESPACE_URI, "for-each"); // Functions in this context Map functions = new HashMap(); functions.put("{" + SQL_NAMESPACE_URI + "}" + "row-position", new Function() { public Object call(org.jaxen.Context context, List args) { return new Integer(interpreterContext.getRowPosition()); } }); interpreterContext.pushFunctions(functions); try { // Iterate through the result set while (hasNext) { // Output footers that need it if (groups != null) { for (int i = groups.size() - 1; i >= 0; i--) { Group g1 = (Group) groups.get(i); if (columnChanged(resultSet, groups, i)) { g1.getFooter().replay(interpreterContext.getOutput()); g1.getFooter().clear(); } } groupCount[0] = 0; } // Set variables interpreterContext.setRowPosition(rowNum[0]); // Interpret row saxStore.replay(contentHandler); // Go to following row hasNext = resultSet.next(); rowNum[0]++; } // Output last footers for (int i = groups.size() - 1; i >= 0; i--) { Group group = (Group) groups.get(i); group.getFooter().replay(interpreterContext.getOutput()); group.getFooter().clear(); } } finally { interpreterContext.popFunctions(); } } catch (Exception e) { throw new ValidationException(e, new LocationData(getDocumentLocator())); } } } private boolean columnChanged(ResultSet resultSet, List groups, int level) throws SQLException { for (int i = level; i >= 0; i--) { Group group = (Group) groups.get(i); if (group.columnChanged(resultSet)) return true; } return false; } } private static class ForEachInterpreter extends InterpreterContentHandler { private Map elementHandlers; private SAXStore saxStore; private ContentHandler savedOutput; private String select; public ForEachInterpreter(SQLProcessorInterpreterContext interpreterContext, Map elementHandlers) { super(interpreterContext, false); this.elementHandlers = elementHandlers; } public void start(String uri, String localname, String qName, Attributes attributes) throws SAXException { // Everything will be stored in a SAXStore saxStore = new SAXStore(); saxStore.setDocumentLocator(getDocumentLocator()); savedOutput = getInterpreterContext().getOutput(); getInterpreterContext().setOutput(saxStore); setForward(true); // Get attributes select = attributes.getValue("select"); } public void end(String uri, String localname, String qName) throws SAXException { if (saxStore != null) { final SQLProcessorInterpreterContext interpreterContext = getInterpreterContext(); // Restore the regular output interpreterContext.setOutput(savedOutput); try { // Create a new InterpreterContentHandler with the same handlers as our parent InterpreterContentHandler contentHandler = new InterpreterContentHandler(interpreterContext, true); contentHandler.setElementHandlers(elementHandlers); // Scope functions final Node[] currentNode = new Node[1]; final int[] currentPosition = new int[1]; Map functions = new HashMap(); functions.put("current", new Function() { public Object call(org.jaxen.Context context, List args) { return currentNode[0]; } }); // FIXME: position() won't work because it will override // the default XPath position() function // We probably need to create a Jaxen Context directly to fix this // functions.put("position", new Function() { // public Object call(org.jaxen.Context context, List args) throws FunctionCallException { // return new Integer(currentPosition[0]); // } // }); interpreterContext.pushFunctions(functions); try { // Iterate through the result set int nodeCount = 1; for (Iterator i = XPathUtils.selectIterator(interpreterContext.getCurrentNode(), select, interpreterContext.getPrefixesMap(), null, interpreterContext.getFunctionContext()); i.hasNext(); nodeCount++) { currentNode[0] = (Node) i.next(); currentPosition[0] = nodeCount; // Interpret iteration interpreterContext.pushCurrentNode(currentNode[0]); saxStore.replay(contentHandler); interpreterContext.popCurrentNode(); } } finally { interpreterContext.popFunctions(); } } catch (Exception e) { throw new ValidationException(e, new LocationData(getDocumentLocator())); } } } } private static class NoResultsInterpreter extends InterpreterContentHandler { public NoResultsInterpreter(SQLProcessorInterpreterContext interpreterContext) { super(interpreterContext, false); } public void start(String uri, String localname, String qName, Attributes attributes) throws SAXException { // Only forward if the result set is empty if (getInterpreterContext().isEmptyResultSet()) { setForward(true); addElementHandler(new ExecuteInterpreter(getInterpreterContext()), SQL_NAMESPACE_URI, "execute"); ValueOfCopyOfInterpreter valueOfCopyOfInterpreter = new ValueOfCopyOfInterpreter(getInterpreterContext()); addElementHandler(valueOfCopyOfInterpreter, SQL_NAMESPACE_URI, "value-of"); addElementHandler(valueOfCopyOfInterpreter, SQL_NAMESPACE_URI, "copy-of"); addElementHandler(new TextInterpreter(getInterpreterContext()), SQL_NAMESPACE_URI, "text"); addElementHandler(new ForEachInterpreter(getInterpreterContext(), getElementHandlers()), SQL_NAMESPACE_URI, "for-each"); } } } private static class QueryInterpreter extends InterpreterContentHandler { public static final int QUERY = 0; public static final int UPDATE = 1; private int type; private StringBuffer query; private List queryParameters; private boolean hasReplaceOrSeparator; private Iterator nodeIterator; private String debugString; public QueryInterpreter(SQLProcessorInterpreterContext interpreterContext, int type) { super(interpreterContext, false); this.type = type; } public void characters(char[] chars, int start, int length) throws SAXException { if (query == null) query = new StringBuffer(); query.append(chars, start, length); } public void startElement(String uri, String localname, String qName, Attributes attributes) throws SAXException { super.startElement(uri, localname, qName, attributes); if (SQL_NAMESPACE_URI.equals(uri)) { if (localname.equals("param") || localname.equals("parameter")) { if (query == null) query = new StringBuffer(); // Add parameter information String direction = attributes.getValue("direction"); String type = attributes.getValue("type"); String sqlType = attributes.getValue("sql-type"); String select = attributes.getValue("select"); String separator = attributes.getValue("separator"); boolean replace = new Boolean(attributes.getValue("replace")).booleanValue(); String nullIf = attributes.getValue("null-if"); if (replace || separator != null) { // Remember that we have to replace at least once hasReplaceOrSeparator = true; } else { // Add question mark for prepared statement query.append(" ? "); } // Remember parameter if (queryParameters == null) queryParameters = new ArrayList(); queryParameters.add(new QueryParameter(direction, type, sqlType, select, separator, replace, nullIf, query.length(), new LocationData(getDocumentLocator()))); } else { // This must be either a get-column or a simple getter (deprecated) boolean isGetColumn = localname.equals("get-column"); String levelString = attributes.getValue("ancestor"); String columnName = attributes.getValue("column"); // Level defaults to 1 in query int level = (levelString == null) ? 1 : Integer.parseInt(levelString); if (level < 1) throw new ValidationException("Attribute level must be 1 or greater in query", new LocationData(getDocumentLocator())); // Set value try { Object value; if (isGetColumn) { String type = attributes.getValue("type"); ResultSet rs = getInterpreterContext().getResultSet(level); if ("oxf:xmlFragment".equals(type)) { ResultSetMetaData metadata = rs.getMetaData(); int columnType = metadata.getColumnType(rs.findColumn(columnName)); if (columnType == Types.CLOB) { value = rs.getClob(columnName); } else if (columnType == Types.BLOB) { throw new ValidationException("Cannot read a Blob as an oxf:xmlFragment", new LocationData(getDocumentLocator())); } else { value = rs.getString(columnName); } } else value = GetterInterpreter.interpretGenericGetter(getInterpreterContext(), getDocumentLocator(), type, columnName, level); } else { value = GetterInterpreter.interpretSimpleGetter(getInterpreterContext(), getDocumentLocator(), localname, columnName, level); } ((QueryParameter) queryParameters.get(queryParameters.size() - 1)).setValue(value); } catch (Exception e) { throw new ValidationException(e, new LocationData(getDocumentLocator())); } } } } public void start(String uri, String localname, String qName, Attributes attributes) throws SAXException { // Get select attribute String selectString = attributes.getValue("select"); if (selectString != null) { if (type != UPDATE) throw new ValidationException("select attribute is valid only on update element", new LocationData(getDocumentLocator())); nodeIterator = XPathUtils.selectIterator(getInterpreterContext().getCurrentNode(), selectString, getInterpreterContext().getPrefixesMap(), null, getInterpreterContext().getFunctionContext()); } // Get debug attribute debugString = attributes.getValue("debug"); } public void end(String uri, String localname, String qName) throws SAXException { // Validate query if (query == null) throw new ValidationException("Missing query", new LocationData(getDocumentLocator())); // Execute query try { // Create a single PreparedStatement if the query is not modified at each iteration PreparedStatement stmt = null; if (!hasReplaceOrSeparator) { String queryString = query.toString(); stmt = getInterpreterContext().getConnection().prepareStatement(queryString); getInterpreterContext().setStatementString(queryString); } getInterpreterContext().setStatement(stmt); int nodeCount = 1; // Iterate through all source nodes (only one if "select" attribute is missing) for (Iterator j = (nodeIterator != null) ? nodeIterator : Collections.singletonList(getInterpreterContext().getCurrentNode()).iterator(); j.hasNext(); nodeCount++) { final Node currentNode = (Node) j.next(); final int _nodeCount = nodeCount; // LocationData locationData = (currentNode instanceof Element) // ? (LocationData) ((Element) currentNode).getData() : null; // Scope sql:position variable (deprecated) Map prefixesMap = getInterpreterContext().getPrefixesMap(); VariableContext variableContext = new VariableContext() { public Object getVariableValue(String namespaceURI, String prefix, String localName) throws UnresolvableException { if (!SQL_NAMESPACE_URI.equals(namespaceURI)) throw new UnresolvableException("Unbound variable: {" + namespaceURI + "}" + localName); if ("position".equals(localName)) { return new Integer(_nodeCount); } else throw new UnresolvableException("Unbound variable: {" + namespaceURI + "}" + localName); } }; // Scope sql:current(), sql:position() and sql:get-column functions Map functions = new HashMap(); functions.put("{" + SQL_NAMESPACE_URI + "}" + "current", new Function() { public Object call(org.jaxen.Context context, List args) { return currentNode; } }); functions.put("{" + SQL_NAMESPACE_URI + "}" + "position", new Function() { public Object call(org.jaxen.Context context, List args) { return new Integer(_nodeCount); } }); functions.put("{" + SQL_NAMESPACE_URI + "}" + "get-column", new Function() { public Object call(org.jaxen.Context context, List args) { int argc = args.size(); if (argc < 1 || argc > 2) throw new OXFException("sql:get-column expects one or two parameters"); String colname = (String) args.get(0); String levelString = (argc == 2) ? (String) args.get(1) : null; int level = (levelString == null) ? 1 : Integer.parseInt(levelString); if (level < 1) throw new OXFException("Attribute level must be 1 or greater in query"); ResultSet rs = getInterpreterContext().getResultSet(level); try { return rs.getString(colname); } catch (SQLException e) { throw new OXFException(e); } } }); try { getInterpreterContext().pushFunctions(functions); // Replace inline parameters StringBuffer replacedQuery = query; if (hasReplaceOrSeparator) { replacedQuery = new StringBuffer(); String queryString = query.toString(); int firstIndex = 0; for (Iterator i = queryParameters.iterator(); i.hasNext();) { QueryParameter parameter = (QueryParameter) i.next(); try { String select = parameter.getSelect(); String separator = parameter.getSeparator(); if (parameter.isReplace() || separator != null) { // Handle query modification for this parameter int secondIndex = parameter.getReplaceIndex(); replacedQuery.append(queryString.substring(firstIndex, secondIndex)); // Create List of either strings or nodes List values; if (separator == null) { // Read the expression as a string if there is a select, otherwise get parameter value as string Object objectValue; if (select != null) { objectValue = XPathUtils.selectStringValue(currentNode, parameter.getSelect(), prefixesMap, variableContext, getInterpreterContext().getFunctionContext()); } else { objectValue = (parameter.getValue() == null) ? null : parameter.getValue().toString(); } values = Collections.singletonList(objectValue); } else { // Accept only a node or node-set if there is a separator, in which case a select is mandatory Object objectValue = XPathUtils.selectObjectValue(currentNode, parameter.getSelect(), prefixesMap, variableContext, getInterpreterContext().getFunctionContext()); if (objectValue instanceof List) { values = (List) objectValue; } else if (objectValue instanceof Node) { values = Collections.singletonList(objectValue); } else { throw new OXFException("sql:parameter with separator requires an expression returning a node-set"); } // Set values on the parameter if they are not replaced immediately if (!parameter.isReplace()) parameter.setValues(values); } if (parameter.isReplace()) { // Replace in the query for (Iterator k = values.iterator(); k.hasNext();) { Object objectValue = k.next(); // Get value as a string String stringValue = (objectValue instanceof Node) ? XPathUtils.selectStringValue((Node) objectValue, ".") : (String) objectValue; // null values are prohibited if (stringValue == null) throw new OXFException("Cannot replace value with null result"); if ("int".equals(parameter.getType()) || "xs:int".equals(parameter.getType())) { replacedQuery.append(Integer.parseInt(stringValue)); } else if ("literal-string".equals(parameter.getType()) || "oxf:literalString".equals(parameter.getType())) { replacedQuery.append(stringValue); } else throw new ValidationException("Unsupported parameter type: " + parameter.getType(), parameter.getLocationData()); // Append separator if needed if (k.hasNext()) replacedQuery.append(separator); } } else { // Update prepared statement for (int k = 0; k < values.size(); k++) { if (k > 0) replacedQuery.append(separator); replacedQuery.append(" ? "); } } firstIndex = secondIndex; } } catch (ValidationException e) { throw e; } catch (Exception e) { throw new ValidationException(e, parameter.getLocationData()); } } if (firstIndex < queryString.length()) { replacedQuery.append(queryString.substring(firstIndex)); } // We create a new PreparedStatement for each iteration String replacedQueryString = replacedQuery.toString(); if (stmt != null) { stmt.close(); } stmt = getInterpreterContext().getConnection().prepareStatement(replacedQueryString); getInterpreterContext().setStatement(stmt); getInterpreterContext().setStatementString(replacedQueryString); } // Output debug if needed if (debugString != null) logger.info("PreparedStatement (debug=\"" + debugString + "\"):\n" + getInterpreterContext().getStatementString()); // Set prepared statement parameters if (queryParameters != null) { int index = 1; for (Iterator i = queryParameters.iterator(); i.hasNext();) { QueryParameter parameter = (QueryParameter) i.next(); try { if (!parameter.isReplace()) { String select = parameter.getSelect(); String type = parameter.getType(); boolean doSetNull = parameter.getNullIf() != null && XPathUtils.selectBooleanValue(currentNode, parameter.getNullIf(), prefixesMap, variableContext, getInterpreterContext().getFunctionContext()).booleanValue(); if ("string".equals(type) || "xs:string".equals(type) || "oxf:xmlFragment".equals(type)) { // Set a string or XML Fragment // List of Clobs, strings or nodes List values; if (parameter.getValues() != null) values = parameter.getValues(); else if (select != null) values = Collections.singletonList(XPathUtils.selectObjectValue(currentNode, parameter.getSelect(), prefixesMap, variableContext, getInterpreterContext().getFunctionContext())); else values = Collections.singletonList(parameter.getValue()); // Iterate through all values for (Iterator k = values.iterator(); k.hasNext(); index++) { Object objectValue = k.next(); // Get Clob, String or Element Object value = null; if (!doSetNull) { if (objectValue instanceof Clob || objectValue instanceof Blob || objectValue instanceof String) { // Leave unchanged value = objectValue; } else if ("oxf:xmlFragment".equals(type)) { // Case of XML Fragment // Get an Element or a String if (objectValue instanceof Element) value = objectValue; else if (objectValue instanceof List) { List list = ((List) objectValue); if (list.size() == 0) value = null; else if (list.get(0) instanceof Element) value = list.get(0); else throw new OXFException("oxf:xmlFragment type expects a node-set an element node in first position"); } else if (objectValue != null) throw new OXFException("oxf:xmlFragment type expects a node, a node-set or a string"); } else { // Case of String if (objectValue instanceof Node) value = XPathUtils.selectStringValue((Node) objectValue, "."); else if (objectValue instanceof List) { List list = ((List) objectValue); if (list.size() == 0) value = null; else if (list.get(0) instanceof Node) value = XPathUtils.selectStringValue((Node) list.get(0), "."); else throw new OXFException("Invalid type: " + objectValue.getClass()); } else if (objectValue != null) throw new OXFException("Invalid type: " + objectValue.getClass()); } } String sqlType = parameter.getSqlType(); if (value == null) { if (SQL_TYPE_CLOB.equals(sqlType)) stmt.setNull(index, Types.CLOB); else if (SQL_TYPE_BLOB.equals(sqlType)) stmt.setNull(index, Types.BLOB); else stmt.setNull(index, Types.VARCHAR); } else if (value instanceof Clob) { Clob clob = (Clob) value; if (SQL_TYPE_CLOB.equals(sqlType)) { // Set Clob as Clob stmt.setClob(index, clob); } else { // Set Clob as String long clobLength = clob.length(); if (clobLength > (long) Integer.MAX_VALUE) throw new OXFException("CLOB length can't be larger than 2GB"); stmt.setString(index, clob.getSubString(1, (int) clob.length())); } // TODO: Check BLOB: should we be able to set a String as a Blob? } else if (value instanceof String || value instanceof Element) { // Make sure we create a Document from the Element if we have one Document xmlFragmentDocument = (value instanceof Element) ? DocumentHelper.createDocument(((Element) value).createCopy()) : null; // Convert document into an XML String if necessary if (value instanceof Element && !SQL_TYPE_XMLTYPE.equals(sqlType)) { // Convert Document into a String boolean serializeXML11 = getInterpreterContext().getPropertySet().getBoolean("serialize-xml-11", false).booleanValue(); value = XMLUtils.domToString(XMLUtils.adjustNamespaces(xmlFragmentDocument, serializeXML11), false, false); } if (SQL_TYPE_XMLTYPE.equals(sqlType)) { // Set DOM using native XML type if (value instanceof Element) { // We have a Document - convert it to DOM // TEMP HACK: We can't seem to be able to convert directly from dom4j to regular DOM (NAMESPACE_ERR from Xerces) // DOMResult domResult = new DOMResult(); // TransformerUtils.getIdentityTransformer().transform(new DocumentSource(xmlFragmentDocument), domResult);xxx // org.w3c.dom.Node node = domResult.getNode(); boolean serializeXML11 = getInterpreterContext().getPropertySet().getBoolean("serialize-xml-11", false).booleanValue(); String stringValue = XMLUtils.domToString(XMLUtils.adjustNamespaces(xmlFragmentDocument, serializeXML11), false, false); // TEMP HACK: Oracle seems to have a problem with XMLType instanciated from a DOM, so we pass a String // org.w3c.dom.Node node = XMLUtils.stringToDOM(stringValue); // if (!(node instanceof org.w3c.dom.Document)) { // // FIXME: Is this necessary? Why wouldn't we always get a Document from the transformation? // org.w3c.dom.Document document = XMLUtils.createDocument(); // document.appendChild(node); // node = document; // } // getInterpreterContext().getDelegate().setDOM(stmt, index, (org.w3c.dom.Document) node); getInterpreterContext().getDelegate().setDOM(stmt, index, stringValue); } else { // We have a String - create a DOM from it // FIXME: Do we need this? throw new UnsupportedOperationException("Setting native XML type from a String is not yet supported. Please report this usage."); } } else if (SQL_TYPE_CLOB.equals(sqlType)) { // Set String as Clob String stringValue = (String) value; getInterpreterContext().getDelegate().setClob(stmt, index, stringValue); // TODO: Check BLOB: should we be able to set a String as a Blob? } else { // Set String as String stmt.setString(index, (String) value); } } else throw new OXFException("Invalid parameter type: " + parameter.getType()); } } else if ("xs:base64Binary".equals(type)) { // We are writing binary data encoded in Base 64. The only target supported // is Blob // For now, only support passing a string from the input document String sqlType = parameter.getSqlType(); if (sqlType != null && !SQL_TYPE_CLOB.equals(sqlType)) throw new OXFException("Invalid sql-type attribute: " + sqlType); if (select == null) throw new UnsupportedOperationException("Setting BLOB requires a select attribute."); // Base64 XPathContentHandler xpathContentHandler = getInterpreterContext().getXPathContentHandler(); if (xpathContentHandler != null && xpathContentHandler.containsExpression(parameter.getSelect())) { // Handle streaming if possible OutputStream blobOutputStream = getInterpreterContext().getDelegate().getBlobOutputStream(stmt, index); xpathContentHandler.selectContentHandler(parameter.getSelect(), new Base64ContentHandler(blobOutputStream)); blobOutputStream.close(); } else { String base64Value = XPathUtils.selectStringValue(currentNode, parameter.getSelect(), prefixesMap, variableContext, getInterpreterContext().getFunctionContext()); getInterpreterContext().getDelegate().setBlob(stmt, index, XMLUtils.base64StringToByteArray(base64Value)); } } else { // Simple cases // List of strings or nodes List values; if (parameter.getValues() != null) values = parameter.getValues(); else if (select != null) values = Collections.singletonList(XPathUtils.selectStringValue(currentNode, parameter.getSelect(), prefixesMap, variableContext, getInterpreterContext().getFunctionContext())); else values = Collections.singletonList(parameter.getValue()); // Iterate through all values for (Iterator k = values.iterator(); k.hasNext(); index++) { Object objectValue = k.next(); // Get String value String stringValue = null; if (!doSetNull) { if (objectValue instanceof String) stringValue = (String) objectValue; else if (objectValue != null) stringValue = XPathUtils.selectStringValue((Node) objectValue, "."); } // For the specific type, set to null or convert String value if ("int".equals(type) || "xs:int".equals(type)) { if (stringValue == null) stmt.setNull(index, Types.INTEGER); else stmt.setInt(index, new Integer(stringValue).intValue()); } else if ("date".equals(type) || "xs:date".equals(type)) { if (stringValue == null) { stmt.setNull(index, Types.DATE); } else { java.sql.Date date = new java.sql.Date(ISODateUtils.parseDate(stringValue).getTime()); stmt.setDate(index, date); } } else if ("xs:dateTime".equals(type)) { if (stringValue == null) { stmt.setNull(index, Types.TIMESTAMP); } else { java.sql.Timestamp timestamp = new java.sql.Timestamp(ISODateUtils.parseDate(stringValue).getTime()); stmt.setTimestamp(index, timestamp); } } else if ("xs:boolean".equals(type)) { if (stringValue == null) stmt.setNull(index, Types.INTEGER); // Types.BOOLEAN is present from JDK 1.4 only else stmt.setBoolean(index, "true".equals(stringValue)); } else if ("xs:decimal".equals(type)) { if (stringValue == null) stmt.setNull(index, Types.DECIMAL); else stmt.setBigDecimal(index, new BigDecimal(stringValue)); } else if ("xs:float".equals(type)) { if (stringValue == null) stmt.setNull(index, Types.FLOAT); else stmt.setFloat(index, Float.parseFloat(stringValue)); } else if ("xs:double".equals(type)) { if (stringValue == null) stmt.setNull(index, Types.DOUBLE); else stmt.setDouble(index, Double.parseDouble(stringValue)); } else if ("xs:anyURI".equals(type)) { String sqlType = parameter.getSqlType(); if (sqlType != null && !SQL_TYPE_CLOB.equals(sqlType)) throw new OXFException("Invalid sql-type attribute: " + sqlType); if (stringValue == null) { stmt.setNull(index, Types.BLOB); } else { // Dereference the URI and write to the BLOB OutputStream blobOutputStream = getInterpreterContext().getDelegate().getBlobOutputStream(stmt, index); XMLUtils.anyURIToOutputStream(stringValue, blobOutputStream); blobOutputStream.close(); } } else throw new ValidationException("Unsupported parameter type: " + type, parameter.getLocationData()); } } } } catch (ValidationException e) { throw e; } catch (Exception e) { throw new ValidationException(e, parameter.getLocationData()); } } } } finally { getInterpreterContext().popFunctions(); } if (type == QUERY) { if (nodeCount > 1) throw new ValidationException("More than one iteration on query element", new LocationData(getDocumentLocator())); ResultSet resultSet = stmt.executeQuery(); boolean hasNext = resultSet.next(); getInterpreterContext().setEmptyResultSet(!hasNext); // Close result set and statement immediately if possible if (getInterpreterContext().isEmptyResultSet()) { stmt.close(); resultSet = null; stmt = null; getInterpreterContext().setStatement(null); } // Remember result set and statement getInterpreterContext().setResultSet(resultSet); } else if (type == UPDATE) { int updateCount = stmt.executeUpdate(); getInterpreterContext().setUpdateCount(updateCount);//FIXME: should add? } } } catch (Exception e) { // FIXME: should store exception so that it can be retrieved // Actually, we'll need a global exception mechanism for pipelines, so this may end up being done // in XPL or BPEL. // Log closest query related to the exception if we can find it String statementString = getInterpreterContext().getStatementString(); logger.error("PreparedStatement:\n" + statementString); // And throw throw new ValidationException(e, new LocationData(getDocumentLocator())); } } } private static class ConfigInterpreter extends InterpreterContentHandler { public ConfigInterpreter(SQLProcessorInterpreterContext interpreterContext) { super(interpreterContext, true); final SQLProcessorInterpreterContext _interpreterContext = interpreterContext; addElementHandler(new InterpreterContentHandler(interpreterContext, true) { public void start(String uri, String localname, String qName, Attributes attributes) { addElementHandler(new InterpreterContentHandler() { StringBuffer datasourceName; public void characters(char[] chars, int start, int length) { if (datasourceName == null) datasourceName = new StringBuffer(); datasourceName.append(chars, start, length); } public void end(String uri, String localname, String qName) { // Validate datasource element if (datasourceName == null) throw new ValidationException("Missing datasource name in datasource element", new LocationData(getDocumentLocator())); // Get the connection from the datasource and set in context try { _interpreterContext.setConnection(getDocumentLocator(), datasourceName.toString()); } catch (Exception e) { throw new ValidationException(e, new LocationData(getDocumentLocator())); } } }, SQL_NAMESPACE_URI, "datasource"); addElementHandler(new ExecuteInterpreter(getInterpreterContext()), SQL_NAMESPACE_URI, "execute"); ValueOfCopyOfInterpreter valueOfCopyOfInterpreter = new ValueOfCopyOfInterpreter(getInterpreterContext()); addElementHandler(valueOfCopyOfInterpreter, SQL_NAMESPACE_URI, "value-of"); addElementHandler(valueOfCopyOfInterpreter, SQL_NAMESPACE_URI, "copy-of"); addElementHandler(new TextInterpreter(getInterpreterContext()), SQL_NAMESPACE_URI, "text"); addElementHandler(new ForEachInterpreter(getInterpreterContext(), getElementHandlers()), SQL_NAMESPACE_URI, "for-each"); } public void end(String uri, String localname, String qName) { // Close connection // NOTE: Don't do this anymore: the connection will be closed when the context is destroyed } }, SQL_NAMESPACE_URI, "connection"); addElementHandler(new TextInterpreter(interpreterContext), SQL_NAMESPACE_URI, "text"); } public void start(String uri, String localname, String qName, Attributes attributes) throws SAXException { getInterpreterContext().getOutput().startDocument(); } public void end(String uri, String localname, String qName) throws SAXException { getInterpreterContext().getOutput().endDocument(); } } private static class TextInterpreter extends InterpreterContentHandler { private StringBuffer text; public TextInterpreter(SQLProcessorInterpreterContext interpreterContext) { super(interpreterContext, false); } public void characters(char[] chars, int start, int length) throws SAXException { if (text == null) text = new StringBuffer(); text.append(chars, start, length); } public void start(String uri, String localname, String qName, Attributes attributes) throws SAXException { text = null; } public void end(String uri, String localname, String qName) throws SAXException { char[] localText = text.toString().toCharArray(); getInterpreterContext().getOutput().characters(localText, 0, localText.length); } } private static class RootInterpreter extends InterpreterContentHandler { private SQLProcessorInterpreterContext interpreterContext; private NamespaceSupport namespaceSupport = new NamespaceSupport(); public RootInterpreter(PipelineContext context, OXFProperties.PropertySet propertySet, Node input, Datasource datasource, XPathContentHandler xpathContentHandler, ContentHandler output) { super(null, false); interpreterContext = new SQLProcessorInterpreterContext(propertySet); interpreterContext.setPipelineContext(context); interpreterContext.setInput(input); interpreterContext.setDatasource(datasource); interpreterContext.setXPathContentHandler(xpathContentHandler); interpreterContext.setOutput(output); interpreterContext.setNamespaceSupport(namespaceSupport); addElementHandler(new ConfigInterpreter(interpreterContext), SQL_NAMESPACE_URI, "config"); } public void startElement(String uri, String localname, String qName, Attributes attributes) throws SAXException { try { namespaceSupport.pushContext(); super.startElement(uri, localname, qName, attributes); } catch (Exception t) { dispose(); throw new OXFException(t); } } public void endElement(String uri, String localname, String qName) throws SAXException { try { super.endElement(uri, localname, qName); namespaceSupport.popContext(); } catch (Exception t) { dispose(); throw new OXFException(t); } } public void startPrefixMapping(String prefix, String uri) throws SAXException { try { super.startPrefixMapping(prefix, uri); interpreterContext.declarePrefix(prefix, uri); } catch (Exception t) { dispose(); throw new OXFException(t); } } public void characters(char[] chars, int start, int length) throws SAXException { try { super.characters(chars, start, length); } catch (Exception t) { dispose(); throw new OXFException(t); } } public void endDocument() throws SAXException { try { super.endDocument(); } catch (Exception t) { dispose(); throw new OXFException(t); } } public void ignorableWhitespace(char[] chars, int start, int length) throws SAXException { try { super.ignorableWhitespace(chars, start, length); } catch (Exception t) { dispose(); throw new OXFException(t); } } public void processingInstruction(String s, String s1) throws SAXException { try { super.processingInstruction(s, s1); } catch (Exception t) { dispose(); throw new OXFException(t); } } public void skippedEntity(String s) throws SAXException { try { super.skippedEntity(s); } catch (Exception t) { dispose(); throw new OXFException(t); } } public void startDocument() throws SAXException { try { super.startDocument(); } catch (Exception t) { dispose(); throw new OXFException(t); } } public void endPrefixMapping(String s) throws SAXException { try { super.endPrefixMapping(s); } catch (Exception t) { dispose(); throw new OXFException(t); } } public Locator getDocumentLocator() { try { return super.getDocumentLocator(); } catch (Exception t) { dispose(); throw new OXFException(t); } } public void setDocumentLocator(Locator locator) { try { super.setDocumentLocator(locator); } catch (Exception t) { dispose(); throw new OXFException(t); } } private void dispose() { // NOTE: Don't do this anymore: the connection will be closed when the context is destroyed } } private static class InterpreterContentHandler extends ForwardingContentHandler { private SQLProcessorInterpreterContext interpreterContext; private boolean forward; private Locator documentLocator; private Map elementHandlers = new HashMap(); private int forwardingLevel = -1; private InterpreterContentHandler currentHandler; private int level = 0; private String currentKey; public InterpreterContentHandler() { this(null, false); } public InterpreterContentHandler(SQLProcessorInterpreterContext interpreterContext, boolean forward) { this.interpreterContext = interpreterContext; this.forward = forward; } public void addElementHandler(InterpreterContentHandler handler, String uri, String localname) { elementHandlers.put("{" + uri + "}" + localname, handler); } public Map getElementHandlers() { return elementHandlers; } public void setElementHandlers(Map elementHandlers) { this.elementHandlers = elementHandlers; } public void startElement(String uri, String localname, String qName, Attributes attributes) throws SAXException { if (forwardingLevel == -1 && elementHandlers.size() > 0) { String key = "{" + uri + "}" + localname; InterpreterContentHandler elementHandler = (InterpreterContentHandler) elementHandlers.get(key); if (elementHandler != null) { forwardingLevel = level; currentKey = key; currentHandler = elementHandler; elementHandler.setDocumentLocator(documentLocator); elementHandler.start(uri, localname, qName, attributes); } else super.startElement(uri, localname, qName, attributes); } else super.startElement(uri, localname, qName, attributes); level++; } public void endElement(String uri, String localname, String qName) throws SAXException { level--; if (forwardingLevel == level) { String key = "{" + uri + "}" + localname; if (!currentKey.equals(key)) throw new ValidationException("Illegal document: expecting " + key + ", got " + currentKey, new LocationData(getDocumentLocator())); InterpreterContentHandler elementHandler = (InterpreterContentHandler) elementHandlers.get(key); forwardingLevel = -1; currentKey = null; currentHandler = null; elementHandler.end(uri, localname, qName); } else super.endElement(uri, localname, qName); } public void setDocumentLocator(Locator locator) { this.documentLocator = locator; super.setDocumentLocator(locator); } public Locator getDocumentLocator() { return documentLocator; } public void startPrefixMapping(String s, String s1) throws SAXException { super.startPrefixMapping(s, s1); } public void start(String uri, String localname, String qName, Attributes attributes) throws SAXException { } public void end(String uri, String localname, String qName) throws SAXException { } protected boolean isInElementHandler() { return forwardingLevel > -1; } protected ContentHandler getContentHandler() { if (currentHandler != null) return currentHandler; else if (forward) return interpreterContext.getOutput(); else return null; } public void characters(char[] chars, int start, int length) throws SAXException { if (currentHandler == null) { // Output only if the string is non-blank [FIXME: Incorrect white space handling!] // String s = new String(chars, start, length); // if (!s.trim().equals("")) super.characters(chars, start, length); } else { super.characters(chars, start, length); } } public SQLProcessorInterpreterContext getInterpreterContext() { return interpreterContext; } public boolean isForward() { return forward; } public void setForward(boolean forward) { this.forward = forward; } } private static class QueryParameter { private String direction; private String type; private String sqlType; private String select; private String separator; private boolean replace; private String nullIf; private int replaceIndex; private Object value; private List values; private LocationData locationData; public QueryParameter(String direction, String type, String sqlType, String select, String separator, boolean replace, String nullIf, int replaceIndex, LocationData locationData) { this.direction = direction; this.type = type; this.sqlType = sqlType; this.select = select; this.separator = separator; this.replace = replace; this.nullIf = nullIf; this.replaceIndex = replaceIndex; this.locationData = locationData; } public void setValue(Object value) { this.value = value; } public String getDirection() { return direction; } public String getType() { return type; } public String getSqlType() { return sqlType; } public String getSelect() { return select; } public String getSeparator() { return separator; } public boolean isReplace() { return replace; } public String getNullIf() { return nullIf; } public int getReplaceIndex() { return replaceIndex; } public Object getValue() { return value; } public LocationData getLocationData() { return locationData; } public List getValues() { return values; } public void setValues(List values) { this.values = values; } } private static abstract class ForwardingContentHandler implements ContentHandler { public ForwardingContentHandler() { } protected abstract ContentHandler getContentHandler(); public void characters(char[] chars, int start, int length) throws SAXException { ContentHandler contentHandler = getContentHandler(); if (contentHandler != null) contentHandler.characters(chars, start, length); } public void endDocument() throws SAXException { ContentHandler contentHandler = getContentHandler(); if (contentHandler != null) contentHandler.endDocument(); } public void endElement(String uri, String localname, String qName) throws SAXException { ContentHandler contentHandler = getContentHandler(); if (contentHandler != null) contentHandler.endElement(uri, localname, qName); } public void endPrefixMapping(String s) throws SAXException { ContentHandler contentHandler = getContentHandler(); if (contentHandler != null) contentHandler.endPrefixMapping(s); } public void ignorableWhitespace(char[] chars, int start, int length) throws SAXException { ContentHandler contentHandler = getContentHandler(); if (contentHandler != null) contentHandler.ignorableWhitespace(chars, start, length); } public void processingInstruction(String s, String s1) throws SAXException { ContentHandler contentHandler = getContentHandler(); if (contentHandler != null) contentHandler.processingInstruction(s, s1); } public void setDocumentLocator(Locator locator) { ContentHandler contentHandler = getContentHandler(); if (contentHandler != null) contentHandler.setDocumentLocator(locator); } public void skippedEntity(String s) throws SAXException { ContentHandler contentHandler = getContentHandler(); if (contentHandler != null) contentHandler.skippedEntity(s); } public void startDocument() throws SAXException { ContentHandler contentHandler = getContentHandler(); if (contentHandler != null) contentHandler.startDocument(); } public void startElement(String uri, String localname, String qName, Attributes attributes) throws SAXException { ContentHandler contentHandler = getContentHandler(); if (contentHandler != null) contentHandler.startElement(uri, localname, qName, attributes); } public void startPrefixMapping(String s, String s1) throws SAXException { ContentHandler contentHandler = getContentHandler(); if (contentHandler != null) contentHandler.startPrefixMapping(s, s1); } } }
Use better empty document, so that XPath wrapper doesn't choke. The document will not be used anyway.
src/java/org/orbeon/oxf/processor/sql/SQLProcessor.java
Use better empty document, so that XPath wrapper doesn't choke. The document will not be used anyway.
Java
apache-2.0
a398a73fc8197f5267e80cb7569f32809e0f13dd
0
phac-nml/irida,phac-nml/irida,phac-nml/irida,phac-nml/irida,phac-nml/irida,phac-nml/irida,phac-nml/irida,phac-nml/irida
package ca.corefacility.bioinformatics.irida.ria.web.ajax.ontologies; import java.util.Collection; import java.util.List; import java.util.stream.Collectors; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import ca.corefacility.bioinformatics.irida.ria.web.ajax.dto.TaxonomyEntry; import ca.corefacility.bioinformatics.irida.service.TaxonomyService; import ca.corefacility.bioinformatics.irida.util.TreeNode; /** * Handle asynchronous request related to the taxonomy ontology. */ @RestController @RequestMapping("/ajax/taxonomy") public class TaxonomyAjaxController { private final TaxonomyService taxonomyService; @Autowired public TaxonomyAjaxController(TaxonomyService taxonomyService) { this.taxonomyService = taxonomyService; } /** * Query the taxonomy ontology and return a list of taxonomy with their children * * @param q {@link String} - term to query the ontology by. * @return {@link ResponseEntity} */ @RequestMapping("") public ResponseEntity<List<TaxonomyEntry>> searchTaxonomy(@RequestParam String q) { Collection<TreeNode<String>> results = taxonomyService.search(q); List<TaxonomyEntry> entries = results.stream() .map(TaxonomyEntry::new) .collect(Collectors.toList()); return ResponseEntity.ok(entries); } }
src/main/java/ca/corefacility/bioinformatics/irida/ria/web/ajax/ontologies/TaxonomyAjaxController.java
package ca.corefacility.bioinformatics.irida.ria.web.ajax.ontologies; import java.util.Collection; import java.util.List; import java.util.stream.Collectors; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import ca.corefacility.bioinformatics.irida.ria.web.ajax.dto.TaxonomyEntry; import ca.corefacility.bioinformatics.irida.service.TaxonomyService; import ca.corefacility.bioinformatics.irida.util.TreeNode; @RestController @RequestMapping("/ajax/taxonomy") public class TaxonomyAjaxController { private final TaxonomyService taxonomyService; @Autowired public TaxonomyAjaxController(TaxonomyService taxonomyService) { this.taxonomyService = taxonomyService; } @RequestMapping("") public ResponseEntity<List<TaxonomyEntry>> searchTaxonomy(@RequestParam String q) { Collection<TreeNode<String>> results = taxonomyService.search(q); List<TaxonomyEntry> entries = results.stream().map(TaxonomyEntry::new).collect(Collectors.toList()); return ResponseEntity.ok(entries); } }
��️ Update JavaDoc
src/main/java/ca/corefacility/bioinformatics/irida/ria/web/ajax/ontologies/TaxonomyAjaxController.java
��️ Update JavaDoc
Java
apache-2.0
bd3bf577fbd2061fef43889b24f8dbcf0fa33d16
0
googleads/googleads-mobile-android-mediation
package com.google.ads.mediation.pangle.rtb; import static com.google.ads.mediation.pangle.PangleConstants.ERROR_INVALID_BID_RESPONSE; import static com.google.ads.mediation.pangle.PangleConstants.ERROR_INVALID_SERVER_PARAMETERS; import static com.google.ads.mediation.pangle.PangleMediationAdapter.TAG; import android.graphics.drawable.Drawable; import android.net.Uri; import android.text.TextUtils; import android.util.Log; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.FrameLayout.LayoutParams; import android.widget.ImageView; import androidx.annotation.NonNull; import com.bytedance.sdk.openadsdk.AdSlot; import com.bytedance.sdk.openadsdk.TTAdConstant; import com.bytedance.sdk.openadsdk.TTAdManager; import com.bytedance.sdk.openadsdk.TTAdNative; import com.bytedance.sdk.openadsdk.TTFeedAd; import com.bytedance.sdk.openadsdk.TTImage; import com.bytedance.sdk.openadsdk.TTNativeAd; import com.bytedance.sdk.openadsdk.adapter.MediaView; import com.bytedance.sdk.openadsdk.adapter.MediationAdapterUtil; import com.google.ads.mediation.pangle.PangleConstants; import com.google.ads.mediation.pangle.PangleMediationAdapter; import com.google.android.gms.ads.AdError; import com.google.android.gms.ads.formats.NativeAd.Image; import com.google.android.gms.ads.mediation.MediationAdLoadCallback; import com.google.android.gms.ads.mediation.MediationNativeAdCallback; import com.google.android.gms.ads.mediation.MediationNativeAdConfiguration; import com.google.android.gms.ads.mediation.UnifiedNativeAdMapper; import com.google.android.gms.ads.nativead.NativeAdAssetNames; import com.google.android.gms.ads.nativead.NativeAdOptions; import java.util.ArrayList; import java.util.List; import java.util.Map; public class PangleRtbNativeAd extends UnifiedNativeAdMapper { private static final double PANGLE_SDK_IMAGE_SCALE = 1.0; private final MediationNativeAdConfiguration adConfiguration; private final MediationAdLoadCallback<UnifiedNativeAdMapper, MediationNativeAdCallback> adLoadCallback; private MediationNativeAdCallback callback; private TTFeedAd ttFeedAd; public PangleRtbNativeAd(@NonNull MediationNativeAdConfiguration mediationNativeAdConfiguration, @NonNull MediationAdLoadCallback<UnifiedNativeAdMapper, MediationNativeAdCallback> mediationAdLoadCallback) { adConfiguration = mediationNativeAdConfiguration; adLoadCallback = mediationAdLoadCallback; } public void render() { PangleMediationAdapter.setCoppa(adConfiguration.taggedForChildDirectedTreatment()); String placementId = adConfiguration.getServerParameters() .getString(PangleConstants.PLACEMENT_ID); if (TextUtils.isEmpty(placementId)) { AdError error = PangleConstants.createAdapterError( ERROR_INVALID_SERVER_PARAMETERS, "Failed to load native ad from Pangle. Missing or invalid Placement ID."); Log.w(TAG, error.toString()); adLoadCallback.onFailure(error); return; } String bidResponse = adConfiguration.getBidResponse(); if (TextUtils.isEmpty(bidResponse)) { AdError error = PangleConstants.createAdapterError( ERROR_INVALID_BID_RESPONSE, "Failed to load native ad from Pangle. Missing or invalid bid response."); Log.w(TAG, error.toString()); adLoadCallback.onFailure(error); return; } TTAdManager mTTAdManager = PangleMediationAdapter.getPangleSdkManager(); TTAdNative mTTAdNative = mTTAdManager .createAdNative(adConfiguration.getContext().getApplicationContext()); AdSlot adSlot = new AdSlot.Builder() .setCodeId(placementId) .setAdCount(1) .withBid(bidResponse) .build(); mTTAdNative.loadFeedAd(adSlot, new TTAdNative.FeedAdListener() { @Override public void onError(int errorCode, String message) { AdError error = PangleConstants.createSdkError(errorCode, message); Log.w(TAG, error.toString()); adLoadCallback.onFailure(error); } @Override public void onFeedAdLoad(List<TTFeedAd> ads) { mapNativeAd(ads.get(0)); callback = adLoadCallback.onSuccess(PangleRtbNativeAd.this); } }); } private void mapNativeAd(TTFeedAd ad) { this.ttFeedAd = ad; // Set data. setHeadline(ttFeedAd.getTitle()); setBody(ttFeedAd.getDescription()); setCallToAction(ttFeedAd.getButtonText()); if (ttFeedAd.getIcon() != null && ttFeedAd.getIcon().isValid()) { setIcon(new PangleNativeMappedImage(null, Uri.parse(ttFeedAd.getIcon().getImageUrl()), PANGLE_SDK_IMAGE_SCALE)); } // Set ad image. if (ttFeedAd.getImageList() != null && ttFeedAd.getImageList().size() != 0) { List<Image> imagesList = new ArrayList<>(); for (TTImage ttImage : ttFeedAd.getImageList()) { if (ttImage.isValid()) { imagesList.add(new PangleNativeMappedImage(null, Uri.parse(ttImage.getImageUrl()), PANGLE_SDK_IMAGE_SCALE)); } } setImages(imagesList); } // Pangle does its own show event handling and click event handling. setOverrideImpressionRecording(true); setOverrideClickHandling(true); // Add Native Feed Main View. MediaView mediaView = new MediaView(adConfiguration.getContext()); MediationAdapterUtil .addNativeFeedMainView(adConfiguration.getContext(), ttFeedAd.getImageMode(), mediaView, ttFeedAd.getAdView(), ttFeedAd.getImageList()); setMediaView(mediaView); if (ttFeedAd.getImageMode() == TTAdConstant.IMAGE_MODE_VIDEO || ttFeedAd.getImageMode() == TTAdConstant.IMAGE_MODE_VIDEO_VERTICAL || ttFeedAd.getImageMode() == TTAdConstant.IMAGE_MODE_VIDEO_SQUARE) { setHasVideoContent(true); ttFeedAd.setVideoAdListener(new TTFeedAd.VideoAdListener() { @Override public void onVideoLoad(TTFeedAd ad) { // No-op, will be deprecated in the next version. } @Override public void onVideoError(int errorCode, int extraCode) { String errorMessage = String.format("Native ad video playback error," + " errorCode: %s, extraCode: %s.", errorCode, extraCode); Log.d(TAG, errorMessage); } @Override public void onVideoAdStartPlay(TTFeedAd ad) { // No-op, will be deprecated in the next version. } @Override public void onVideoAdPaused(TTFeedAd ad) { // No-op, will be deprecated in the next version. } @Override public void onVideoAdContinuePlay(TTFeedAd ad) { // No-op, will be deprecated in the next version. } @Override public void onProgressUpdate(long current, long duration) { // No-op, will be deprecated in the next version. } @Override public void onVideoAdComplete(TTFeedAd ad) { // No-op, will be deprecated in the next version. } }); } } @Override public void trackViews(@NonNull View containerView, @NonNull Map<String, View> clickableAssetViews, @NonNull Map<String, View> nonClickableAssetViews) { if (ttFeedAd == null) { return; } // Set click interaction. ArrayList<View> assetViews = new ArrayList<>(clickableAssetViews.values()); View creativeBtn = clickableAssetViews.get(NativeAdAssetNames.ASSET_CALL_TO_ACTION); ArrayList<View> creativeViews = new ArrayList<>(); if (creativeBtn != null) { creativeViews.add(creativeBtn); } ttFeedAd.registerViewForInteraction((ViewGroup) containerView, assetViews, creativeViews, new TTNativeAd.AdInteractionListener() { @Override public void onAdClicked(View view, TTNativeAd ad) { // No-op. } @Override public void onAdCreativeClick(View view, TTNativeAd ad) { if (callback != null) { callback.reportAdClicked(); } } @Override public void onAdShow(TTNativeAd ad) { if (callback != null) { callback.reportAdImpression(); } } }); // Set logo. NativeAdOptions nativeAdOptions = adConfiguration.getNativeAdOptions(); ViewGroup adView = (ViewGroup) containerView; View overlayView = adView.getChildAt(adView.getChildCount() - 1); if (overlayView instanceof FrameLayout) { int privacyIconPlacement = nativeAdOptions.getAdChoicesPlacement(); ImageView privacyInformationIconImageView = null; privacyInformationIconImageView = (ImageView) ttFeedAd.getAdLogoView(); if (privacyInformationIconImageView != null) { privacyInformationIconImageView.setVisibility(View.VISIBLE); ((ViewGroup) overlayView).addView(privacyInformationIconImageView); FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); switch (privacyIconPlacement) { case NativeAdOptions.ADCHOICES_TOP_LEFT: params.gravity = Gravity.TOP | Gravity.START; break; case NativeAdOptions.ADCHOICES_BOTTOM_RIGHT: params.gravity = Gravity.BOTTOM | Gravity.END; break; case NativeAdOptions.ADCHOICES_BOTTOM_LEFT: params.gravity = Gravity.BOTTOM | Gravity.START; break; case NativeAdOptions.ADCHOICES_TOP_RIGHT: params.gravity = Gravity.TOP | Gravity.END; break; default: params.gravity = Gravity.TOP | Gravity.END; } privacyInformationIconImageView.setLayoutParams(params); } adView.requestLayout(); } } public class PangleNativeMappedImage extends Image { private final Drawable drawable; private final Uri imageUri; private final double scale; private PangleNativeMappedImage(Drawable drawable, Uri imageUri, double scale) { this.drawable = drawable; this.imageUri = imageUri; this.scale = scale; } @NonNull @Override public Drawable getDrawable() { return drawable; } @NonNull @Override public Uri getUri() { return imageUri; } @Override public double getScale() { return scale; } } }
ThirdPartyAdapters/pangle/pangle/src/main/java/com/google/ads/mediation/pangle/rtb/PangleRtbNativeAd.java
package com.google.ads.mediation.pangle.rtb; import static com.google.ads.mediation.pangle.PangleConstants.ERROR_INVALID_BID_RESPONSE; import static com.google.ads.mediation.pangle.PangleConstants.ERROR_INVALID_SERVER_PARAMETERS; import static com.google.ads.mediation.pangle.PangleMediationAdapter.TAG; import android.graphics.drawable.Drawable; import android.net.Uri; import android.text.TextUtils; import android.util.Log; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.FrameLayout.LayoutParams; import android.widget.ImageView; import androidx.annotation.NonNull; import com.bytedance.sdk.openadsdk.AdSlot; import com.bytedance.sdk.openadsdk.TTAdConstant; import com.bytedance.sdk.openadsdk.TTAdManager; import com.bytedance.sdk.openadsdk.TTAdNative; import com.bytedance.sdk.openadsdk.TTFeedAd; import com.bytedance.sdk.openadsdk.TTImage; import com.bytedance.sdk.openadsdk.TTNativeAd; import com.bytedance.sdk.openadsdk.adapter.MediaView; import com.bytedance.sdk.openadsdk.adapter.MediationAdapterUtil; import com.google.ads.mediation.pangle.PangleConstants; import com.google.ads.mediation.pangle.PangleMediationAdapter; import com.google.android.gms.ads.AdError; import com.google.android.gms.ads.formats.NativeAd.Image; import com.google.android.gms.ads.mediation.MediationAdLoadCallback; import com.google.android.gms.ads.mediation.MediationNativeAdCallback; import com.google.android.gms.ads.mediation.MediationNativeAdConfiguration; import com.google.android.gms.ads.mediation.UnifiedNativeAdMapper; import com.google.android.gms.ads.nativead.NativeAdAssetNames; import com.google.android.gms.ads.nativead.NativeAdOptions; import java.util.ArrayList; import java.util.List; import java.util.Map; public class PangleRtbNativeAd extends UnifiedNativeAdMapper { private static final double PANGLE_SDK_IMAGE_SCALE = 1.0; private final MediationNativeAdConfiguration adConfiguration; private final MediationAdLoadCallback<UnifiedNativeAdMapper, MediationNativeAdCallback> adLoadCallback; private MediationNativeAdCallback callback; private TTFeedAd ttFeedAd; public PangleRtbNativeAd(@NonNull MediationNativeAdConfiguration mediationNativeAdConfiguration, @NonNull MediationAdLoadCallback<UnifiedNativeAdMapper, MediationNativeAdCallback> mediationAdLoadCallback) { adConfiguration = mediationNativeAdConfiguration; adLoadCallback = mediationAdLoadCallback; } public void render() { PangleMediationAdapter.setCoppa(adConfiguration.taggedForChildDirectedTreatment()); String placementId = adConfiguration.getServerParameters() .getString(PangleConstants.PLACEMENT_ID); if (TextUtils.isEmpty(placementId)) { AdError error = PangleConstants.createAdapterError( ERROR_INVALID_SERVER_PARAMETERS, "Failed to load native ad from Pangle. Missing or invalid Placement ID."); Log.w(TAG, error.toString()); adLoadCallback.onFailure(error); return; } String bidResponse = adConfiguration.getBidResponse(); if (TextUtils.isEmpty(bidResponse)) { AdError error = PangleConstants.createAdapterError( ERROR_INVALID_BID_RESPONSE, "Failed to load native ad from Pangle. Missing or invalid bid response."); Log.w(TAG, error.toString()); adLoadCallback.onFailure(error); return; } TTAdManager mTTAdManager = PangleMediationAdapter.getPangleSdkManager(); TTAdNative mTTAdNative = mTTAdManager .createAdNative(adConfiguration.getContext().getApplicationContext()); AdSlot adSlot = new AdSlot.Builder() .setCodeId(placementId) .setAdCount(1) .withBid(bidResponse) .build(); mTTAdNative.loadFeedAd(adSlot, new TTAdNative.FeedAdListener() { @Override public void onError(int errorCode, String message) { AdError error = PangleConstants.createSdkError(errorCode, message); Log.w(TAG, error.toString()); adLoadCallback.onFailure(error); } @Override public void onFeedAdLoad(List<TTFeedAd> ads) { mapNativeAd(ads.get(0)); callback = adLoadCallback.onSuccess(PangleRtbNativeAd.this); } }); } private void mapNativeAd(TTFeedAd ad) { this.ttFeedAd = ad; // Set data. setHeadline(ttFeedAd.getTitle()); setBody(ttFeedAd.getDescription()); setCallToAction(ttFeedAd.getButtonText()); if (ttFeedAd.getIcon() != null && ttFeedAd.getIcon().isValid()) { setIcon(new PangleNativeMappedImage(null, Uri.parse(ttFeedAd.getIcon().getImageUrl()), PANGLE_SDK_IMAGE_SCALE)); } // Set ad image. if (ttFeedAd.getImageList() != null && ttFeedAd.getImageList().size() != 0) { List<Image> imagesList = new ArrayList<>(); for (TTImage ttImage : ttFeedAd.getImageList()) { if (ttImage.isValid()) { imagesList.add(new PangleNativeMappedImage(null, Uri.parse(ttImage.getImageUrl()), PANGLE_SDK_IMAGE_SCALE)); } } setImages(imagesList); } // Pangle does its own show event handling and click event handling. setOverrideImpressionRecording(true); setOverrideClickHandling(true); // Add Native Feed Main View. MediaView mediaView = new MediaView(adConfiguration.getContext()); MediationAdapterUtil .addNativeFeedMainView(adConfiguration.getContext(), ttFeedAd.getImageMode(), mediaView, ttFeedAd.getAdView(), ttFeedAd.getImageList()); setMediaView(mediaView); if (ttFeedAd.getImageMode() == TTAdConstant.IMAGE_MODE_VIDEO || ttFeedAd.getImageMode() == TTAdConstant.IMAGE_MODE_VIDEO_VERTICAL || ttFeedAd.getImageMode() == TTAdConstant.IMAGE_MODE_VIDEO_SQUARE) { setHasVideoContent(true); ttFeedAd.setVideoAdListener(new TTFeedAd.VideoAdListener() { @Override public void onVideoLoad(TTFeedAd ad) { // No-op, will be deprecated in the next version. } @Override public void onVideoError(int errorCode, int extraCode) { String errorMessage = String.format("Native ad video playback error," + " errorCode: %s, extraCode: %s.", errorCode, extraCode); Log.d(TAG, errorMessage); } @Override public void onVideoAdStartPlay(TTFeedAd ad) { // No-op, will be deprecated in the next version. } @Override public void onVideoAdPaused(TTFeedAd ad) { // No-op, will be deprecated in the next version. } @Override public void onVideoAdContinuePlay(TTFeedAd ad) { // No-op, will be deprecated in the next version. } @Override public void onProgressUpdate(long current, long duration) { // No-op, will be deprecated in the next version. } @Override public void onVideoAdComplete(TTFeedAd ad) { // No-op, will be deprecated in the next version. } }); } } @Override public void trackViews(@NonNull View containerView, @NonNull Map<String, View> clickableAssetViews, @NonNull Map<String, View> nonClickableAssetViews) { if (ttFeedAd == null) { return; } // Set click interaction. ArrayList<View> assetViews = new ArrayList<>(clickableAssetViews.values()); View creativeBtn = clickableAssetViews.get(NativeAdAssetNames.ASSET_CALL_TO_ACTION); ArrayList<View> creativeViews = new ArrayList<>(); if (creativeBtn != null) { creativeViews.add(creativeBtn); } ttFeedAd.registerViewForInteraction((ViewGroup) containerView, assetViews, creativeViews, new TTNativeAd.AdInteractionListener() { @Override public void onAdClicked(View view, TTNativeAd ad) { } @Override public void onAdCreativeClick(View view, TTNativeAd ad) { if (callback != null) { callback.reportAdClicked(); } } @Override public void onAdShow(TTNativeAd ad) { if (callback != null) { callback.reportAdImpression(); } } }); // Set logo. NativeAdOptions nativeAdOptions = adConfiguration.getNativeAdOptions(); ViewGroup adView = (ViewGroup) containerView; View overlayView = adView.getChildAt(adView.getChildCount() - 1); if (overlayView instanceof FrameLayout) { int privacyIconPlacement = nativeAdOptions.getAdChoicesPlacement(); ImageView privacyInformationIconImageView = null; privacyInformationIconImageView = (ImageView) ttFeedAd.getAdLogoView(); if (privacyInformationIconImageView != null) { privacyInformationIconImageView.setVisibility(View.VISIBLE); ((ViewGroup) overlayView).addView(privacyInformationIconImageView); FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); switch (privacyIconPlacement) { case NativeAdOptions.ADCHOICES_TOP_LEFT: params.gravity = Gravity.TOP | Gravity.START; break; case NativeAdOptions.ADCHOICES_BOTTOM_RIGHT: params.gravity = Gravity.BOTTOM | Gravity.END; break; case NativeAdOptions.ADCHOICES_BOTTOM_LEFT: params.gravity = Gravity.BOTTOM | Gravity.START; break; case NativeAdOptions.ADCHOICES_TOP_RIGHT: params.gravity = Gravity.TOP | Gravity.END; break; default: params.gravity = Gravity.TOP | Gravity.END; } privacyInformationIconImageView.setLayoutParams(params); } adView.requestLayout(); } } public class PangleNativeMappedImage extends Image { private final Drawable drawable; private final Uri imageUri; private final double scale; private PangleNativeMappedImage(Drawable drawable, Uri imageUri, double scale) { this.drawable = drawable; this.imageUri = imageUri; this.scale = scale; } @NonNull @Override public Drawable getDrawable() { return drawable; } @NonNull @Override public Uri getUri() { return imageUri; } @Override public double getScale() { return scale; } } }
[fix]Optimize comments
ThirdPartyAdapters/pangle/pangle/src/main/java/com/google/ads/mediation/pangle/rtb/PangleRtbNativeAd.java
[fix]Optimize comments
Java
apache-2.0
000026350b21756c1dceba100a4b94c375a6fadc
0
bgroenks96/libgdx,Arcnor/libgdx,sarkanyi/libgdx,ninoalma/libgdx,BlueRiverInteractive/libgdx,nave966/libgdx,JFixby/libgdx,bladecoder/libgdx,kagehak/libgdx,PedroRomanoBarbosa/libgdx,lordjone/libgdx,del-sol/libgdx,BlueRiverInteractive/libgdx,309746069/libgdx,anserran/libgdx,gouessej/libgdx,bladecoder/libgdx,jsjolund/libgdx,TheAks999/libgdx,shiweihappy/libgdx,KrisLee/libgdx,Zonglin-Li6565/libgdx,tell10glu/libgdx,MadcowD/libgdx,fwolff/libgdx,designcrumble/libgdx,MadcowD/libgdx,Deftwun/libgdx,PedroRomanoBarbosa/libgdx,collinsmith/libgdx,copystudy/libgdx,UnluckyNinja/libgdx,gdos/libgdx,nave966/libgdx,JDReutt/libgdx,nrallakis/libgdx,nudelchef/libgdx,bsmr-java/libgdx,andyvand/libgdx,kotcrab/libgdx,firefly2442/libgdx,czyzby/libgdx,nudelchef/libgdx,JDReutt/libgdx,JDReutt/libgdx,toa5/libgdx,ninoalma/libgdx,katiepino/libgdx,codepoke/libgdx,ricardorigodon/libgdx,collinsmith/libgdx,toloudis/libgdx,ya7lelkom/libgdx,snovak/libgdx,luischavez/libgdx,czyzby/libgdx,davebaol/libgdx,stickyd/libgdx,kzganesan/libgdx,jsjolund/libgdx,Dzamir/libgdx,Xhanim/libgdx,kzganesan/libgdx,kotcrab/libgdx,js78/libgdx,nave966/libgdx,MovingBlocks/libgdx,mumer92/libgdx,katiepino/libgdx,GreenLightning/libgdx,xpenatan/libgdx-LWJGL3,Heart2009/libgdx,GreenLightning/libgdx,alex-dorokhov/libgdx,yangweigbh/libgdx,czyzby/libgdx,snovak/libgdx,toa5/libgdx,JDReutt/libgdx,NathanSweet/libgdx,JFixby/libgdx,sinistersnare/libgdx,saltares/libgdx,flaiker/libgdx,BlueRiverInteractive/libgdx,Badazdz/libgdx,kagehak/libgdx,katiepino/libgdx,Arcnor/libgdx,sjosegarcia/libgdx,realitix/libgdx,djom20/libgdx,tell10glu/libgdx,djom20/libgdx,xpenatan/libgdx-LWJGL3,nooone/libgdx,hyvas/libgdx,basherone/libgdxcn,libgdx/libgdx,EsikAntony/libgdx,ya7lelkom/libgdx,djom20/libgdx,toloudis/libgdx,shiweihappy/libgdx,zhimaijoy/libgdx,SidneyXu/libgdx,lordjone/libgdx,FredGithub/libgdx,xpenatan/libgdx-LWJGL3,saltares/libgdx,nooone/libgdx,Zonglin-Li6565/libgdx,tommycli/libgdx,Deftwun/libgdx,sarkanyi/libgdx,Senth/libgdx,firefly2442/libgdx,MadcowD/libgdx,toloudis/libgdx,curtiszimmerman/libgdx,azakhary/libgdx,Zomby2D/libgdx,EsikAntony/libgdx,stickyd/libgdx,KrisLee/libgdx,saltares/libgdx,ya7lelkom/libgdx,GreenLightning/libgdx,jsjolund/libgdx,nelsonsilva/libgdx,xoppa/libgdx,Heart2009/libgdx,designcrumble/libgdx,EsikAntony/libgdx,josephknight/libgdx,bgroenks96/libgdx,Wisienkas/libgdx,zhimaijoy/libgdx,jberberick/libgdx,SidneyXu/libgdx,saqsun/libgdx,TheAks999/libgdx,MikkelTAndersen/libgdx,Gliby/libgdx,FredGithub/libgdx,Thotep/libgdx,hyvas/libgdx,libgdx/libgdx,revo09/libgdx,nrallakis/libgdx,srwonka/libGdx,Gliby/libgdx,Zonglin-Li6565/libgdx,alex-dorokhov/libgdx,stickyd/libgdx,thepullman/libgdx,hyvas/libgdx,nrallakis/libgdx,bladecoder/libgdx,FyiurAmron/libgdx,saqsun/libgdx,lordjone/libgdx,revo09/libgdx,anserran/libgdx,Xhanim/libgdx,samskivert/libgdx,Gliby/libgdx,youprofit/libgdx,yangweigbh/libgdx,copystudy/libgdx,KrisLee/libgdx,Thotep/libgdx,josephknight/libgdx,Heart2009/libgdx,1yvT0s/libgdx,gf11speed/libgdx,toa5/libgdx,ThiagoGarciaAlves/libgdx,lordjone/libgdx,alireza-hosseini/libgdx,snovak/libgdx,Heart2009/libgdx,shiweihappy/libgdx,toa5/libgdx,TheAks999/libgdx,UnluckyNinja/libgdx,cypherdare/libgdx,kzganesan/libgdx,MikkelTAndersen/libgdx,toloudis/libgdx,MovingBlocks/libgdx,gouessej/libgdx,mumer92/libgdx,shiweihappy/libgdx,nave966/libgdx,js78/libgdx,sjosegarcia/libgdx,hyvas/libgdx,sjosegarcia/libgdx,srwonka/libGdx,bladecoder/libgdx,ryoenji/libgdx,Gliby/libgdx,noelsison2/libgdx,fwolff/libgdx,jasonwee/libgdx,del-sol/libgdx,luischavez/libgdx,mumer92/libgdx,309746069/libgdx,nudelchef/libgdx,tommyettinger/libgdx,zhimaijoy/libgdx,copystudy/libgdx,ztv/libgdx,billgame/libgdx,ttencate/libgdx,snovak/libgdx,xoppa/libgdx,bsmr-java/libgdx,jsjolund/libgdx,djom20/libgdx,jberberick/libgdx,antag99/libgdx,ztv/libgdx,gdos/libgdx,nooone/libgdx,titovmaxim/libgdx,libgdx/libgdx,TheAks999/libgdx,del-sol/libgdx,MathieuDuponchelle/gdx,billgame/libgdx,Xhanim/libgdx,xpenatan/libgdx-LWJGL3,ricardorigodon/libgdx,FyiurAmron/libgdx,czyzby/libgdx,samskivert/libgdx,junkdog/libgdx,revo09/libgdx,stinsonga/libgdx,gdos/libgdx,noelsison2/libgdx,MathieuDuponchelle/gdx,hyvas/libgdx,junkdog/libgdx,realitix/libgdx,nrallakis/libgdx,fiesensee/libgdx,firefly2442/libgdx,bsmr-java/libgdx,firefly2442/libgdx,309746069/libgdx,Wisienkas/libgdx,tell10glu/libgdx,FredGithub/libgdx,azakhary/libgdx,tommyettinger/libgdx,gouessej/libgdx,billgame/libgdx,realitix/libgdx,SidneyXu/libgdx,alireza-hosseini/libgdx,designcrumble/libgdx,alex-dorokhov/libgdx,Dzamir/libgdx,jasonwee/libgdx,jsjolund/libgdx,luischavez/libgdx,andyvand/libgdx,davebaol/libgdx,zommuter/libgdx,Xhanim/libgdx,sarkanyi/libgdx,thepullman/libgdx,Gliby/libgdx,zhimaijoy/libgdx,revo09/libgdx,MathieuDuponchelle/gdx,haedri/libgdx-1,Arcnor/libgdx,Dzamir/libgdx,ttencate/libgdx,EsikAntony/libgdx,zommuter/libgdx,andyvand/libgdx,curtiszimmerman/libgdx,ttencate/libgdx,xranby/libgdx,bgroenks96/libgdx,curtiszimmerman/libgdx,ryoenji/libgdx,Deftwun/libgdx,anserran/libgdx,alireza-hosseini/libgdx,1yvT0s/libgdx,lordjone/libgdx,jasonwee/libgdx,FyiurAmron/libgdx,toa5/libgdx,katiepino/libgdx,hyvas/libgdx,samskivert/libgdx,309746069/libgdx,zommuter/libgdx,PedroRomanoBarbosa/libgdx,flaiker/libgdx,titovmaxim/libgdx,cypherdare/libgdx,zhimaijoy/libgdx,Zonglin-Li6565/libgdx,nrallakis/libgdx,kagehak/libgdx,samskivert/libgdx,nave966/libgdx,toloudis/libgdx,saltares/libgdx,Dzamir/libgdx,ztv/libgdx,xranby/libgdx,antag99/libgdx,curtiszimmerman/libgdx,Wisienkas/libgdx,ryoenji/libgdx,xpenatan/libgdx-LWJGL3,nudelchef/libgdx,sarkanyi/libgdx,xpenatan/libgdx-LWJGL3,MetSystem/libgdx,MathieuDuponchelle/gdx,Dzamir/libgdx,jberberick/libgdx,SidneyXu/libgdx,codepoke/libgdx,petugez/libgdx,mumer92/libgdx,ninoalma/libgdx,flaiker/libgdx,haedri/libgdx-1,BlueRiverInteractive/libgdx,kagehak/libgdx,Zomby2D/libgdx,ya7lelkom/libgdx,del-sol/libgdx,zhimaijoy/libgdx,antag99/libgdx,Senth/libgdx,luischavez/libgdx,JDReutt/libgdx,ThiagoGarciaAlves/libgdx,jsjolund/libgdx,TheAks999/libgdx,Zomby2D/libgdx,nudelchef/libgdx,GreenLightning/libgdx,andyvand/libgdx,gf11speed/libgdx,codepoke/libgdx,ztv/libgdx,cypherdare/libgdx,ThiagoGarciaAlves/libgdx,bgroenks96/libgdx,Wisienkas/libgdx,noelsison2/libgdx,xranby/libgdx,thepullman/libgdx,basherone/libgdxcn,revo09/libgdx,ryoenji/libgdx,titovmaxim/libgdx,ya7lelkom/libgdx,MetSystem/libgdx,MetSystem/libgdx,MadcowD/libgdx,Wisienkas/libgdx,firefly2442/libgdx,gdos/libgdx,UnluckyNinja/libgdx,anserran/libgdx,junkdog/libgdx,copystudy/libgdx,katiepino/libgdx,tommyettinger/libgdx,basherone/libgdxcn,toa5/libgdx,Thotep/libgdx,jasonwee/libgdx,sarkanyi/libgdx,GreenLightning/libgdx,PedroRomanoBarbosa/libgdx,titovmaxim/libgdx,srwonka/libGdx,JFixby/libgdx,Badazdz/libgdx,GreenLightning/libgdx,realitix/libgdx,UnluckyNinja/libgdx,copystudy/libgdx,anserran/libgdx,BlueRiverInteractive/libgdx,ya7lelkom/libgdx,toa5/libgdx,MovingBlocks/libgdx,MovingBlocks/libgdx,NathanSweet/libgdx,gouessej/libgdx,nrallakis/libgdx,MadcowD/libgdx,fwolff/libgdx,sinistersnare/libgdx,ztv/libgdx,tommycli/libgdx,zommuter/libgdx,GreenLightning/libgdx,kotcrab/libgdx,xpenatan/libgdx-LWJGL3,Zomby2D/libgdx,kotcrab/libgdx,stickyd/libgdx,Thotep/libgdx,lordjone/libgdx,sjosegarcia/libgdx,JFixby/libgdx,gdos/libgdx,kotcrab/libgdx,yangweigbh/libgdx,Deftwun/libgdx,Gliby/libgdx,Dzamir/libgdx,Xhanim/libgdx,ThiagoGarciaAlves/libgdx,jberberick/libgdx,nrallakis/libgdx,haedri/libgdx-1,nooone/libgdx,JFixby/libgdx,tommycli/libgdx,tommyettinger/libgdx,ttencate/libgdx,fiesensee/libgdx,Deftwun/libgdx,sarkanyi/libgdx,firefly2442/libgdx,jasonwee/libgdx,srwonka/libGdx,zommuter/libgdx,MadcowD/libgdx,srwonka/libGdx,jsjolund/libgdx,nave966/libgdx,curtiszimmerman/libgdx,yangweigbh/libgdx,nooone/libgdx,MikkelTAndersen/libgdx,fwolff/libgdx,tell10glu/libgdx,Zonglin-Li6565/libgdx,Senth/libgdx,gouessej/libgdx,ninoalma/libgdx,alex-dorokhov/libgdx,Wisienkas/libgdx,collinsmith/libgdx,del-sol/libgdx,toloudis/libgdx,andyvand/libgdx,sarkanyi/libgdx,xpenatan/libgdx-LWJGL3,1yvT0s/libgdx,del-sol/libgdx,nave966/libgdx,yangweigbh/libgdx,js78/libgdx,KrisLee/libgdx,NathanSweet/libgdx,petugez/libgdx,josephknight/libgdx,azakhary/libgdx,jberberick/libgdx,kotcrab/libgdx,fwolff/libgdx,azakhary/libgdx,kotcrab/libgdx,js78/libgdx,hyvas/libgdx,codepoke/libgdx,saqsun/libgdx,youprofit/libgdx,czyzby/libgdx,309746069/libgdx,Deftwun/libgdx,Badazdz/libgdx,MovingBlocks/libgdx,FyiurAmron/libgdx,codepoke/libgdx,josephknight/libgdx,josephknight/libgdx,fiesensee/libgdx,nelsonsilva/libgdx,anserran/libgdx,alex-dorokhov/libgdx,petugez/libgdx,fiesensee/libgdx,zhimaijoy/libgdx,revo09/libgdx,snovak/libgdx,toloudis/libgdx,ttencate/libgdx,FredGithub/libgdx,copystudy/libgdx,stinsonga/libgdx,BlueRiverInteractive/libgdx,srwonka/libGdx,petugez/libgdx,srwonka/libGdx,UnluckyNinja/libgdx,toloudis/libgdx,bgroenks96/libgdx,billgame/libgdx,ninoalma/libgdx,titovmaxim/libgdx,jberberick/libgdx,basherone/libgdxcn,junkdog/libgdx,ryoenji/libgdx,MikkelTAndersen/libgdx,bgroenks96/libgdx,collinsmith/libgdx,309746069/libgdx,antag99/libgdx,SidneyXu/libgdx,Dzamir/libgdx,czyzby/libgdx,josephknight/libgdx,ryoenji/libgdx,youprofit/libgdx,andyvand/libgdx,sjosegarcia/libgdx,js78/libgdx,ya7lelkom/libgdx,alex-dorokhov/libgdx,ricardorigodon/libgdx,curtiszimmerman/libgdx,saltares/libgdx,Arcnor/libgdx,basherone/libgdxcn,ThiagoGarciaAlves/libgdx,libgdx/libgdx,js78/libgdx,collinsmith/libgdx,Gliby/libgdx,1yvT0s/libgdx,srwonka/libGdx,UnluckyNinja/libgdx,curtiszimmerman/libgdx,flaiker/libgdx,copystudy/libgdx,nelsonsilva/libgdx,xoppa/libgdx,haedri/libgdx-1,gouessej/libgdx,ztv/libgdx,fiesensee/libgdx,junkdog/libgdx,tommycli/libgdx,Senth/libgdx,nelsonsilva/libgdx,Heart2009/libgdx,azakhary/libgdx,alireza-hosseini/libgdx,junkdog/libgdx,alex-dorokhov/libgdx,realitix/libgdx,antag99/libgdx,stickyd/libgdx,davebaol/libgdx,ninoalma/libgdx,tell10glu/libgdx,yangweigbh/libgdx,FredGithub/libgdx,nudelchef/libgdx,ryoenji/libgdx,EsikAntony/libgdx,fwolff/libgdx,firefly2442/libgdx,fwolff/libgdx,xranby/libgdx,PedroRomanoBarbosa/libgdx,Senth/libgdx,samskivert/libgdx,saqsun/libgdx,gdos/libgdx,del-sol/libgdx,hyvas/libgdx,sjosegarcia/libgdx,snovak/libgdx,TheAks999/libgdx,bladecoder/libgdx,toa5/libgdx,EsikAntony/libgdx,Thotep/libgdx,petugez/libgdx,djom20/libgdx,Badazdz/libgdx,xoppa/libgdx,kzganesan/libgdx,MovingBlocks/libgdx,cypherdare/libgdx,Xhanim/libgdx,MikkelTAndersen/libgdx,basherone/libgdxcn,gf11speed/libgdx,designcrumble/libgdx,gf11speed/libgdx,andyvand/libgdx,MathieuDuponchelle/gdx,saqsun/libgdx,kzganesan/libgdx,MathieuDuponchelle/gdx,billgame/libgdx,Arcnor/libgdx,tommycli/libgdx,kagehak/libgdx,saqsun/libgdx,haedri/libgdx-1,JDReutt/libgdx,ThiagoGarciaAlves/libgdx,ztv/libgdx,flaiker/libgdx,kagehak/libgdx,PedroRomanoBarbosa/libgdx,MathieuDuponchelle/gdx,xoppa/libgdx,stickyd/libgdx,bsmr-java/libgdx,collinsmith/libgdx,JFixby/libgdx,Deftwun/libgdx,Senth/libgdx,MetSystem/libgdx,FyiurAmron/libgdx,mumer92/libgdx,MikkelTAndersen/libgdx,zhimaijoy/libgdx,noelsison2/libgdx,curtiszimmerman/libgdx,SidneyXu/libgdx,xoppa/libgdx,alex-dorokhov/libgdx,ya7lelkom/libgdx,NathanSweet/libgdx,nelsonsilva/libgdx,tommycli/libgdx,nudelchef/libgdx,ThiagoGarciaAlves/libgdx,gf11speed/libgdx,titovmaxim/libgdx,saqsun/libgdx,gdos/libgdx,flaiker/libgdx,SidneyXu/libgdx,ricardorigodon/libgdx,fwolff/libgdx,nelsonsilva/libgdx,MovingBlocks/libgdx,Thotep/libgdx,xoppa/libgdx,tell10glu/libgdx,antag99/libgdx,1yvT0s/libgdx,realitix/libgdx,youprofit/libgdx,lordjone/libgdx,samskivert/libgdx,czyzby/libgdx,saltares/libgdx,anserran/libgdx,FyiurAmron/libgdx,KrisLee/libgdx,ThiagoGarciaAlves/libgdx,thepullman/libgdx,designcrumble/libgdx,zommuter/libgdx,stinsonga/libgdx,flaiker/libgdx,xranby/libgdx,revo09/libgdx,UnluckyNinja/libgdx,stinsonga/libgdx,czyzby/libgdx,revo09/libgdx,katiepino/libgdx,alireza-hosseini/libgdx,luischavez/libgdx,ttencate/libgdx,JFixby/libgdx,samskivert/libgdx,djom20/libgdx,Senth/libgdx,MathieuDuponchelle/gdx,andyvand/libgdx,josephknight/libgdx,junkdog/libgdx,noelsison2/libgdx,saltares/libgdx,Zonglin-Li6565/libgdx,shiweihappy/libgdx,JDReutt/libgdx,del-sol/libgdx,jberberick/libgdx,noelsison2/libgdx,titovmaxim/libgdx,alireza-hosseini/libgdx,tommyettinger/libgdx,djom20/libgdx,JDReutt/libgdx,kagehak/libgdx,Badazdz/libgdx,Zomby2D/libgdx,luischavez/libgdx,katiepino/libgdx,jasonwee/libgdx,petugez/libgdx,libgdx/libgdx,SidneyXu/libgdx,tommycli/libgdx,stinsonga/libgdx,MetSystem/libgdx,samskivert/libgdx,Heart2009/libgdx,billgame/libgdx,xranby/libgdx,sinistersnare/libgdx,antag99/libgdx,ttencate/libgdx,MovingBlocks/libgdx,MetSystem/libgdx,nave966/libgdx,kzganesan/libgdx,KrisLee/libgdx,stickyd/libgdx,nooone/libgdx,BlueRiverInteractive/libgdx,js78/libgdx,youprofit/libgdx,1yvT0s/libgdx,luischavez/libgdx,haedri/libgdx-1,Wisienkas/libgdx,js78/libgdx,jsjolund/libgdx,MadcowD/libgdx,Xhanim/libgdx,BlueRiverInteractive/libgdx,billgame/libgdx,sinistersnare/libgdx,davebaol/libgdx,thepullman/libgdx,ninoalma/libgdx,firefly2442/libgdx,youprofit/libgdx,snovak/libgdx,Zonglin-Li6565/libgdx,zommuter/libgdx,ricardorigodon/libgdx,1yvT0s/libgdx,KrisLee/libgdx,codepoke/libgdx,xranby/libgdx,ttencate/libgdx,fiesensee/libgdx,gdos/libgdx,sjosegarcia/libgdx,MetSystem/libgdx,copystudy/libgdx,PedroRomanoBarbosa/libgdx,alireza-hosseini/libgdx,bgroenks96/libgdx,TheAks999/libgdx,xranby/libgdx,gouessej/libgdx,ricardorigodon/libgdx,gf11speed/libgdx,nudelchef/libgdx,codepoke/libgdx,bsmr-java/libgdx,alireza-hosseini/libgdx,GreenLightning/libgdx,collinsmith/libgdx,noelsison2/libgdx,FredGithub/libgdx,bsmr-java/libgdx,xoppa/libgdx,KrisLee/libgdx,designcrumble/libgdx,MetSystem/libgdx,FredGithub/libgdx,Gliby/libgdx,josephknight/libgdx,anserran/libgdx,nrallakis/libgdx,NathanSweet/libgdx,haedri/libgdx-1,tell10glu/libgdx,Xhanim/libgdx,thepullman/libgdx,Zonglin-Li6565/libgdx,billgame/libgdx,ricardorigodon/libgdx,realitix/libgdx,flaiker/libgdx,designcrumble/libgdx,ztv/libgdx,ricardorigodon/libgdx,Badazdz/libgdx,Deftwun/libgdx,thepullman/libgdx,youprofit/libgdx,gf11speed/libgdx,mumer92/libgdx,saltares/libgdx,jasonwee/libgdx,bgroenks96/libgdx,zommuter/libgdx,Wisienkas/libgdx,kotcrab/libgdx,Badazdz/libgdx,petugez/libgdx,sarkanyi/libgdx,shiweihappy/libgdx,kagehak/libgdx,PedroRomanoBarbosa/libgdx,codepoke/libgdx,luischavez/libgdx,MikkelTAndersen/libgdx,MathieuDuponchelle/gdx,fiesensee/libgdx,JFixby/libgdx,sinistersnare/libgdx,katiepino/libgdx,gouessej/libgdx,saqsun/libgdx,davebaol/libgdx,Thotep/libgdx,Heart2009/libgdx,yangweigbh/libgdx,haedri/libgdx-1,junkdog/libgdx,FyiurAmron/libgdx,gf11speed/libgdx,kzganesan/libgdx,tommycli/libgdx,TheAks999/libgdx,FyiurAmron/libgdx,Dzamir/libgdx,Arcnor/libgdx,bsmr-java/libgdx,mumer92/libgdx,jberberick/libgdx,youprofit/libgdx,yangweigbh/libgdx,309746069/libgdx,MikkelTAndersen/libgdx,davebaol/libgdx,thepullman/libgdx,MadcowD/libgdx,azakhary/libgdx,Senth/libgdx,sjosegarcia/libgdx,FredGithub/libgdx,Badazdz/libgdx,titovmaxim/libgdx,309746069/libgdx,jasonwee/libgdx,tell10glu/libgdx,stickyd/libgdx,cypherdare/libgdx,EsikAntony/libgdx,ninoalma/libgdx,1yvT0s/libgdx,mumer92/libgdx,Heart2009/libgdx,antag99/libgdx,snovak/libgdx,EsikAntony/libgdx,collinsmith/libgdx,designcrumble/libgdx,Thotep/libgdx,lordjone/libgdx,petugez/libgdx,realitix/libgdx,shiweihappy/libgdx,fiesensee/libgdx,sinistersnare/libgdx,shiweihappy/libgdx,noelsison2/libgdx,djom20/libgdx,UnluckyNinja/libgdx,bsmr-java/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.assets; import java.util.ArrayList; import java.util.Stack; import com.badlogic.gdx.assets.loaders.AssetLoader; import com.badlogic.gdx.assets.loaders.BitmapFontLoader; import com.badlogic.gdx.assets.loaders.FileHandleResolver; import com.badlogic.gdx.assets.loaders.MusicLoader; import com.badlogic.gdx.assets.loaders.PixmapLoader; import com.badlogic.gdx.assets.loaders.SkinLoader; import com.badlogic.gdx.assets.loaders.SoundLoader; import com.badlogic.gdx.assets.loaders.TextureAtlasLoader; import com.badlogic.gdx.assets.loaders.TextureLoader; import com.badlogic.gdx.assets.loaders.resolvers.InternalFileHandleResolver; import com.badlogic.gdx.audio.Music; import com.badlogic.gdx.audio.Sound; import com.badlogic.gdx.graphics.Pixmap; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.TextureAtlas; import com.badlogic.gdx.scenes.scene2d.ui.Skin; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.Disposable; import com.badlogic.gdx.utils.GdxRuntimeException; import com.badlogic.gdx.utils.ObjectIntMap; import com.badlogic.gdx.utils.ObjectMap; public class AssetManager implements Disposable { final ObjectMap<Class, ObjectMap<String, RefCountedContainer>> assets = new ObjectMap<Class, ObjectMap<String, RefCountedContainer>>(); final ObjectMap<String, Class> assetTypes = new ObjectMap<String, Class>(); final ObjectMap<String, Array<String>> assetDependencies = new ObjectMap<String, Array<String>>(); final ObjectMap<Class, AssetLoader> loaders = new ObjectMap<Class, AssetLoader>(); final ArrayList<AssetDescriptor> loadQueue = new ArrayList<AssetDescriptor>(); Stack<AssetLoadingTask> tasks = new Stack<AssetLoadingTask>(); AssetErrorListener listener = null; int loaded = 0; int toLoad = 0; /** Creates a new AssetManager with all default loaders. */ public AssetManager () { this(new InternalFileHandleResolver()); } /** Creates a new AssetManager with all default loaders. */ public AssetManager (FileHandleResolver resolver) { setLoader(BitmapFont.class, new BitmapFontLoader(resolver)); setLoader(Music.class, new MusicLoader(resolver)); setLoader(Pixmap.class, new PixmapLoader(resolver)); setLoader(Sound.class, new SoundLoader(resolver)); setLoader(TextureAtlas.class, new TextureAtlasLoader(resolver)); setLoader(Texture.class, new TextureLoader(resolver)); setLoader(Skin.class, new SkinLoader(resolver)); // setLoader(TileMapRenderer.class, new TileMapRendererLoader(resolver)); } /** @param fileName the asset file name * @return the asset */ public synchronized <T> T get (String fileName) { Class<T> type = assetTypes.get(fileName); ObjectMap<String, RefCountedContainer> assetsByType = assets.get(type); if (assetsByType == null) throw new GdxRuntimeException("Asset not loaded: " + fileName); RefCountedContainer assetContainer = assetsByType.get(fileName); if (assetContainer == null) throw new GdxRuntimeException("Asset not loaded: " + fileName); T asset = assetContainer.getObject(type); if (asset == null) throw new GdxRuntimeException("Asset not loaded: " + fileName); return asset; } /** @param fileName the asset file name * @param type the asset type * @return the asset */ public synchronized <T> T get (String fileName, Class<T> type) { ObjectMap<String, RefCountedContainer> assetsByType = assets.get(type); if (assetsByType == null) throw new GdxRuntimeException("Asset not loaded: " + fileName); RefCountedContainer assetContainer = assetsByType.get(fileName); if (assetContainer == null) throw new GdxRuntimeException("Asset not loaded: " + fileName); T asset = assetContainer.getObject(type); if (asset == null) throw new GdxRuntimeException("Asset not loaded: " + fileName); return asset; } /** Removes the asset and all its dependencies if they are not used by other assets. * @param fileName the file name */ public synchronized void unload (String fileName) { // check if it's in the queue int foundIndex = -1; for (int i = 0; i < loadQueue.size(); i++) { if (loadQueue.get(i).fileName.equals(fileName)) { foundIndex = i; break; } } if (foundIndex != -1) { loadQueue.remove(foundIndex); // log.debug("Unload (from queue): " + fileName); return; } // check if it's currently processed (and the first element in the stack, thus not a dependency) // and cancel if necessary if (tasks.size() > 0) { AssetLoadingTask currAsset = tasks.firstElement(); if (currAsset.assetDesc.fileName.equals(fileName)) { currAsset.cancel = true; // log.debug("Unload (from tasks): " + fileName); return; } } // get the asset and its type Class type = assetTypes.get(fileName); if (type == null) throw new GdxRuntimeException("Asset not loaded: " + fileName); RefCountedContainer assetRef = assets.get(type).get(fileName); // if it is reference counted, decrement ref count and check if we can really get rid of it. assetRef.decRefCount(); if (assetRef.getRefCount() <= 0) { // log.debug("Unload (dispose): " + fileName); // if it is disposable dispose it if (assetRef.getObject(Object.class) instanceof Disposable) ((Disposable)assetRef.getObject(Object.class)).dispose(); // remove the asset from the manager. assetTypes.remove(fileName); assets.get(type).remove(fileName); } else { // log.debug("Unload (decrement): " + fileName); } // remove any dependencies (or just decrement their ref count). Array<String> dependencies = assetDependencies.get(fileName); if (dependencies != null) { for (String dependency : dependencies) { unload(dependency); } } // remove dependencies if ref count < 0 if (assetRef.getRefCount() <= 0) { assetDependencies.remove(fileName); } } /** @param asset the asset * @return whether the asset is contained in this manager */ public synchronized <T> boolean containsAsset (T asset) { ObjectMap<String, RefCountedContainer> typedAssets = assets.get(asset.getClass()); if (typedAssets == null) return false; for (String fileName : typedAssets.keys()) { T otherAsset = (T)typedAssets.get(fileName).getObject(Object.class); if (otherAsset == asset || asset.equals(otherAsset)) return true; } return false; } /** @param asset the asset * @return whether the filename of the asset or null */ public synchronized <T> String getAssetFileName (T asset) { for (Class assetType : assets.keys()) { ObjectMap<String, RefCountedContainer> typedAssets = assets.get(assetType); for (String fileName : typedAssets.keys()) { T otherAsset = (T)typedAssets.get(fileName).getObject(Object.class); if (otherAsset == asset || asset.equals(otherAsset)) return fileName; } } return null; } /** @param fileName the file name of the asset * @return whether the asset is loaded */ public synchronized boolean isLoaded (String fileName) { if (fileName == null) return false; return assetTypes.containsKey(fileName); } /** @param fileName the file name of the asset * @return whether the asset is loaded */ public synchronized boolean isLoaded (String fileName, Class type) { ObjectMap<String, RefCountedContainer> assetsByType = assets.get(type); if (assetsByType == null) return false; RefCountedContainer assetContainer = assetsByType.get(fileName); if (assetContainer == null) return false; return assetContainer.getObject(type) != null; } /** Adds the given asset to the loading queue of the AssetManager. * @param fileName the file name (interpretation depends on {@link AssetLoader}) * @param type the type of the asset. */ public synchronized <T> void load (String fileName, Class<T> type) { load(fileName, type, null); } /** Adds the given asset to the loading queue of the AssetManager. * @param fileName the file name (interpretation depends on {@link AssetLoader}) * @param type the type of the asset. * @param parameter parameters for the AssetLoader. */ public synchronized <T> void load (String fileName, Class<T> type, AssetLoaderParameters<T> parameter) { AssetLoader loader = loaders.get(type); if (loader == null) throw new GdxRuntimeException("No loader for type: " + type.getName()); if (loadQueue.size() == 0) { loaded = 0; toLoad = 0; } // check if an asset with the same name but a different type has already been added. // check preload queue for (int i = 0; i < loadQueue.size(); i++) { AssetDescriptor desc = loadQueue.get(i); if (desc.fileName.equals(fileName) && !desc.type.equals(type)) throw new GdxRuntimeException("Asset with name '" + fileName + "' already in preload queue, but has different type (expected: " + type.getName() + ", found: " + desc.type.getName()); } // check task list for (int i = 0; i < tasks.size(); i++) { AssetDescriptor desc = tasks.get(i).assetDesc; if (desc.fileName.equals(fileName) && !desc.type.equals(type)) throw new GdxRuntimeException("Asset with name '" + fileName + "' already in task list, but has different type (expected: " + type.getName() + ", found: " + desc.type.getName()); } // check loaded assets Class otherType = assetTypes.get(fileName); if (otherType != null && !otherType.equals(type)) throw new GdxRuntimeException("Asset with name '" + fileName + "' already loaded, but has different type (expected: " + type.getName() + ", found: " + otherType.getName()); toLoad++; AssetDescriptor assetDesc = new AssetDescriptor(fileName, type, parameter); loadQueue.add(assetDesc); // log.debug("Queued: " + assetDesc); } /** Adds the given asset to the loading queue of the AssetManager. * @param desc the {@link AssetDescriptor} */ public synchronized void load (AssetDescriptor desc) { load(desc.fileName, desc.type, desc.params); } /** Disposes the given asset and all its dependencies recursively, depth first. * @param fileName */ private void disposeDependencies (String fileName) { Array<String> dependencies = assetDependencies.get(fileName); if (dependencies != null) { for (String dependency : dependencies) { disposeDependencies(dependency); } } Class type = assetTypes.get(fileName); Object asset = assets.get(type).get(fileName).getObject(Object.class); if (asset instanceof Disposable) ((Disposable)asset).dispose(); } /** Updates the AssetManager, keeping it loading any assets in the preload queue. * @return true if all loading is finished. */ public synchronized boolean update () { try { if (tasks.size() == 0) { // loop until we have a new task ready to be processed while (loadQueue.size() != 0 && tasks.size() == 0) { nextTask(); } // have we not found a task? We are done! if (tasks.size() == 0) return true; } return updateTask() && loadQueue.size() == 0 && tasks.size() == 0; } catch (Throwable t) { handleTaskError(t); return loadQueue.size() == 0; } } // public void finishLoading () { // log.debug("Waiting for loading to complete..."); // while (!update()) // Thread.yield(); // log.debug("Loading complete."); // } synchronized void injectDependency (String parentAssetFilename, AssetDescriptor dependendAssetDesc) { // add the asset as a dependency of the parent asset Array<String> dependencies = assetDependencies.get(parentAssetFilename); if (dependencies == null) { dependencies = new Array<String>(); assetDependencies.put(parentAssetFilename, dependencies); } dependencies.add(dependendAssetDesc.fileName); // if the asset is already loaded, increase its reference count. if (isLoaded(dependendAssetDesc.fileName)) { // log.debug("Dependency already loaded: " + dependendAssetDesc); Class type = assetTypes.get(dependendAssetDesc.fileName); RefCountedContainer assetRef = assets.get(type).get(dependendAssetDesc.fileName); assetRef.incRefCount(); incrementRefCountedDependencies(dependendAssetDesc.fileName); } // else add a new task for the asset. else { // log.info("Loading dependency: " + dependendAssetDesc); addTask(dependendAssetDesc); } } /** Removes a task from the loadQueue and adds it to the task stack. If the asset is already loaded (which can happen if it was * a dependency of a previously loaded asset) its reference count will be increased. */ private void nextTask () { AssetDescriptor assetDesc = loadQueue.remove(0); // if the asset not meant to be reloaded and is already loaded, increase its reference count if (isLoaded(assetDesc.fileName)) { // log.debug("Already loaded: " + assetDesc); Class type = assetTypes.get(assetDesc.fileName); RefCountedContainer assetRef = assets.get(type).get(assetDesc.fileName); assetRef.incRefCount(); incrementRefCountedDependencies(assetDesc.fileName); loaded++; } else { // else add a new task for the asset. // log.info("Loading: " + assetDesc); addTask(assetDesc); } } /** Adds a {@link AssetLoadingTask} to the task stack for the given asset. * @param assetDesc */ private void addTask (AssetDescriptor assetDesc) { AssetLoader loader = loaders.get(assetDesc.type); if (loader == null) throw new GdxRuntimeException("No loader for type: " + assetDesc.type.getName()); tasks.push(new AssetLoadingTask(this, assetDesc, loader)); } /** Adds an asset to this AssetManager */ protected <T> void addAsset(final String fileName, Class<T> type, T asset) { // add the asset to the filename lookup assetTypes.put(fileName, type); // add the asset to the type lookup ObjectMap<String, RefCountedContainer> typeToAssets = assets.get(type); if (typeToAssets == null) { typeToAssets = new ObjectMap<String, RefCountedContainer>(); assets.put(type, typeToAssets); } typeToAssets.put(fileName, new RefCountedContainer(asset)); } /** Updates the current task on the top of the task stack. * @return true if the asset is loaded. */ private boolean updateTask () { AssetLoadingTask task = tasks.peek(); // if the task has finished loading if (task.update()) { addAsset(task.assetDesc.fileName, task.assetDesc.type, task.getAsset()); // increase the number of loaded assets and pop the task from the stack if (tasks.size() == 1) loaded++; tasks.pop(); // remove the asset if it was canceled. if (task.cancel) { unload(task.assetDesc.fileName); } else { // otherwise, if a listener was found in the parameter invoke it if (task.assetDesc.params != null && task.assetDesc.params.loadedCallback != null) { task.assetDesc.params.loadedCallback.finishedLoading(this, task.assetDesc.fileName, task.assetDesc.type); } // long endTime = System.nanoTime(); // log.debug("Loaded: " + (endTime - task.startTime) / 1000000f + "ms " + task.assetDesc); } return true; } else { return false; } } private void incrementRefCountedDependencies (String parent) { Array<String> dependencies = assetDependencies.get(parent); if (dependencies == null) return; for (String dependency : dependencies) { Class type = assetTypes.get(dependency); RefCountedContainer assetRef = assets.get(type).get(dependency); assetRef.incRefCount(); incrementRefCountedDependencies(dependency); } } /** Handles a runtime/loading error in {@link #update()} by optionally invoking the {@link AssetErrorListener}. * @param t */ private void handleTaskError (Throwable t) { // log.error("Error loading asset.", t); if (tasks.isEmpty()) throw new GdxRuntimeException(t); // pop the faulty task from the stack AssetLoadingTask task = tasks.pop(); AssetDescriptor assetDesc = task.assetDesc; // remove all dependencies if (task.dependenciesLoaded && task.dependencies != null) { for (AssetDescriptor desc : task.dependencies) { unload(desc.fileName); } } // clear the rest of the stack tasks.clear(); // inform the listener that something bad happened if (listener != null) { listener.error(assetDesc.fileName, assetDesc.type, t); } else { throw new GdxRuntimeException(t); } } /** Sets a new {@link AssetLoader} for the given type. * @param type the type of the asset * @param loader the loader */ public synchronized <T, P extends AssetLoaderParameters<T>> void setLoader (Class<T> type, AssetLoader<T, P> loader) { if (type == null) throw new IllegalArgumentException("type cannot be null."); if (loader == null) throw new IllegalArgumentException("loader cannot be null."); // log.debug("Loader set: " + type.getName() + " -> " + loader.getClass().getName()); loaders.put(type, loader); } /** @return the number of loaded assets */ public synchronized int getLoadedAssets () { return assetTypes.size; } /** @return the number of currently queued assets */ public synchronized int getQueuedAssets () { return loadQueue.size() + (tasks.size()); } /** @return the progress in percent of completion. */ public synchronized float getProgress () { if (toLoad == 0) return 1; return Math.min(1, loaded / (float)toLoad); } /** Sets an {@link AssetErrorListener} to be invoked in case loading an asset failed. * @param listener the listener or null */ public synchronized void setErrorListener (AssetErrorListener listener) { this.listener = listener; } /** Disposes all assets in the manager and stops all asynchronous loading. */ public synchronized void dispose () { // log.debug("Disposing."); clear(); } /** Clears and disposes all assets and the preloading queue. */ public synchronized void clear () { loadQueue.clear(); while (!update()) ; ObjectIntMap<String> dependencyCount = new ObjectIntMap<String>(); while (assetTypes.size > 0) { // for each asset, figure out how often it was referenced dependencyCount.clear(); Array<String> assets = assetTypes.keys().toArray(); for (String asset : assets) { dependencyCount.put(asset, 0); } for (String asset : assets) { Array<String> dependencies = assetDependencies.get(asset); if (dependencies == null) continue; for (String dependency : dependencies) { int count = dependencyCount.get(dependency, 0); count++; dependencyCount.put(dependency, count); } } // only dispose of assets that are root assets (not referenced) for (String asset : assets) { if (dependencyCount.get(asset, 0) == 0) { unload(asset); } } } this.assets.clear(); this.assetTypes.clear(); this.assetDependencies.clear(); this.loaded = 0; this.toLoad = 0; this.loadQueue.clear(); this.tasks.clear(); } /** @return the {@link Logger} used by the {@link AssetManager} */ // public Logger getLogger () { // return log; // return null; // } /** Returns the reference count of an asset. * @param fileName */ public synchronized int getReferenceCount (String fileName) { Class type = assetTypes.get(fileName); if (type == null) throw new GdxRuntimeException("Asset not loaded: " + fileName); return assets.get(type).get(fileName).getRefCount(); } /** Sets the reference count of an asset. * @param fileName */ public synchronized void setReferenceCount (String fileName, int refCount) { Class type = assetTypes.get(fileName); if (type == null) throw new GdxRuntimeException("Asset not loaded: " + fileName); assets.get(type).get(fileName).setRefCount(refCount); } /** @return a string containg ref count and dependency information for all assets. */ public synchronized String getDiagnostics () { StringBuffer buffer = new StringBuffer(); for (String fileName : assetTypes.keys()) { buffer.append(fileName); buffer.append(", "); Class type = assetTypes.get(fileName); RefCountedContainer assetRef = assets.get(type).get(fileName); Array<String> dependencies = assetDependencies.get(fileName); buffer.append(type.getName()); buffer.append(", refs: "); buffer.append(assetRef.getRefCount()); if (dependencies != null) { buffer.append(", deps: ["); for (String dep : dependencies) { buffer.append(dep); buffer.append(","); } buffer.append("]"); } buffer.append("\n"); } return buffer.toString(); } /** blocks until all assets are loaded. */ public void finishLoading () { while (!update()) ; } /** @return the file names of all loaded assets. */ public synchronized Array<String> getAssetNames() { return assetTypes.keys().toArray(); } /** @return the dependencies of an asset or null if the asset has no dependencies. */ public synchronized Array<String> getDependencies(String fileName) { return assetDependencies.get(fileName); } /** @return the type of a loaded asset. */ public synchronized Class getAssetType (String fileName) { return assetTypes.get(fileName); } }
backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/com/badlogic/gdx/assets/AssetManager.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.assets; import java.util.ArrayList; import java.util.Stack; import com.badlogic.gdx.assets.loaders.AssetLoader; import com.badlogic.gdx.assets.loaders.BitmapFontLoader; import com.badlogic.gdx.assets.loaders.FileHandleResolver; import com.badlogic.gdx.assets.loaders.MusicLoader; import com.badlogic.gdx.assets.loaders.PixmapLoader; import com.badlogic.gdx.assets.loaders.SkinLoader; import com.badlogic.gdx.assets.loaders.SoundLoader; import com.badlogic.gdx.assets.loaders.TextureAtlasLoader; import com.badlogic.gdx.assets.loaders.TextureLoader; import com.badlogic.gdx.assets.loaders.resolvers.InternalFileHandleResolver; import com.badlogic.gdx.audio.Music; import com.badlogic.gdx.audio.Sound; import com.badlogic.gdx.graphics.Pixmap; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.TextureAtlas; import com.badlogic.gdx.scenes.scene2d.ui.Skin; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.Disposable; import com.badlogic.gdx.utils.GdxRuntimeException; import com.badlogic.gdx.utils.ObjectIntMap; import com.badlogic.gdx.utils.ObjectMap; public class AssetManager implements Disposable { final ObjectMap<Class, ObjectMap<String, RefCountedContainer>> assets = new ObjectMap<Class, ObjectMap<String, RefCountedContainer>>(); final ObjectMap<String, Class> assetTypes = new ObjectMap<String, Class>(); final ObjectMap<String, Array<String>> assetDependencies = new ObjectMap<String, Array<String>>(); final ObjectMap<Class, AssetLoader> loaders = new ObjectMap<Class, AssetLoader>(); final ArrayList<AssetDescriptor> loadQueue = new ArrayList<AssetDescriptor>(); Stack<AssetLoadingTask> tasks = new Stack<AssetLoadingTask>(); AssetErrorListener listener = null; int loaded = 0; int toLoad = 0; /** Creates a new AssetManager with all default loaders. */ public AssetManager () { this(new InternalFileHandleResolver()); } /** Creates a new AssetManager with all default loaders. */ public AssetManager (FileHandleResolver resolver) { setLoader(BitmapFont.class, new BitmapFontLoader(resolver)); setLoader(Music.class, new MusicLoader(resolver)); setLoader(Pixmap.class, new PixmapLoader(resolver)); setLoader(Sound.class, new SoundLoader(resolver)); setLoader(TextureAtlas.class, new TextureAtlasLoader(resolver)); setLoader(Texture.class, new TextureLoader(resolver)); setLoader(Skin.class, new SkinLoader(resolver)); // setLoader(TileMapRenderer.class, new TileMapRendererLoader(resolver)); } /** @param fileName the asset file name * @return the asset */ public synchronized <T> T get (String fileName) { Class<T> type = assetTypes.get(fileName); ObjectMap<String, RefCountedContainer> assetsByType = assets.get(type); if (assetsByType == null) throw new GdxRuntimeException("Asset not loaded: " + fileName); RefCountedContainer assetContainer = assetsByType.get(fileName); if (assetContainer == null) throw new GdxRuntimeException("Asset not loaded: " + fileName); T asset = assetContainer.getObject(type); if (asset == null) throw new GdxRuntimeException("Asset not loaded: " + fileName); return asset; } /** @param fileName the asset file name * @param type the asset type * @return the asset */ public synchronized <T> T get (String fileName, Class<T> type) { ObjectMap<String, RefCountedContainer> assetsByType = assets.get(type); if (assetsByType == null) throw new GdxRuntimeException("Asset not loaded: " + fileName); RefCountedContainer assetContainer = assetsByType.get(fileName); if (assetContainer == null) throw new GdxRuntimeException("Asset not loaded: " + fileName); T asset = assetContainer.getObject(type); if (asset == null) throw new GdxRuntimeException("Asset not loaded: " + fileName); return asset; } /** Removes the asset and all its dependencies if they are not used by other assets. * @param fileName the file name */ public synchronized void unload (String fileName) { // check if it's in the queue int foundIndex = -1; for (int i = 0; i < loadQueue.size(); i++) { if (loadQueue.get(i).fileName.equals(fileName)) { foundIndex = i; break; } } if (foundIndex != -1) { loadQueue.remove(foundIndex); // log.debug("Unload (from queue): " + fileName); return; } // check if it's currently processed (and the first element in the stack, thus not a dependency) // and cancel if necessary if (tasks.size() > 0) { AssetLoadingTask currAsset = tasks.firstElement(); if (currAsset.assetDesc.fileName.equals(fileName)) { currAsset.cancel = true; // log.debug("Unload (from tasks): " + fileName); return; } } // get the asset and its type Class type = assetTypes.get(fileName); if (type == null) throw new GdxRuntimeException("Asset not loaded: " + fileName); RefCountedContainer assetRef = assets.get(type).get(fileName); // if it is reference counted, decrement ref count and check if we can really get rid of it. assetRef.decRefCount(); if (assetRef.getRefCount() <= 0) { // log.debug("Unload (dispose): " + fileName); // if it is disposable dispose it if (assetRef.getObject(Object.class) instanceof Disposable) ((Disposable)assetRef.getObject(Object.class)).dispose(); // remove the asset from the manager. assetTypes.remove(fileName); assets.get(type).remove(fileName); } else { // log.debug("Unload (decrement): " + fileName); } // remove any dependencies (or just decrement their ref count). Array<String> dependencies = assetDependencies.get(fileName); if (dependencies != null) { for (String dependency : dependencies) { unload(dependency); } } // remove dependencies if ref count < 0 if (assetRef.getRefCount() <= 0) { assetDependencies.remove(fileName); } } /** @param asset the asset * @return whether the asset is contained in this manager */ public synchronized <T> boolean containsAsset (T asset) { ObjectMap<String, RefCountedContainer> typedAssets = assets.get(asset.getClass()); if (typedAssets == null) return false; for (String fileName : typedAssets.keys()) { T otherAsset = (T)typedAssets.get(fileName).getObject(Object.class); if (otherAsset == asset || asset.equals(otherAsset)) return true; } return false; } /** @param asset the asset * @return whether the filename of the asset or null */ public synchronized <T> String getAssetFileName (T asset) { for (Class assetType : assets.keys()) { ObjectMap<String, RefCountedContainer> typedAssets = assets.get(assetType); for (String fileName : typedAssets.keys()) { T otherAsset = (T)typedAssets.get(fileName).getObject(Object.class); if (otherAsset == asset || asset.equals(otherAsset)) return fileName; } } return null; } /** @param fileName the file name of the asset * @return whether the asset is loaded */ public synchronized boolean isLoaded (String fileName) { if (fileName == null) return false; return assetTypes.containsKey(fileName); } /** @param fileName the file name of the asset * @return whether the asset is loaded */ public synchronized boolean isLoaded (String fileName, Class type) { ObjectMap<String, RefCountedContainer> assetsByType = assets.get(type); if (assetsByType == null) return false; RefCountedContainer assetContainer = assetsByType.get(fileName); if (assetContainer == null) return false; return assetContainer.getObject(type) != null; } /** Adds the given asset to the loading queue of the AssetManager. * @param fileName the file name (interpretation depends on {@link AssetLoader}) * @param type the type of the asset. */ public synchronized <T> void load (String fileName, Class<T> type) { load(fileName, type, null); } /** Adds the given asset to the loading queue of the AssetManager. * @param fileName the file name (interpretation depends on {@link AssetLoader}) * @param type the type of the asset. * @param parameter parameters for the AssetLoader. */ public synchronized <T> void load (String fileName, Class<T> type, AssetLoaderParameters<T> parameter) { AssetLoader loader = loaders.get(type); if (loader == null) throw new GdxRuntimeException("No loader for type: " + type.getName()); if (loadQueue.size() == 0) { loaded = 0; toLoad = 0; } // check if an asset with the same name but a different type has already been added. // check preload queue for (int i = 0; i < loadQueue.size(); i++) { AssetDescriptor desc = loadQueue.get(i); if (desc.fileName.equals(fileName) && !desc.type.equals(type)) throw new GdxRuntimeException("Asset with name '" + fileName + "' already in preload queue, but has different type (expected: " + type.getName() + ", found: " + desc.type.getName()); } // check task list for (int i = 0; i < tasks.size(); i++) { AssetDescriptor desc = tasks.get(i).assetDesc; if (desc.fileName.equals(fileName) && !desc.type.equals(type)) throw new GdxRuntimeException("Asset with name '" + fileName + "' already in task list, but has different type (expected: " + type.getName() + ", found: " + desc.type.getName()); } // check loaded assets Class otherType = assetTypes.get(fileName); if (otherType != null && !otherType.equals(type)) throw new GdxRuntimeException("Asset with name '" + fileName + "' already loaded, but has different type (expected: " + type.getName() + ", found: " + otherType.getName()); toLoad++; AssetDescriptor assetDesc = new AssetDescriptor(fileName, type, parameter); loadQueue.add(assetDesc); // log.debug("Queued: " + assetDesc); } /** Adds the given asset to the loading queue of the AssetManager. * @param desc the {@link AssetDescriptor} */ public synchronized void load (AssetDescriptor desc) { load(desc.fileName, desc.type, desc.params); } /** Disposes the given asset and all its dependencies recursively, depth first. * @param fileName */ private void disposeDependencies (String fileName) { Array<String> dependencies = assetDependencies.get(fileName); if (dependencies != null) { for (String dependency : dependencies) { disposeDependencies(dependency); } } Class type = assetTypes.get(fileName); Object asset = assets.get(type).get(fileName).getObject(Object.class); if (asset instanceof Disposable) ((Disposable)asset).dispose(); } /** Updates the AssetManager, keeping it loading any assets in the preload queue. * @return true if all loading is finished. */ public synchronized boolean update () { try { if (tasks.size() == 0) { // loop until we have a new task ready to be processed while (loadQueue.size() != 0 && tasks.size() == 0) { nextTask(); } // have we not found a task? We are done! if (tasks.size() == 0) return true; } return updateTask() && loadQueue.size() == 0 && tasks.size() == 0; } catch (Throwable t) { handleTaskError(t); return loadQueue.size() == 0; } } // public void finishLoading () { // log.debug("Waiting for loading to complete..."); // while (!update()) // Thread.yield(); // log.debug("Loading complete."); // } synchronized void injectDependency (String parentAssetFilename, AssetDescriptor dependendAssetDesc) { // add the asset as a dependency of the parent asset Array<String> dependencies = assetDependencies.get(parentAssetFilename); if (dependencies == null) { dependencies = new Array<String>(); assetDependencies.put(parentAssetFilename, dependencies); } dependencies.add(dependendAssetDesc.fileName); // if the asset is already loaded, increase its reference count. if (isLoaded(dependendAssetDesc.fileName)) { // log.debug("Dependency already loaded: " + dependendAssetDesc); Class type = assetTypes.get(dependendAssetDesc.fileName); RefCountedContainer assetRef = assets.get(type).get(dependendAssetDesc.fileName); assetRef.incRefCount(); incrementRefCountedDependencies(dependendAssetDesc.fileName); } // else add a new task for the asset. else { // log.info("Loading dependency: " + dependendAssetDesc); addTask(dependendAssetDesc); } } /** Removes a task from the loadQueue and adds it to the task stack. If the asset is already loaded (which can happen if it was * a dependency of a previously loaded asset) its reference count will be increased. */ private void nextTask () { AssetDescriptor assetDesc = loadQueue.remove(0); // if the asset not meant to be reloaded and is already loaded, increase its reference count if (isLoaded(assetDesc.fileName)) { // log.debug("Already loaded: " + assetDesc); Class type = assetTypes.get(assetDesc.fileName); RefCountedContainer assetRef = assets.get(type).get(assetDesc.fileName); assetRef.incRefCount(); incrementRefCountedDependencies(assetDesc.fileName); loaded++; } else { // else add a new task for the asset. // log.info("Loading: " + assetDesc); addTask(assetDesc); } } /** Adds a {@link AssetLoadingTask} to the task stack for the given asset. * @param assetDesc */ private void addTask (AssetDescriptor assetDesc) { AssetLoader loader = loaders.get(assetDesc.type); if (loader == null) throw new GdxRuntimeException("No loader for type: " + assetDesc.type.getName()); tasks.push(new AssetLoadingTask(this, assetDesc, loader)); } /** Updates the current task on the top of the task stack. * @return true if the asset is loaded. */ private boolean updateTask () { AssetLoadingTask task = tasks.peek(); // if the task has finished loading if (task.update()) { // add the asset to the filename lookup assetTypes.put(task.assetDesc.fileName, task.assetDesc.type); // add the asset to the type lookup ObjectMap<String, RefCountedContainer> typeToAssets = assets.get(task.assetDesc.type); if (typeToAssets == null) { typeToAssets = new ObjectMap<String, RefCountedContainer>(); assets.put(task.assetDesc.type, typeToAssets); } typeToAssets.put(task.assetDesc.fileName, new RefCountedContainer(task.getAsset())); // increase the number of loaded assets and pop the task from the stack if (tasks.size() == 1) loaded++; tasks.pop(); // remove the asset if it was canceled. if (task.cancel) { unload(task.assetDesc.fileName); } else { // otherwise, if a listener was found in the parameter invoke it if (task.assetDesc.params != null && task.assetDesc.params.loadedCallback != null) { task.assetDesc.params.loadedCallback.finishedLoading(this, task.assetDesc.fileName, task.assetDesc.type); } // long endTime = System.nanoTime(); // log.debug("Loaded: " + (endTime - task.startTime) / 1000000f + "ms " + task.assetDesc); } return true; } else { return false; } } private void incrementRefCountedDependencies (String parent) { Array<String> dependencies = assetDependencies.get(parent); if (dependencies == null) return; for (String dependency : dependencies) { Class type = assetTypes.get(dependency); RefCountedContainer assetRef = assets.get(type).get(dependency); assetRef.incRefCount(); incrementRefCountedDependencies(dependency); } } /** Handles a runtime/loading error in {@link #update()} by optionally invoking the {@link AssetErrorListener}. * @param t */ private void handleTaskError (Throwable t) { // log.error("Error loading asset.", t); if (tasks.isEmpty()) throw new GdxRuntimeException(t); // pop the faulty task from the stack AssetLoadingTask task = tasks.pop(); AssetDescriptor assetDesc = task.assetDesc; // remove all dependencies if (task.dependenciesLoaded && task.dependencies != null) { for (AssetDescriptor desc : task.dependencies) { unload(desc.fileName); } } // clear the rest of the stack tasks.clear(); // inform the listener that something bad happened if (listener != null) { listener.error(assetDesc.fileName, assetDesc.type, t); } else { throw new GdxRuntimeException(t); } } /** Sets a new {@link AssetLoader} for the given type. * @param type the type of the asset * @param loader the loader */ public synchronized <T, P extends AssetLoaderParameters<T>> void setLoader (Class<T> type, AssetLoader<T, P> loader) { if (type == null) throw new IllegalArgumentException("type cannot be null."); if (loader == null) throw new IllegalArgumentException("loader cannot be null."); // log.debug("Loader set: " + type.getName() + " -> " + loader.getClass().getName()); loaders.put(type, loader); } /** @return the number of loaded assets */ public synchronized int getLoadedAssets () { return assetTypes.size; } /** @return the number of currently queued assets */ public synchronized int getQueuedAssets () { return loadQueue.size() + (tasks.size()); } /** @return the progress in percent of completion. */ public synchronized float getProgress () { if (toLoad == 0) return 1; return Math.min(1, loaded / (float)toLoad); } /** Sets an {@link AssetErrorListener} to be invoked in case loading an asset failed. * @param listener the listener or null */ public synchronized void setErrorListener (AssetErrorListener listener) { this.listener = listener; } /** Disposes all assets in the manager and stops all asynchronous loading. */ public synchronized void dispose () { // log.debug("Disposing."); clear(); } /** Clears and disposes all assets and the preloading queue. */ public synchronized void clear () { loadQueue.clear(); while (!update()) ; ObjectIntMap<String> dependencyCount = new ObjectIntMap<String>(); while (assetTypes.size > 0) { // for each asset, figure out how often it was referenced dependencyCount.clear(); Array<String> assets = assetTypes.keys().toArray(); for (String asset : assets) { dependencyCount.put(asset, 0); } for (String asset : assets) { Array<String> dependencies = assetDependencies.get(asset); if (dependencies == null) continue; for (String dependency : dependencies) { int count = dependencyCount.get(dependency, 0); count++; dependencyCount.put(dependency, count); } } // only dispose of assets that are root assets (not referenced) for (String asset : assets) { if (dependencyCount.get(asset, 0) == 0) { unload(asset); } } } this.assets.clear(); this.assetTypes.clear(); this.assetDependencies.clear(); this.loaded = 0; this.toLoad = 0; this.loadQueue.clear(); this.tasks.clear(); } /** @return the {@link Logger} used by the {@link AssetManager} */ // public Logger getLogger () { // return log; // return null; // } /** Returns the reference count of an asset. * @param fileName */ public synchronized int getReferenceCount (String fileName) { Class type = assetTypes.get(fileName); if (type == null) throw new GdxRuntimeException("Asset not loaded: " + fileName); return assets.get(type).get(fileName).getRefCount(); } /** Sets the reference count of an asset. * @param fileName */ public synchronized void setReferenceCount (String fileName, int refCount) { Class type = assetTypes.get(fileName); if (type == null) throw new GdxRuntimeException("Asset not loaded: " + fileName); assets.get(type).get(fileName).setRefCount(refCount); } /** @return a string containg ref count and dependency information for all assets. */ public synchronized String getDiagnostics () { StringBuffer buffer = new StringBuffer(); for (String fileName : assetTypes.keys()) { buffer.append(fileName); buffer.append(", "); Class type = assetTypes.get(fileName); RefCountedContainer assetRef = assets.get(type).get(fileName); Array<String> dependencies = assetDependencies.get(fileName); buffer.append(type.getName()); buffer.append(", refs: "); buffer.append(assetRef.getRefCount()); if (dependencies != null) { buffer.append(", deps: ["); for (String dep : dependencies) { buffer.append(dep); buffer.append(","); } buffer.append("]"); } buffer.append("\n"); } return buffer.toString(); } /** blocks until all assets are loaded. */ public void finishLoading () { while (!update()) ; } /** @return the file names of all loaded assets. */ public synchronized Array<String> getAssetNames() { return assetTypes.keys().toArray(); } /** @return the dependencies of an asset or null if the asset has no dependencies. */ public synchronized Array<String> getDependencies(String fileName) { return assetDependencies.get(fileName); } /** @return the type of a loaded asset. */ public synchronized Class getAssetType (String fileName) { return assetTypes.get(fileName); } }
Update Gwt AssetManager
backends/gdx-backends-gwt/src/com/badlogic/gdx/backends/gwt/emu/com/badlogic/gdx/assets/AssetManager.java
Update Gwt AssetManager
Java
apache-2.0
3ec845660e554b1f9c8f926a669daf0094ca4239
0
DevStreet/FinanceAnalytics,nssales/OG-Platform,McLeodMoores/starling,McLeodMoores/starling,codeaudit/OG-Platform,codeaudit/OG-Platform,jeorme/OG-Platform,jeorme/OG-Platform,ChinaQuants/OG-Platform,jerome79/OG-Platform,nssales/OG-Platform,McLeodMoores/starling,McLeodMoores/starling,jerome79/OG-Platform,ChinaQuants/OG-Platform,jeorme/OG-Platform,ChinaQuants/OG-Platform,nssales/OG-Platform,jeorme/OG-Platform,jerome79/OG-Platform,DevStreet/FinanceAnalytics,DevStreet/FinanceAnalytics,codeaudit/OG-Platform,jerome79/OG-Platform,codeaudit/OG-Platform,nssales/OG-Platform,ChinaQuants/OG-Platform,DevStreet/FinanceAnalytics
/** * Copyright (C) 2009 - 2010 by OpenGamma Inc. * * Please see distribution for license. */ package com.opengamma.financial.analytics.model.option; import com.opengamma.OpenGammaRuntimeException; import com.opengamma.engine.ComputationTarget; import com.opengamma.engine.ComputationTargetType; import com.opengamma.engine.function.FunctionCompilationContext; import com.opengamma.financial.model.option.definition.AmericanVanillaOptionDefinition; import com.opengamma.financial.model.option.definition.EuropeanVanillaOptionDefinition; import com.opengamma.financial.model.option.definition.OptionDefinition; import com.opengamma.financial.model.option.definition.StandardOptionDataBundle; import com.opengamma.financial.model.option.pricing.analytic.AnalyticOptionModel; import com.opengamma.financial.model.option.pricing.analytic.BlackScholesMertonModel; import com.opengamma.financial.security.option.AmericanExerciseType; import com.opengamma.financial.security.option.AsianExerciseType; import com.opengamma.financial.security.option.BermudanExerciseType; import com.opengamma.financial.security.option.EuropeanExerciseType; import com.opengamma.financial.security.option.ExerciseTypeVisitor; import com.opengamma.financial.security.option.OptionSecurity; import com.opengamma.financial.security.option.OptionType; /** * * */ public class BlackScholesMertonModelFunction extends StandardOptionDataAnalyticOptionModelFunction { private final AnalyticOptionModel<OptionDefinition, StandardOptionDataBundle> _model = new BlackScholesMertonModel(); @Override public boolean canApplyTo(final FunctionCompilationContext context, final ComputationTarget target) { if (target.getType() != ComputationTargetType.SECURITY) { return false; } if (target.getSecurity() instanceof OptionSecurity) { return true; } return false; } @Override public String getShortName() { return "BlackScholesMertonModel"; } @Override protected AnalyticOptionModel<OptionDefinition, StandardOptionDataBundle> getModel() { return _model; } @Override protected OptionDefinition getOptionDefinition(final OptionSecurity option) { return option.getExerciseType().accept( new ExerciseTypeVisitor<OptionDefinition>() { @Override public OptionDefinition visitAmericanExerciseType(AmericanExerciseType exerciseType) { return new AmericanVanillaOptionDefinition(option.getStrike(), option.getExpiry(), option.getOptionType() == OptionType.CALL); } @Override public OptionDefinition visitAsianExerciseType(AsianExerciseType exerciseType) { throw new OpenGammaRuntimeException("Unsupported option type: Asian"); } @Override public OptionDefinition visitBermudanExerciseType(BermudanExerciseType exerciseType) { throw new OpenGammaRuntimeException("Unsupported option type: Bermudan"); } @Override public OptionDefinition visitEuropeanExerciseType(EuropeanExerciseType exerciseType) { return new EuropeanVanillaOptionDefinition(option.getStrike(), option.getExpiry(), option.getOptionType() == OptionType.CALL); } } ); } }
projects/OG-Financial/src/com/opengamma/financial/analytics/model/option/BlackScholesMertonModelFunction.java
/** * Copyright (C) 2009 - 2010 by OpenGamma Inc. * * Please see distribution for license. */ package com.opengamma.financial.analytics.model.option; import com.opengamma.OpenGammaRuntimeException; import com.opengamma.engine.ComputationTarget; import com.opengamma.engine.ComputationTargetType; import com.opengamma.engine.function.FunctionCompilationContext; import com.opengamma.financial.model.option.definition.AmericanVanillaOptionDefinition; import com.opengamma.financial.model.option.definition.EuropeanVanillaOptionDefinition; import com.opengamma.financial.model.option.definition.OptionDefinition; import com.opengamma.financial.model.option.definition.StandardOptionDataBundle; import com.opengamma.financial.model.option.pricing.analytic.AnalyticOptionModel; import com.opengamma.financial.model.option.pricing.analytic.BlackScholesMertonModel; import com.opengamma.financial.security.option.AmericanExerciseType; import com.opengamma.financial.security.option.AsianExerciseType; import com.opengamma.financial.security.option.BermudanExerciseType; import com.opengamma.financial.security.option.EuropeanExerciseType; import com.opengamma.financial.security.option.ExerciseType; import com.opengamma.financial.security.option.ExerciseTypeVisitor; import com.opengamma.financial.security.option.OptionSecurity; import com.opengamma.financial.security.option.OptionType; /** * * */ public class BlackScholesMertonModelFunction extends StandardOptionDataAnalyticOptionModelFunction { private final AnalyticOptionModel<OptionDefinition, StandardOptionDataBundle> _model = new BlackScholesMertonModel(); @Override public boolean canApplyTo(final FunctionCompilationContext context, final ComputationTarget target) { if (target.getType() != ComputationTargetType.SECURITY) { return false; } if (target.getSecurity() instanceof OptionSecurity) { return true; } return false; } @Override public String getShortName() { return "BlackScholesMertonModel"; } @Override protected AnalyticOptionModel<OptionDefinition, StandardOptionDataBundle> getModel() { return _model; } @Override protected OptionDefinition getOptionDefinition(final OptionSecurity option) { return option.getExerciseType().accept( new ExerciseTypeVisitor<OptionDefinition>() { @Override public OptionDefinition visitAmericanExerciseType(AmericanExerciseType exerciseType) { return new AmericanVanillaOptionDefinition(option.getStrike(), option.getExpiry(), option.getOptionType() == OptionType.CALL); } @Override public OptionDefinition visitAsianExerciseType(AsianExerciseType exerciseType) { throw new OpenGammaRuntimeException("Unsupported option type: Asian"); } @Override public OptionDefinition visitBermudanExerciseType(BermudanExerciseType exerciseType) { throw new OpenGammaRuntimeException("Unsupported option type: Bermudan"); } @Override public OptionDefinition visitEuropeanExerciseType(EuropeanExerciseType exerciseType) { return new EuropeanVanillaOptionDefinition(option.getStrike(), option.getExpiry(), option.getOptionType() == OptionType.CALL); } } ); } }
Removed unnecessary import.
projects/OG-Financial/src/com/opengamma/financial/analytics/model/option/BlackScholesMertonModelFunction.java
Removed unnecessary import.
Java
apache-2.0
8a0f1f5e56a677bdc957201b15dc595ee77b266c
0
kishorejangid/manifoldcf,kishorejangid/manifoldcf,kishorejangid/manifoldcf,kishorejangid/manifoldcf,apache/manifoldcf,apache/manifoldcf,apache/manifoldcf,apache/manifoldcf,apache/manifoldcf,apache/manifoldcf,kishorejangid/manifoldcf,kishorejangid/manifoldcf
/* $Id: LivelinkConnector.java 996524 2010-09-13 13:38:01Z kwright $ */ /** * 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.manifoldcf.crawler.connectors.livelink; import org.apache.manifoldcf.core.interfaces.*; import org.apache.manifoldcf.agents.interfaces.*; import org.apache.manifoldcf.crawler.interfaces.*; import org.apache.manifoldcf.crawler.system.Logging; import org.apache.manifoldcf.crawler.system.ManifoldCF; import org.apache.manifoldcf.core.common.XThreadInputStream; import org.apache.manifoldcf.core.common.XThreadOutputStream; import org.apache.manifoldcf.core.common.InterruptibleSocketFactory; import org.apache.manifoldcf.core.common.DateParser; import org.apache.manifoldcf.livelink.*; import java.io.*; import java.util.*; import java.net.*; import java.util.concurrent.TimeUnit; import com.opentext.api.*; import org.apache.http.conn.HttpClientConnectionManager; import org.apache.http.client.HttpClient; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.protocol.HttpRequestExecutor; import org.apache.http.impl.client.HttpClients; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.CredentialsProvider; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.config.SocketConfig; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.NameValuePair; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.conn.ssl.BrowserCompatHostnameVerifier; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.auth.AuthScope; import org.apache.http.auth.NTCredentials; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpRequestBase; import org.apache.http.impl.client.DefaultRedirectStrategy; import org.apache.http.util.EntityUtils; import org.apache.http.HttpStatus; import org.apache.http.HttpHost; import org.apache.http.Header; import org.apache.http.message.BasicHeader; import org.apache.http.message.BasicNameValuePair; import org.apache.http.protocol.HTTP; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.HttpRequestRetryHandler; import org.apache.http.protocol.HttpContext; import org.apache.http.conn.ConnectTimeoutException; import org.apache.http.client.RedirectException; import org.apache.http.client.CircularRedirectException; import org.apache.http.NoHttpResponseException; import org.apache.http.HttpException; /** This is the Livelink implementation of the IRepositoryConnectr interface. * The original Volant code forced there to be one livelink session per JVM, with * lots of buggy synchronization present to try to enforce this. This implementation * is multi-session. However, since it is possible that the Volant restriction was * indeed needed, I have attempted to structure things to allow me to turn on * single-session if needed. * * For livelink, the document identifiers are the object identifiers. * */ public class LivelinkConnector extends org.apache.manifoldcf.crawler.connectors.BaseRepositoryConnector { public static final String _rcsid = "@(#)$Id: LivelinkConnector.java 996524 2010-09-13 13:38:01Z kwright $"; // Activities we will report on private final static String ACTIVITY_SEED = "find documents"; private final static String ACTIVITY_FETCH = "fetch document"; /** Deny access token for default authority */ private final static String defaultAuthorityDenyToken = GLOBAL_DENY_TOKEN; // A couple of very important points. // First, the canonical document identifier has the following form: // <D|F>[<volume_id>:]<object_id> // Second, the only LEGAL objects for a document identifier to describe // are folders, documents, and volume objects. Project objects are NOT // allowed; they must be mapped to the appropriate volume object before // being returned to the crawler. // Metadata names for general metadata fields protected final static String GENERAL_NAME_FIELD = "general_name"; protected final static String GENERAL_DESCRIPTION_FIELD = "general_description"; protected final static String GENERAL_CREATIONDATE_FIELD = "general_creationdate"; protected final static String GENERAL_MODIFYDATE_FIELD = "general_modifydate"; protected final static String GENERAL_OWNER = "general_owner"; protected final static String GENERAL_CREATOR = "general_creator"; protected final static String GENERAL_MODIFIER = "general_modifier"; protected final static String GENERAL_PARENTID = "general_parentid"; // Signal that we have set up connection parameters properly private boolean hasSessionParameters = false; // Signal that we have set up a connection properly private boolean hasConnected = false; // Session expiration time private long expirationTime = -1L; // Idle session expiration interval private final static long expirationInterval = 300000L; // Data required for maintaining livelink connection private LAPI_DOCUMENTS LLDocs = null; private LAPI_ATTRIBUTES LLAttributes = null; private LAPI_USERS LLUsers = null; private LLSERVER llServer = null; private int LLENTWK_VOL; private int LLENTWK_ID; private int LLCATWK_VOL; private int LLCATWK_ID; // Parameter values we need private String serverProtocol = null; private String serverName = null; private int serverPort = -1; private String serverUsername = null; private String serverPassword = null; private String serverHTTPCgi = null; private String serverHTTPNTLMDomain = null; private String serverHTTPNTLMUsername = null; private String serverHTTPNTLMPassword = null; private IKeystoreManager serverHTTPSKeystore = null; private String ingestProtocol = null; private String ingestPort = null; private String ingestCgiPath = null; private String viewProtocol = null; private String viewServerName = null; private String viewPort = null; private String viewCgiPath = null; private String ingestNtlmDomain = null; private String ingestNtlmUsername = null; private String ingestNtlmPassword = null; // SSL support for ingestion private IKeystoreManager ingestKeystoreManager = null; // Connection management private HttpClientConnectionManager connectionManager = null; private HttpClient httpClient = null; // Base path for viewing private String viewBasePath = null; // Ingestion port number private int ingestPortNumber = -1; // Activities list private static final String[] activitiesList = new String[]{ACTIVITY_SEED,ACTIVITY_FETCH}; // Retry count. This is so we can try to install some measure of sanity into situations where LAPI gets confused communicating to the server. // So, for some kinds of errors, we just retry for a while hoping it will go away. private static final int FAILURE_RETRY_COUNT = 10; // Current host name private static String currentHost = null; private static java.net.InetAddress currentAddr = null; static { // Find the current host name try { currentAddr = java.net.InetAddress.getLocalHost(); // Get hostname currentHost = currentAddr.getHostName(); } catch (UnknownHostException e) { } } /** Constructor. */ public LivelinkConnector() { } /** Tell the world what model this connector uses for getDocumentIdentifiers(). * This must return a model value as specified above. *@return the model type value. */ @Override public int getConnectorModel() { // Livelink is a chained hierarchy model return MODEL_CHAINED_ADD_CHANGE; } /** Connect. The configuration parameters are included. *@param configParams are the configuration parameters for this connection. */ @Override public void connect(ConfigParams configParams) { super.connect(configParams); // This is required by getBins() serverName = params.getParameter(LiveLinkParameters.serverName); } protected class GetSessionThread extends Thread { protected Throwable exception = null; public GetSessionThread() { super(); setDaemon(true); } public void run() { try { // Create the session llServer = new LLSERVER(!serverProtocol.equals("internal"),serverProtocol.equals("https"), serverName,serverPort,serverUsername,serverPassword, serverHTTPCgi,serverHTTPNTLMDomain,serverHTTPNTLMUsername,serverHTTPNTLMPassword, serverHTTPSKeystore); LLDocs = new LAPI_DOCUMENTS(llServer.getLLSession()); LLAttributes = new LAPI_ATTRIBUTES(llServer.getLLSession()); LLUsers = new LAPI_USERS(llServer.getLLSession()); if (Logging.connectors.isDebugEnabled()) { String passwordExists = (serverPassword!=null&&serverPassword.length()>0)?"password exists":""; Logging.connectors.debug("Livelink: Livelink Session: Server='"+serverName+"'; port='"+serverPort+"'; user name='"+serverUsername+"'; "+passwordExists); } LLValue entinfo = new LLValue().setAssoc(); int status; status = LLDocs.AccessEnterpriseWS(entinfo); if (status == 0) { LLENTWK_ID = entinfo.toInteger("ID"); LLENTWK_VOL = entinfo.toInteger("VolumeID"); } else throw new ManifoldCFException("Error accessing enterprise workspace: "+status); entinfo = new LLValue().setAssoc(); status = LLDocs.AccessCategoryWS(entinfo); if (status == 0) { LLCATWK_ID = entinfo.toInteger("ID"); LLCATWK_VOL = entinfo.toInteger("VolumeID"); } else throw new ManifoldCFException("Error accessing category workspace: "+status); } catch (Throwable e) { this.exception = e; } } public void finishUp() throws ManifoldCFException, InterruptedException { join(); Throwable thr = exception; if (thr != null) { if (thr instanceof RuntimeException) throw (RuntimeException)thr; else if (thr instanceof ManifoldCFException) throw (ManifoldCFException)thr; else if (thr instanceof Error) throw (Error)thr; else throw new RuntimeException("Unrecognized exception type: "+thr.getClass().getName()+": "+thr.getMessage(),thr); } } } /** Get the bin name string for a document identifier. The bin name describes the queue to which the * document will be assigned for throttling purposes. Throttling controls the rate at which items in a * given queue are fetched; it does not say anything about the overall fetch rate, which may operate on * multiple queues or bins. * For example, if you implement a web crawler, a good choice of bin name would be the server name, since * that is likely to correspond to a real resource that will need real throttle protection. *@param documentIdentifier is the document identifier. *@return the bin name. */ @Override public String[] getBinNames(String documentIdentifier) { // This should return server name return new String[]{serverName}; } protected HttpHost getHost() { return new HttpHost(llServer.getHost(),ingestPortNumber,ingestProtocol); } protected void getSessionParameters() throws ManifoldCFException { if (hasSessionParameters == false) { // Do the initial setup part (what used to be part of connect() itself) // Get the parameters ingestProtocol = params.getParameter(LiveLinkParameters.ingestProtocol); ingestPort = params.getParameter(LiveLinkParameters.ingestPort); ingestCgiPath = params.getParameter(LiveLinkParameters.ingestCgiPath); viewProtocol = params.getParameter(LiveLinkParameters.viewProtocol); viewServerName = params.getParameter(LiveLinkParameters.viewServerName); viewPort = params.getParameter(LiveLinkParameters.viewPort); viewCgiPath = params.getParameter(LiveLinkParameters.viewCgiPath); ingestNtlmDomain = params.getParameter(LiveLinkParameters.ingestNtlmDomain); ingestNtlmUsername = params.getParameter(LiveLinkParameters.ingestNtlmUsername); ingestNtlmPassword = params.getObfuscatedParameter(LiveLinkParameters.ingestNtlmPassword); serverProtocol = params.getParameter(LiveLinkParameters.serverProtocol); String serverPortString = params.getParameter(LiveLinkParameters.serverPort); serverUsername = params.getParameter(LiveLinkParameters.serverUsername); serverPassword = params.getObfuscatedParameter(LiveLinkParameters.serverPassword); serverHTTPCgi = params.getParameter(LiveLinkParameters.serverHTTPCgiPath); serverHTTPNTLMDomain = params.getParameter(LiveLinkParameters.serverHTTPNTLMDomain); serverHTTPNTLMUsername = params.getParameter(LiveLinkParameters.serverHTTPNTLMUsername); serverHTTPNTLMPassword = params.getObfuscatedParameter(LiveLinkParameters.serverHTTPNTLMPassword); if (ingestProtocol == null || ingestProtocol.length() == 0) ingestProtocol = null; if (viewProtocol == null || viewProtocol.length() == 0) { if (ingestProtocol == null) viewProtocol = "http"; else viewProtocol = ingestProtocol; } if (ingestPort == null || ingestPort.length() == 0) { if (ingestProtocol != null) { if (!ingestProtocol.equals("https")) ingestPort = "80"; else ingestPort = "443"; } else ingestPort = null; } if (viewPort == null || viewPort.length() == 0) { if (ingestProtocol == null || !viewProtocol.equals(ingestProtocol)) { if (!viewProtocol.equals("https")) viewPort = "80"; else viewPort = "443"; } else viewPort = ingestPort; } if (ingestPort != null) { try { ingestPortNumber = Integer.parseInt(ingestPort); } catch (NumberFormatException e) { throw new ManifoldCFException("Bad ingest port: "+e.getMessage(),e); } } String viewPortString; try { int portNumber = Integer.parseInt(viewPort); viewPortString = ":" + Integer.toString(portNumber); if (!viewProtocol.equals("https")) { if (portNumber == 80) viewPortString = ""; } else { if (portNumber == 443) viewPortString = ""; } } catch (NumberFormatException e) { throw new ManifoldCFException("Bad view port: "+e.getMessage(),e); } if (viewCgiPath == null || viewCgiPath.length() == 0) viewCgiPath = ingestCgiPath; if (ingestNtlmDomain != null && ingestNtlmDomain.length() == 0) ingestNtlmDomain = null; if (ingestNtlmDomain == null) { ingestNtlmUsername = null; ingestNtlmPassword = null; } else { if (ingestNtlmUsername == null || ingestNtlmUsername.length() == 0) { ingestNtlmUsername = serverUsername; if (ingestNtlmPassword == null || ingestNtlmPassword.length() == 0) ingestNtlmPassword = serverPassword; } else { if (ingestNtlmPassword == null) ingestNtlmPassword = ""; } } // Set up ingest ssl if indicated String ingestKeystoreData = params.getParameter(LiveLinkParameters.ingestKeystore); if (ingestKeystoreData != null) ingestKeystoreManager = KeystoreManagerFactory.make("",ingestKeystoreData); // Server parameter processing if (serverProtocol == null || serverProtocol.length() == 0) serverProtocol = "internal"; if (serverPortString == null) serverPort = 2099; else serverPort = new Integer(serverPortString).intValue(); if (serverHTTPNTLMDomain != null && serverHTTPNTLMDomain.length() == 0) serverHTTPNTLMDomain = null; if (serverHTTPNTLMUsername == null || serverHTTPNTLMUsername.length() == 0) { serverHTTPNTLMUsername = null; serverHTTPNTLMPassword = null; } // Set up server ssl if indicated String serverHTTPSKeystoreData = params.getParameter(LiveLinkParameters.serverHTTPSKeystore); if (serverHTTPSKeystoreData != null) serverHTTPSKeystore = KeystoreManagerFactory.make("",serverHTTPSKeystoreData); // View parameters if (viewServerName == null || viewServerName.length() == 0) viewServerName = serverName; viewBasePath = viewProtocol+"://"+viewServerName+viewPortString+viewCgiPath; hasSessionParameters = true; } } protected void getSession() throws ManifoldCFException, ServiceInterruption { getSessionParameters(); if (hasConnected == false) { int socketTimeout = 900000; int connectionTimeout = 300000; // Set up connection manager connectionManager = new PoolingHttpClientConnectionManager(); CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); // Set up ingest ssl if indicated SSLConnectionSocketFactory myFactory = null; if (ingestKeystoreManager != null) { myFactory = new SSLConnectionSocketFactory(new InterruptibleSocketFactory(ingestKeystoreManager.getSecureSocketFactory(), connectionTimeout), new BrowserCompatHostnameVerifier()); } // Set up authentication to use if (ingestNtlmDomain != null) { credentialsProvider.setCredentials(AuthScope.ANY, new NTCredentials(ingestNtlmUsername,ingestNtlmPassword,currentHost,ingestNtlmDomain)); } HttpClientBuilder builder = HttpClients.custom() .setConnectionManager(connectionManager) .setMaxConnTotal(1) .disableAutomaticRetries() .setDefaultRequestConfig(RequestConfig.custom() .setCircularRedirectsAllowed(true) .setSocketTimeout(socketTimeout) .setStaleConnectionCheckEnabled(true) .setExpectContinueEnabled(true) .setConnectTimeout(connectionTimeout) .setConnectionRequestTimeout(socketTimeout) .build()) .setDefaultSocketConfig(SocketConfig.custom() .setTcpNoDelay(true) .setSoTimeout(socketTimeout) .build()) .setDefaultCredentialsProvider(credentialsProvider) .setRequestExecutor(new HttpRequestExecutor(socketTimeout)) .setRedirectStrategy(new DefaultRedirectStrategy()); if (myFactory != null) builder.setSSLSocketFactory(myFactory); httpClient = builder.build(); // System.out.println("Connection server object = "+llServer.toString()); // Establish the actual connection int sanityRetryCount = FAILURE_RETRY_COUNT; while (true) { GetSessionThread t = new GetSessionThread(); try { t.start(); t.finishUp(); hasConnected = true; break; } catch (InterruptedException e) { t.interrupt(); throw new ManifoldCFException("Interrupted: "+e.getMessage(),e,ManifoldCFException.INTERRUPTED); } catch (RuntimeException e2) { sanityRetryCount = handleLivelinkRuntimeException(e2,sanityRetryCount,true); } } } expirationTime = System.currentTimeMillis() + expirationInterval; } // All methods below this line will ONLY be called if a connect() call succeeded // on this instance! protected static int executeMethodViaThread(HttpClient client, HttpRequestBase executeMethod) throws InterruptedException, HttpException, IOException { ExecuteMethodThread t = new ExecuteMethodThread(client,executeMethod); t.start(); try { return t.getResponseCode(); } catch (InterruptedException e) { t.interrupt(); throw e; } finally { t.abort(); t.finishUp(); } } /** Check status of connection. */ @Override public String check() throws ManifoldCFException { try { // Destroy saved session setup and repeat it hasConnected = false; getSession(); // Now, set up trial of ingestion connection if (ingestProtocol != null) { String contextMsg = "for document access"; String ingestHttpAddress = ingestCgiPath; HttpClient client = getInitializedClient(contextMsg); HttpGet method = new HttpGet(getHost().toURI() + ingestHttpAddress); method.setHeader(new BasicHeader("Accept","*/*")); try { int statusCode = executeMethodViaThread(client,method); switch (statusCode) { case 502: return "Fetch test had transient 502 error response"; case HttpStatus.SC_UNAUTHORIZED: return "Fetch test returned UNAUTHORIZED (401) response; check the security credentials and configuration"; case HttpStatus.SC_OK: return super.check(); default: return "Fetch test returned an unexpected response code of "+Integer.toString(statusCode); } } catch (InterruptedException e) { throw new ManifoldCFException("Interrupted: "+e.getMessage(),e,ManifoldCFException.INTERRUPTED); } catch (java.net.SocketTimeoutException e) { return "Fetch test timed out reading from the Livelink HTTP Server: "+e.getMessage(); } catch (java.net.SocketException e) { return "Fetch test received a socket error reading from Livelink HTTP Server: "+e.getMessage(); } catch (javax.net.ssl.SSLHandshakeException e) { return "Fetch test was unable to set up a SSL connection to Livelink HTTP Server: "+e.getMessage(); } catch (ConnectTimeoutException e) { return "Fetch test connection timed out reading from Livelink HTTP Server: "+e.getMessage(); } catch (InterruptedIOException e) { throw new ManifoldCFException("Interrupted: "+e.getMessage(),e,ManifoldCFException.INTERRUPTED); } catch (HttpException e) { return "Fetch test had an HTTP exception: "+e.getMessage(); } catch (IOException e) { return "Fetch test had an IO failure: "+e.getMessage(); } } else return super.check(); } catch (ServiceInterruption e) { return "Transient error: "+e.getMessage(); } catch (ManifoldCFException e) { if (e.getErrorCode() == ManifoldCFException.INTERRUPTED) throw e; return "Error: "+e.getMessage(); } } /** This method is periodically called for all connectors that are connected but not * in active use. */ @Override public void poll() throws ManifoldCFException { if (!hasConnected) return; long currentTime = System.currentTimeMillis(); if (currentTime >= expirationTime) { hasConnected = false; expirationTime = -1L; // Shutdown livelink connection if (llServer != null) { llServer.disconnect(); llServer = null; } // Shutdown pool if (connectionManager != null) { connectionManager.shutdown(); connectionManager = null; } } } /** This method is called to assess whether to count this connector instance should * actually be counted as being connected. *@return true if the connector instance is actually connected. */ @Override public boolean isConnected() { return hasConnected; } /** Close the connection. Call this before discarding the repository connector. */ @Override public void disconnect() throws ManifoldCFException { hasSessionParameters = false; hasConnected = false; expirationTime = -1L; if (llServer != null) { llServer.disconnect(); llServer = null; } LLDocs = null; LLAttributes = null; ingestKeystoreManager = null; ingestPortNumber = -1; serverProtocol = null; serverName = null; serverPort = -1; serverUsername = null; serverPassword = null; serverHTTPCgi = null; serverHTTPNTLMDomain = null; serverHTTPNTLMUsername = null; serverHTTPNTLMPassword = null; serverHTTPSKeystore = null; ingestPort = null; ingestProtocol = null; ingestCgiPath = null; viewPort = null; viewServerName = null; viewProtocol = null; viewCgiPath = null; viewBasePath = null; ingestNtlmDomain = null; ingestNtlmUsername = null; ingestNtlmPassword = null; if (connectionManager != null) { connectionManager.shutdown(); connectionManager = null; } super.disconnect(); } /** List the activities we might report on. */ @Override public String[] getActivitiesList() { return activitiesList; } /** Convert a document identifier to a relative URI to read data from. This is not the search URI; that's constructed * by a different method. *@param documentIdentifier is the document identifier. *@return the relative document uri. */ protected String convertToIngestURI(String documentIdentifier) throws ManifoldCFException { // The document identifier is the string form of the object ID for this connector. if (!documentIdentifier.startsWith("D")) return null; int colonPosition = documentIdentifier.indexOf(":",1); if (colonPosition == -1) return ingestCgiPath+"?func=ll&objID="+documentIdentifier.substring(1)+"&objAction=download"; else return ingestCgiPath+"?func=ll&objID="+documentIdentifier.substring(colonPosition+1)+"&objAction=download"; } /** Convert a document identifier to a URI to view. The URI is the URI that will be the unique key from * the search index, and will be presented to the user as part of the search results. It must therefore * be a unique way of describing the document. *@param documentIdentifier is the document identifier. *@return the document uri. */ protected String convertToViewURI(String documentIdentifier) throws ManifoldCFException { // The document identifier is the string form of the object ID for this connector. if (!documentIdentifier.startsWith("D")) return null; int colonPosition = documentIdentifier.indexOf(":",1); if (colonPosition == -1) return viewBasePath+"?func=ll&objID="+documentIdentifier.substring(1)+"&objAction=download"; else return viewBasePath+"?func=ll&objID="+documentIdentifier.substring(colonPosition+1)+"&objAction=download"; } /** Request arbitrary connector information. * This method is called directly from the API in order to allow API users to perform any one of several connector-specific * queries. *@param output is the response object, to be filled in by this method. *@param command is the command, which is taken directly from the API request. *@return true if the resource is found, false if not. In either case, output may be filled in. */ @Override public boolean requestInfo(Configuration output, String command) throws ManifoldCFException { if (command.equals("workspaces")) { try { String[] workspaces = getWorkspaceNames(); int i = 0; while (i < workspaces.length) { String workspace = workspaces[i++]; ConfigurationNode node = new ConfigurationNode("workspace"); node.setValue(workspace); output.addChild(output.getChildCount(),node); } } catch (ServiceInterruption e) { ManifoldCF.createServiceInterruptionNode(output,e); } catch (ManifoldCFException e) { ManifoldCF.createErrorNode(output,e); } } else if (command.startsWith("folders/")) { String path = command.substring("folders/".length()); try { String[] folders = getChildFolderNames(path); int i = 0; while (i < folders.length) { String folder = folders[i++]; ConfigurationNode node = new ConfigurationNode("folder"); node.setValue(folder); output.addChild(output.getChildCount(),node); } } catch (ServiceInterruption e) { ManifoldCF.createServiceInterruptionNode(output,e); } catch (ManifoldCFException e) { ManifoldCF.createErrorNode(output,e); } } else if (command.startsWith("categories/")) { String path = command.substring("categories/".length()); try { String[] categories = getChildCategoryNames(path); int i = 0; while (i < categories.length) { String category = categories[i++]; ConfigurationNode node = new ConfigurationNode("category"); node.setValue(category); output.addChild(output.getChildCount(),node); } } catch (ServiceInterruption e) { ManifoldCF.createServiceInterruptionNode(output,e); } catch (ManifoldCFException e) { ManifoldCF.createErrorNode(output,e); } } else if (command.startsWith("categoryattributes/")) { String path = command.substring("categoryattributes/".length()); try { String[] attributes = getCategoryAttributes(path); int i = 0; while (i < attributes.length) { String attribute = attributes[i++]; ConfigurationNode node = new ConfigurationNode("attribute"); node.setValue(attribute); output.addChild(output.getChildCount(),node); } } catch (ServiceInterruption e) { ManifoldCF.createServiceInterruptionNode(output,e); } catch (ManifoldCFException e) { ManifoldCF.createErrorNode(output,e); } } else return super.requestInfo(output,command); return true; } /** Queue "seed" documents. Seed documents are the starting places for crawling activity. Documents * are seeded when this method calls appropriate methods in the passed in ISeedingActivity object. * * This method can choose to find repository changes that happen only during the specified time interval. * The seeds recorded by this method will be viewed by the framework based on what the * getConnectorModel() method returns. * * It is not a big problem if the connector chooses to create more seeds than are * strictly necessary; it is merely a question of overall work required. * * The end time and seeding version string passed to this method may be interpreted for greatest efficiency. * For continuous crawling jobs, this method will * be called once, when the job starts, and at various periodic intervals as the job executes. * * When a job's specification is changed, the framework automatically resets the seeding version string to null. The * seeding version string may also be set to null on each job run, depending on the connector model returned by * getConnectorModel(). * * Note that it is always ok to send MORE documents rather than less to this method. * The connector will be connected before this method can be called. *@param activities is the interface this method should use to perform whatever framework actions are desired. *@param spec is a document specification (that comes from the job). *@param seedTime is the end of the time range of documents to consider, exclusive. *@param lastSeedVersionString is the last seeding version string for this job, or null if the job has no previous seeding version string. *@param jobMode is an integer describing how the job is being run, whether continuous or once-only. *@return an updated seeding version string, to be stored with the job. */ @Override public String addSeedDocuments(ISeedingActivity activities, Specification spec, String lastSeedVersion, long seedTime, int jobMode) throws ManifoldCFException, ServiceInterruption { getSession(); LivelinkContext llc = new LivelinkContext(); // First, grab the root LLValue ObjectInformation rootValue = llc.getObjectInformation(LLENTWK_VOL,LLENTWK_ID); if (!rootValue.exists()) { // If we get here, it HAS to be a bad network/transient problem. Logging.connectors.warn("Livelink: Could not look up root workspace object during seeding! Retrying -"); throw new ServiceInterruption("Service interruption during seeding",new ManifoldCFException("Could not looking root workspace object during seeding"),System.currentTimeMillis()+60000L, System.currentTimeMillis()+600000L,-1,true); } // Walk the specification for the "startpoint" types. Amalgamate these into a list of strings. // Presume that all roots are startpoint nodes boolean doUserWorkspaces = false; for (int i = 0; i < spec.getChildCount(); i++) { SpecificationNode n = spec.getChild(i); if (n.getType().equals("startpoint")) { // The id returned is simply the node path, which can't be messed up long beginTime = System.currentTimeMillis(); String path = n.getAttributeValue("path"); VolumeAndId vaf = rootValue.getPathId(path); if (vaf != null) { activities.recordActivity(new Long(beginTime),ACTIVITY_SEED,null, path,"OK",null,null); String newID = "F" + new Integer(vaf.getVolumeID()).toString()+":"+ new Integer(vaf.getPathId()).toString(); activities.addSeedDocument(newID); if (Logging.connectors.isDebugEnabled()) Logging.connectors.debug("Livelink: Seed = '"+newID+"'"); } else { activities.recordActivity(new Long(beginTime),ACTIVITY_SEED,null, path,"NOT FOUND",null,null); } } else if (n.getType().equals("userworkspace")) { String value = n.getAttributeValue("value"); if (value != null && value.equals("true")) doUserWorkspaces = true; else if (value != null && value.equals("false")) doUserWorkspaces = false; } if (doUserWorkspaces) { // Do ListUsers and enumerate the values. int sanityRetryCount = FAILURE_RETRY_COUNT; while (true) { ListUsersThread t = new ListUsersThread(); try { t.start(); LLValue childrenDocs; try { childrenDocs = t.finishUp(); } catch (ManifoldCFException e) { sanityRetryCount = assessRetry(sanityRetryCount,e); continue; } int size = 0; if (childrenDocs.isRecord()) size = 1; if (childrenDocs.isTable()) size = childrenDocs.size(); // Do the scan for (int j = 0; j < size; j++) { int childID = childrenDocs.toInteger(j, "ID"); // Skip admin user if (childID == 1000 || childID == 1001) continue; if (Logging.connectors.isDebugEnabled()) Logging.connectors.debug("Livelink: Found a user: ID="+Integer.toString(childID)); activities.addSeedDocument("F0:"+Integer.toString(childID)); } break; } catch (InterruptedException e) { t.interrupt(); throw new ManifoldCFException("Interrupted: "+e.getMessage(),e,ManifoldCFException.INTERRUPTED); } catch (RuntimeException e) { sanityRetryCount = handleLivelinkRuntimeException(e,sanityRetryCount,true); continue; } } } } return ""; } /** Process a set of documents. * This is the method that should cause each document to be fetched, processed, and the results either added * to the queue of documents for the current job, and/or entered into the incremental ingestion manager. * The document specification allows this class to filter what is done based on the job. * The connector will be connected before this method can be called. *@param documentIdentifiers is the set of document identifiers to process. *@param statuses are the currently-stored document versions for each document in the set of document identifiers * passed in above. *@param activities is the interface this method should use to queue up new document references * and ingest documents. *@param jobMode is an integer describing how the job is being run, whether continuous or once-only. *@param usesDefaultAuthority will be true only if the authority in use for these documents is the default one. */ @Override public void processDocuments(String[] documentIdentifiers, IExistingVersions statuses, Specification spec, IProcessActivity activities, int jobMode, boolean usesDefaultAuthority) throws ManifoldCFException, ServiceInterruption { // Initialize a "livelink context", to minimize the number of objects we have to fetch LivelinkContext llc = new LivelinkContext(); // Initialize the table of catid's. // Keeping this around will allow us to benefit from batching of documents. MetadataDescription desc = new MetadataDescription(llc); // First, process the spec to get the string we tack on SystemMetadataDescription sDesc = new SystemMetadataDescription(llc,spec); // Read the forced acls. A null return indicates that security is disabled!!! // A zero-length return indicates that the native acls should be used. // All of this is germane to how we ingest the document, so we need to note it in // the version string completely. String[] acls = sDesc.getAcls(); // Sort it, in case it is needed. if (acls != null) java.util.Arrays.sort(acls); // Prepare the specified metadata String metadataString = null; String[] specifiedMetadataAttributes = null; CategoryPathAccumulator catAccum = null; if (!sDesc.includeAllMetadata()) { StringBuilder sb = new StringBuilder(); specifiedMetadataAttributes = sDesc.getMetadataAttributes(); // Sort! java.util.Arrays.sort(specifiedMetadataAttributes); // Build the metadata string piece now packList(sb,specifiedMetadataAttributes,'+'); metadataString = sb.toString(); } else catAccum = new CategoryPathAccumulator(llc); // Calculate the part of the version string that comes from path name and mapping. // This starts with = since ; is used by another optional component (the forced acls) String pathNameAttributeVersion; StringBuilder sb2 = new StringBuilder(); if (sDesc.getPathAttributeName() != null) sb2.append("=").append(sDesc.getPathAttributeName()).append(":").append(sDesc.getPathSeparator()).append(":").append(sDesc.getMatchMapString()); pathNameAttributeVersion = sb2.toString(); // Since the identifier indicates it is a directory, then queue up all the current children which pass the filter. String filterString = sDesc.getFilterString(); for (String documentIdentifier : documentIdentifiers) { // Since each livelink access is time-consuming, be sure that we abort if the job has gone inactive activities.checkJobStillActive(); // Read the document or folder metadata, which includes the ModifyDate String docID = documentIdentifier; boolean isFolder = docID.startsWith("F"); int colonPos = docID.indexOf(":",1); int objID; int vol; if (colonPos == -1) { objID = new Integer(docID.substring(1)).intValue(); vol = LLENTWK_VOL; } else { objID = new Integer(docID.substring(colonPos+1)).intValue(); vol = new Integer(docID.substring(1,colonPos)).intValue(); } getSession(); ObjectInformation value = llc.getObjectInformation(vol,objID); if (!value.exists()) { if (Logging.connectors.isDebugEnabled()) Logging.connectors.debug("Livelink: Object "+Integer.toString(vol)+":"+Integer.toString(objID)+" has no information - deleting"); activities.deleteDocument(documentIdentifier); continue; } // Make sure we have permission to see the object's contents int permissions = value.getPermissions().intValue(); if ((permissions & LAPI_DOCUMENTS.PERM_SEECONTENTS) == 0) { if (Logging.connectors.isDebugEnabled()) Logging.connectors.debug("Livelink: Crawl user cannot see contents of object "+Integer.toString(vol)+":"+Integer.toString(objID)+" - deleting"); activities.deleteDocument(documentIdentifier); continue; } Date dt = value.getModifyDate(); // The rights don't change when the object changes, so we have to include those too. int[] rights = getObjectRights(vol,objID); if (rights == null) { if (Logging.connectors.isDebugEnabled()) Logging.connectors.debug("Livelink: Could not get rights for object "+Integer.toString(vol)+":"+Integer.toString(objID)+" - deleting"); activities.deleteDocument(documentIdentifier); continue; } // We were able to get rights, so object still exists. // Changed folder versioning for MCF 2.0 if (isFolder) { // === Livelink folder === // I'm still not sure if Livelink folder modified dates are one-level or hierarchical. // The code below assumes one-level only, so we always scan folders and there's no versioning if (Logging.connectors.isDebugEnabled()) Logging.connectors.debug("Livelink: Processing folder "+Integer.toString(vol)+":"+Integer.toString(objID)); int sanityRetryCount = FAILURE_RETRY_COUNT; while (true) { ListObjectsThread t = new ListObjectsThread(vol,objID,filterString); try { t.start(); LLValue childrenDocs; try { childrenDocs = t.finishUp(); } catch (ManifoldCFException e) { sanityRetryCount = assessRetry(sanityRetryCount,e); continue; } int size = 0; if (childrenDocs.isRecord()) size = 1; if (childrenDocs.isTable()) size = childrenDocs.size(); // System.out.println("Total child count = "+Integer.toString(size)); // Do the scan for (int j = 0; j < size; j++) { int childID = childrenDocs.toInteger(j, "ID"); if (Logging.connectors.isDebugEnabled()) Logging.connectors.debug("Livelink: Found a child of folder "+Integer.toString(vol)+":"+Integer.toString(objID)+" : ID="+Integer.toString(childID)); int subtype = childrenDocs.toInteger(j, "SubType"); boolean childIsFolder = (subtype == LAPI_DOCUMENTS.FOLDERSUBTYPE || subtype == LAPI_DOCUMENTS.PROJECTSUBTYPE || subtype == LAPI_DOCUMENTS.COMPOUNDDOCUMENTSUBTYPE); // If it's a folder, we just let it through for now if (!childIsFolder && checkInclude(childrenDocs.toString(j,"Name") + "." + childrenDocs.toString(j,"FileType"), spec) == false) { if (Logging.connectors.isDebugEnabled()) Logging.connectors.debug("Livelink: Child identifier "+Integer.toString(childID)+" was excluded by inclusion criteria"); continue; } if (childIsFolder) { if (Logging.connectors.isDebugEnabled()) Logging.connectors.debug("Livelink: Child identifier "+Integer.toString(childID)+" is a folder, project, or compound document; adding a reference"); if (subtype == LAPI_DOCUMENTS.PROJECTSUBTYPE) { // If we pick up a project object, we need to describe the volume object (which // will be the root of all documents beneath) activities.addDocumentReference("F"+new Integer(childID).toString()+":"+new Integer(-childID).toString()); } else activities.addDocumentReference("F"+new Integer(vol).toString()+":"+new Integer(childID).toString()); } else { if (Logging.connectors.isDebugEnabled()) Logging.connectors.debug("Livelink: Child identifier "+Integer.toString(childID)+" is a simple document; adding a reference"); activities.addDocumentReference("D"+new Integer(vol).toString()+":"+new Integer(childID).toString()); } } break; } catch (InterruptedException e) { t.interrupt(); throw new ManifoldCFException("Interrupted: "+e.getMessage(),e,ManifoldCFException.INTERRUPTED); } catch (RuntimeException e) { sanityRetryCount = handleLivelinkRuntimeException(e,sanityRetryCount,true); continue; } } if (Logging.connectors.isDebugEnabled()) Logging.connectors.debug("Livelink: Done processing folder "+Integer.toString(vol)+":"+Integer.toString(objID)); } else { // === Livelink document === // The version string includes the following: // 1) The modify date for the document // 2) The rights for the document, ordered (which can change without changing the ModifyDate field) // 3) The requested metadata fields (category and attribute, ordered) for the document // // The document identifiers are object id's. StringBuilder sb = new StringBuilder(); String[] categoryPaths; if (sDesc.includeAllMetadata()) { // Find all the metadata associated with this object, and then // find the set of category pathnames that correspond to it. int[] catIDs = getObjectCategoryIDs(vol,objID); categoryPaths = catAccum.getCategoryPathsAttributeNames(catIDs); // Sort! java.util.Arrays.sort(categoryPaths); // Build the metadata string piece now packList(sb,categoryPaths,'+'); } else { categoryPaths = specifiedMetadataAttributes; sb.append(metadataString); } String[] actualAcls; String[] denyAcls; String denyAcl; if (acls != null && acls.length == 0) { // No forced acls. Read the actual acls from livelink, as a set of rights. // We need also to add in support for the special rights objects. These are: // -1: RIGHT_WORLD // -2: RIGHT_SYSTEM // -3: RIGHT_OWNER // -4: RIGHT_GROUP // // RIGHT_WORLD means guest access. // RIGHT_SYSTEM is "Public Access". // RIGHT_OWNER is access by the owner of the object. // RIGHT_GROUP is access by a member of the base group containing the owner // // These objects are returned by the GetObjectRights() call made above, and NOT // returned by LLUser.ListObjects(). We have to figure out how to map these to // things that are // the equivalent of acls. actualAcls = lookupTokens(rights, value); java.util.Arrays.sort(actualAcls); // If security is on, no deny acl is needed for the local authority, since the repository does not support "deny". But this was added // to be really really really sure. denyAcl = defaultAuthorityDenyToken; } else if (acls != null && acls.length > 0) { // Forced acls actualAcls = acls; denyAcl = defaultAuthorityDenyToken; } else { // Security is OFF actualAcls = acls; denyAcl = null; } // Now encode the acls. If null, we write a special value. if (actualAcls == null) { sb.append('-'); denyAcls = null; } else { sb.append('+'); packList(sb,actualAcls,'+'); // This was added on 4/21/2008 to support forced acls working with the global default authority. pack(sb,denyAcl,'+'); denyAcls = new String[]{denyAcl}; } // The date does not need to be parseable sb.append(new Long(dt.getTime()).toString()); // PathNameAttributeVersion comes completely from the spec, so we don't // have to worry about it changing. No need, therefore, to parse it during // processDocuments. sb.append("=").append(pathNameAttributeVersion); // Tack on ingestCgiPath, to insulate us against changes to the repository connection setup. Added 9/7/07. sb.append("_").append(viewBasePath); String versionString = sb.toString(); if (Logging.connectors.isDebugEnabled()) Logging.connectors.debug("Livelink: Successfully calculated version string for document "+Integer.toString(vol)+":"+Integer.toString(objID)+" : '"+versionString+"'"); if (!activities.checkDocumentNeedsReindexing(documentIdentifier,versionString)) continue; // Index the document if (Logging.connectors.isDebugEnabled()) Logging.connectors.debug("Livelink: Processing document "+Integer.toString(vol)+":"+Integer.toString(objID)); if (!checkIngest(llc,objID,spec)) { if (Logging.connectors.isDebugEnabled()) Logging.connectors.debug("Livelink: Decided not to ingest document "+Integer.toString(vol)+":"+Integer.toString(objID)+" - Did not match ingestion criteria"); activities.noDocument(documentIdentifier,versionString); continue; } if (Logging.connectors.isDebugEnabled()) Logging.connectors.debug("Livelink: Decided to ingest document "+Integer.toString(vol)+":"+Integer.toString(objID)); // Grab the access tokens for this file from the version string, inside ingest method. ingestFromLiveLink(llc,documentIdentifier,versionString,actualAcls,denyAcls,categoryPaths,activities,desc,sDesc); if (Logging.connectors.isDebugEnabled()) Logging.connectors.debug("Livelink: Done processing document "+Integer.toString(vol)+":"+Integer.toString(objID)); } } } protected class ListObjectsThread extends Thread { protected final int vol; protected final int objID; protected final String filterString; protected Throwable exception = null; protected LLValue rval = null; public ListObjectsThread(int vol, int objID, String filterString) { super(); setDaemon(true); this.vol = vol; this.objID = objID; this.filterString = filterString; } public void run() { try { LLValue childrenDocs = new LLValue(); int status = LLDocs.ListObjects(vol, objID, null, filterString, LAPI_DOCUMENTS.PERM_SEECONTENTS, childrenDocs); if (status != 0) { throw new ManifoldCFException("Error retrieving contents of folder "+Integer.toString(vol)+":"+Integer.toString(objID)+" : Status="+Integer.toString(status)+" ("+llServer.getErrors()+")"); } rval = childrenDocs; } catch (Throwable e) { this.exception = e; } } public LLValue finishUp() throws ManifoldCFException, InterruptedException { join(); Throwable thr = exception; if (thr != null) { if (thr instanceof RuntimeException) throw (RuntimeException)thr; else if (thr instanceof ManifoldCFException) throw (ManifoldCFException)thr; else if (thr instanceof Error) throw (Error)thr; else throw new RuntimeException("Unrecognized exception type: "+thr.getClass().getName()+": "+thr.getMessage(),thr); } return rval; } } /** Get the maximum number of documents to amalgamate together into one batch, for this connector. *@return the maximum number. 0 indicates "unlimited". */ @Override public int getMaxDocumentRequest() { // Intrinsically, Livelink doesn't batch well. Multiple chunks have no advantage over one-at-a-time requests, // since apparently the Livelink API does not support multiples. HOWEVER - when metadata is considered, // it becomes worthwhile, because we will be able to do what is needed to look up the correct CATID node // only once per n requests! So it's a tradeoff between the advantage gained by threading, and the // savings gained by CATID lookup. // Note that at Shell, the fact that the network hiccups a lot makes it better to choose a smaller value. return 6; } // UI support methods. // // These support methods come in two varieties. The first bunch is involved in setting up connection configuration information. The second bunch // is involved in presenting and editing document specification information for a job. The two kinds of methods are accordingly treated differently, // in that the first bunch cannot assume that the current connector object is connected, while the second bunch can. That is why the first bunch // receives a thread context argument for all UI methods, while the second bunch does not need one (since it has already been applied via the connect() // method, above). /** Output the configuration header section. * This method is called in the head section of the connector's configuration page. Its purpose is to add the required tabs to the list, and to output any * javascript methods that might be needed by the configuration editing HTML. *@param threadContext is the local thread context. *@param out is the output to which any HTML should be sent. *@param parameters are the configuration parameters, as they currently exist, for this connection being configured. *@param tabsArray is an array of tab names. Add to this array any tab names that are specific to the connector. */ @Override public void outputConfigurationHeader(IThreadContext threadContext, IHTTPOutput out, Locale locale, ConfigParams parameters, List<String> tabsArray) throws ManifoldCFException, IOException { tabsArray.add(Messages.getString(locale,"LivelinkConnector.Server")); tabsArray.add(Messages.getString(locale,"LivelinkConnector.DocumentAccess")); tabsArray.add(Messages.getString(locale,"LivelinkConnector.DocumentView")); out.print( "<script type=\"text/javascript\">\n"+ "<!--\n"+ "function ServerDeleteCertificate(aliasName)\n"+ "{\n"+ " editconnection.serverkeystorealias.value = aliasName;\n"+ " editconnection.serverconfigop.value = \"Delete\";\n"+ " postForm();\n"+ "}\n"+ "\n"+ "function ServerAddCertificate()\n"+ "{\n"+ " if (editconnection.servercertificate.value == \"\")\n"+ " {\n"+ " alert(\""+Messages.getBodyJavascriptString(locale,"LivelinkConnector.ChooseACertificateFile")+"\");\n"+ " editconnection.servercertificate.focus();\n"+ " }\n"+ " else\n"+ " {\n"+ " editconnection.serverconfigop.value = \"Add\";\n"+ " postForm();\n"+ " }\n"+ "}\n"+ "\n"+ "function IngestDeleteCertificate(aliasName)\n"+ "{\n"+ " editconnection.ingestkeystorealias.value = aliasName;\n"+ " editconnection.ingestconfigop.value = \"Delete\";\n"+ " postForm();\n"+ "}\n"+ "\n"+ "function IngestAddCertificate()\n"+ "{\n"+ " if (editconnection.ingestcertificate.value == \"\")\n"+ " {\n"+ " alert(\""+Messages.getBodyJavascriptString(locale,"LivelinkConnector.ChooseACertificateFile")+"\");\n"+ " editconnection.ingestcertificate.focus();\n"+ " }\n"+ " else\n"+ " {\n"+ " editconnection.ingestconfigop.value = \"Add\";\n"+ " postForm();\n"+ " }\n"+ "}\n"+ "\n"+ "function checkConfig()\n"+ "{\n"+ " if (editconnection.serverport.value != \"\" && !isInteger(editconnection.serverport.value))\n"+ " {\n"+ " alert(\""+Messages.getBodyJavascriptString(locale,"LivelinkConnector.AValidNumberIsRequired")+"\");\n"+ " editconnection.serverport.focus();\n"+ " return false;\n"+ " }\n"+ " if (editconnection.ingestport.value != \"\" && !isInteger(editconnection.ingestport.value))\n"+ " {\n"+ " alert(\""+Messages.getBodyJavascriptString(locale,"LivelinkConnector.AValidNumberOrBlankIsRequired")+"\");\n"+ " editconnection.ingestport.focus();\n"+ " return false;\n"+ " }\n"+ " if (editconnection.viewport.value != \"\" && !isInteger(editconnection.viewport.value))\n"+ " {\n"+ " alert(\""+Messages.getBodyJavascriptString(locale,"LivelinkConnector.AValidNumberOrBlankIsRequired")+"\");\n"+ " editconnection.viewport.focus();\n"+ " return false;\n"+ " }\n"+ " return true;\n"+ "}\n"+ "\n"+ "function checkConfigForSave()\n"+ "{\n"+ " if (editconnection.servername.value == \"\")\n"+ " {\n"+ " alert(\""+Messages.getBodyJavascriptString(locale,"LivelinkConnector.EnterALivelinkServerName")+"\");\n"+ " SelectTab(\"" + Messages.getBodyJavascriptString(locale,"LivelinkConnector.Server") + "\");\n"+ " editconnection.servername.focus();\n"+ " return false;\n"+ " }\n"+ " if (editconnection.serverport.value == \"\")\n"+ " {\n"+ " alert(\""+Messages.getBodyJavascriptString(locale,"LivelinkConnector.AServerPortNumberIsRequired")+"\");\n"+ " SelectTab(\"" + Messages.getBodyJavascriptString(locale,"LivelinkConnector.Server") + "\");\n"+ " editconnection.serverport.focus();\n"+ " return false;\n"+ " }\n"+ " if (editconnection.serverhttpcgipath.value == \"\")\n"+ " {\n"+ " alert(\""+Messages.getBodyJavascriptString(locale,"LivelinkConnector.EnterTheServerCgiPathToLivelink")+"\");\n"+ " SelectTab(\"" + Messages.getBodyJavascriptString(locale,"LivelinkConnector.Server") + "\");\n"+ " editconnection.serverhttpcgipath.focus();\n"+ " return false;\n"+ " }\n"+ " if (editconnection.serverhttpcgipath.value.substring(0,1) != \"/\")\n"+ " {\n"+ " alert(\""+Messages.getBodyJavascriptString(locale,"LivelinkConnector.TheServerCgiPathMustBeginWithACharacter")+"\");\n"+ " SelectTab(\"" + Messages.getBodyJavascriptString(locale,"LivelinkConnector.Server") + "\");\n"+ " editconnection.serverhttpcgipath.focus();\n"+ " return false;\n"+ " }\n"+ " if (editconnection.viewprotocol.value == \"\" && editconnection.ingestprotocol.value == \"\")\n"+ " {\n"+ " alert(\""+Messages.getBodyJavascriptString(locale,"LivelinkConnector.SelectAViewProtocol")+"\");\n"+ " SelectTab(\"" + Messages.getBodyJavascriptString(locale,"LivelinkConnector.DocumentView") + "\");\n"+ " editconnection.viewprotocol.focus();\n"+ " return false;\n"+ " }\n"+ " if (editconnection.viewcgipath.value == \"\" && editconnection.ingestcgipath.value == \"\")\n"+ " {\n"+ " alert(\""+Messages.getBodyJavascriptString(locale,"LivelinkConnector.EnterTheViewCgiPathToLivelink")+"\");\n"+ " SelectTab(\"" + Messages.getBodyJavascriptString(locale,"LivelinkConnector.DocumentView") + "\");\n"+ " editconnection.viewcgipath.focus();\n"+ " return false;\n"+ " }\n"+ " if (editconnection.ingestcgipath.value != \"\" && editconnection.ingestcgipath.value.substring(0,1) != \"/\")\n"+ " {\n"+ " alert(\""+Messages.getBodyJavascriptString(locale,"LivelinkConnector.TheIngestCgiPathMustBeBlankOrBeginWithACharacter")+"\");\n"+ " SelectTab(\"" + Messages.getBodyJavascriptString(locale,"LivelinkConnector.DocumentAccess") + "\");\n"+ " editconnection.ingestcgipath.focus();\n"+ " return false;\n"+ " }\n"+ " if (editconnection.viewcgipath.value != \"\" && editconnection.viewcgipath.value.substring(0,1) != \"/\")\n"+ " {\n"+ " alert(\""+Messages.getBodyJavascriptString(locale,"LivelinkConnector.TheViewCgiPathMustBeBlankOrBeginWithACharacter")+"\");\n"+ " SelectTab(\"" + Messages.getBodyJavascriptString(locale,"LivelinkConnector.DocumentView") + "\");\n"+ " editconnection.viewcgipath.focus();\n"+ " return false;\n"+ " }\n"+ " return true;\n"+ "}\n"+ "\n"+ "//-->\n"+ "</script>\n" ); } /** Output the configuration body section. * This method is called in the body section of the connector's configuration page. Its purpose is to present the required form elements for editing. * The coder can presume that the HTML that is output from this configuration will be within appropriate <html>, <body>, and <form> tags. The name of the * form is "editconnection". *@param threadContext is the local thread context. *@param out is the output to which any HTML should be sent. *@param parameters are the configuration parameters, as they currently exist, for this connection being configured. *@param tabName is the current tab name. */ @Override public void outputConfigurationBody(IThreadContext threadContext, IHTTPOutput out, Locale locale, ConfigParams parameters, String tabName) throws ManifoldCFException, IOException { // LAPI parameters String serverProtocol = parameters.getParameter(LiveLinkParameters.serverProtocol); if (serverProtocol == null) serverProtocol = "internal"; String serverName = parameters.getParameter(LiveLinkParameters.serverName); if (serverName == null) serverName = "localhost"; String serverPort = parameters.getParameter(LiveLinkParameters.serverPort); if (serverPort == null) serverPort = "2099"; String serverUserName = parameters.getParameter(LiveLinkParameters.serverUsername); if (serverUserName == null) serverUserName = ""; String serverPassword = parameters.getObfuscatedParameter(LiveLinkParameters.serverPassword); if (serverPassword == null) serverPassword = ""; else serverPassword = out.mapPasswordToKey(serverPassword); String serverHTTPCgiPath = parameters.getParameter(LiveLinkParameters.serverHTTPCgiPath); if (serverHTTPCgiPath == null) serverHTTPCgiPath = "/livelink/livelink.exe"; String serverHTTPNTLMDomain = parameters.getParameter(LiveLinkParameters.serverHTTPNTLMDomain); if (serverHTTPNTLMDomain == null) serverHTTPNTLMDomain = ""; String serverHTTPNTLMUserName = parameters.getParameter(LiveLinkParameters.serverHTTPNTLMUsername); if (serverHTTPNTLMUserName == null) serverHTTPNTLMUserName = ""; String serverHTTPNTLMPassword = parameters.getObfuscatedParameter(LiveLinkParameters.serverHTTPNTLMPassword); if (serverHTTPNTLMPassword == null) serverHTTPNTLMPassword = ""; else serverHTTPNTLMPassword = out.mapPasswordToKey(serverHTTPNTLMPassword); String serverHTTPSKeystore = parameters.getParameter(LiveLinkParameters.serverHTTPSKeystore); IKeystoreManager localServerHTTPSKeystore; if (serverHTTPSKeystore == null) localServerHTTPSKeystore = KeystoreManagerFactory.make(""); else localServerHTTPSKeystore = KeystoreManagerFactory.make("",serverHTTPSKeystore); // Document access parameters String ingestProtocol = parameters.getParameter(LiveLinkParameters.ingestProtocol); if (ingestProtocol == null) ingestProtocol = ""; String ingestPort = parameters.getParameter(LiveLinkParameters.ingestPort); if (ingestPort == null) ingestPort = ""; String ingestCgiPath = parameters.getParameter(LiveLinkParameters.ingestCgiPath); if (ingestCgiPath == null) ingestCgiPath = ""; String ingestNtlmUsername = parameters.getParameter(LiveLinkParameters.ingestNtlmUsername); if (ingestNtlmUsername == null) ingestNtlmUsername = ""; String ingestNtlmPassword = parameters.getObfuscatedParameter(LiveLinkParameters.ingestNtlmPassword); if (ingestNtlmPassword == null) ingestNtlmPassword = ""; else ingestNtlmPassword = out.mapPasswordToKey(ingestNtlmPassword); String ingestNtlmDomain = parameters.getParameter(LiveLinkParameters.ingestNtlmDomain); if (ingestNtlmDomain == null) ingestNtlmDomain = ""; String ingestKeystore = parameters.getParameter(LiveLinkParameters.ingestKeystore); IKeystoreManager localIngestKeystore; if (ingestKeystore == null) localIngestKeystore = KeystoreManagerFactory.make(""); else localIngestKeystore = KeystoreManagerFactory.make("",ingestKeystore); // Document view parameters String viewProtocol = parameters.getParameter(LiveLinkParameters.viewProtocol); if (viewProtocol == null) viewProtocol = "http"; String viewServerName = parameters.getParameter(LiveLinkParameters.viewServerName); if (viewServerName == null) viewServerName = ""; String viewPort = parameters.getParameter(LiveLinkParameters.viewPort); if (viewPort == null) viewPort = ""; String viewCgiPath = parameters.getParameter(LiveLinkParameters.viewCgiPath); if (viewCgiPath == null) viewCgiPath = "/livelink/livelink.exe"; // The "Server" tab // Always pass the whole keystore as a hidden. out.print( "<input name=\"serverconfigop\" type=\"hidden\" value=\"Continue\"/>\n" ); if (serverHTTPSKeystore != null) { out.print( "<input type=\"hidden\" name=\"serverhttpskeystoredata\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(serverHTTPSKeystore)+"\"/>\n" ); } if (tabName.equals(Messages.getString(locale,"LivelinkConnector.Server"))) { out.print( "<table class=\"displaytable\">\n"+ " <tr><td class=\"separator\" colspan=\"2\"><hr/></td></tr>\n"+ " <tr>\n"+ " <td class=\"description\">"+Messages.getBodyString(locale,"LivelinkConnector.ServerProtocol")+"</td>\n"+ " <td class=\"value\">\n"+ " <select name=\"serverprotocol\" size=\"2\">\n"+ " <option value=\"internal\" "+((serverProtocol.equals("internal"))?"selected=\"selected\"":"")+">"+Messages.getBodyString(locale,"LivelinkConnector.internal")+"</option>\n"+ " <option value=\"http\" "+((serverProtocol.equals("http"))?"selected=\"selected\"":"")+">http</option>\n"+ " <option value=\"https\" "+((serverProtocol.equals("https"))?"selected=\"selected\"":"")+">https</option>\n"+ " </select>\n"+ " </td>\n"+ " </tr>\n"+ " <tr>\n"+ " <td class=\"description\"><nobr>"+Messages.getBodyString(locale,"LivelinkConnector.ServerName")+"</nobr></td>\n"+ " <td class=\"value\"><input type=\"text\" size=\"64\" name=\"servername\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(serverName)+"\"/></td>\n"+ " </tr>\n"+ " <tr>\n"+ " <td class=\"description\"><nobr>"+Messages.getBodyString(locale,"LivelinkConnector.ServerPort")+"</nobr></td>\n"+ " <td class=\"value\"><input type=\"text\" size=\"5\" name=\"serverport\" value=\""+serverPort+"\"/></td>\n"+ " </tr>\n"+ " <tr>\n"+ " <td class=\"description\"><nobr>"+Messages.getBodyString(locale,"LivelinkConnector.ServerUserName")+"</nobr></td>\n"+ " <td class=\"value\"><input type=\"text\" size=\"32\" name=\"serverusername\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(serverUserName)+"\"/></td>\n"+ " </tr>\n"+ " <tr>\n"+ " <td class=\"description\"><nobr>"+Messages.getBodyString(locale,"LivelinkConnector.ServerPassword")+"</nobr></td>\n"+ " <td class=\"value\"><input type=\"password\" size=\"32\" name=\"serverpassword\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(serverPassword)+"\"/></td>\n"+ " </tr>\n"+ " <tr><td class=\"separator\" colspan=\"2\"><hr/></td></tr>\n"+ " <tr>\n"+ " <td class=\"description\"><nobr>"+Messages.getBodyString(locale,"LivelinkConnector.ServerHTTPCGIPath")+"</nobr></td>\n"+ " <td class=\"value\"><input type=\"text\" size=\"32\" name=\"serverhttpcgipath\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(serverHTTPCgiPath)+"\"/></td>\n"+ " </tr>\n"+ " <tr>\n"+ " <td class=\"description\"><nobr>"+Messages.getBodyString(locale,"LivelinkConnector.ServerHTTPNTLMDomain")+"</nobr><br/><nobr>"+Messages.getBodyString(locale,"LivelinkConnector.SetIfNTLMAuthDesired")+"</nobr></td>\n"+ " <td class=\"value\">\n"+ " <input type=\"text\" size=\"32\" name=\"serverhttpntlmdomain\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(serverHTTPNTLMDomain)+"\"/>\n"+ " </td>\n"+ " </tr>\n"+ " <tr>\n"+ " <td class=\"description\"><nobr>"+Messages.getBodyString(locale,"LivelinkConnector.ServerHTTPNTLMUserName")+"</nobr></td>\n"+ " <td class=\"value\">\n"+ " <input type=\"text\" size=\"32\" name=\"serverhttpntlmusername\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(serverHTTPNTLMUserName)+"\"/>\n"+ " </td>\n"+ " </tr>\n"+ " <tr>\n"+ " <td class=\"description\"><nobr>"+Messages.getBodyString(locale,"LivelinkConnector.ServerHTTPNTLMPassword")+"</nobr></td>\n"+ " <td class=\"value\">\n"+ " <input type=\"password\" size=\"32\" name=\"serverhttpntlmpassword\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(serverHTTPNTLMPassword)+"\"/>\n"+ " </td>\n"+ " </tr>\n"+ " <tr><td class=\"separator\" colspan=\"2\"><hr/></td></tr>\n" ); out.print( " <tr>\n"+ " <td class=\"description\"><nobr>"+Messages.getBodyString(locale,"LivelinkConnector.ServerSSLCertificateList")+"</nobr></td>\n"+ " <td class=\"value\">\n"+ " <input type=\"hidden\" name=\"serverkeystorealias\" value=\"\"/>\n"+ " <table class=\"displaytable\">\n" ); // List the individual certificates in the store, with a delete button for each String[] contents = localServerHTTPSKeystore.getContents(); if (contents.length == 0) { out.print( " <tr><td class=\"message\" colspan=\"2\"><nobr>"+Messages.getBodyString(locale,"LivelinkConnector.NoCertificatesPresent")+"</nobr></td></tr>\n" ); } else { int i = 0; while (i < contents.length) { String alias = contents[i]; String description = localServerHTTPSKeystore.getDescription(alias); if (description.length() > 128) description = description.substring(0,125) + "..."; out.print( " <tr>\n"+ " <td class=\"value\"><input type=\"button\" onclick='Javascript:ServerDeleteCertificate(\""+org.apache.manifoldcf.ui.util.Encoder.attributeJavascriptEscape(alias)+"\")' alt=\""+Messages.getAttributeString(locale,"LivelinkConnector.DeleteCert")+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(alias)+"\" value=\""+Messages.getAttributeString(locale,"LivelinkConnector.Delete")+"\"/></td>\n"+ " <td>"+org.apache.manifoldcf.ui.util.Encoder.bodyEscape(description)+"</td>\n"+ " </tr>\n" ); i++; } } out.print( " </table>\n"+ " <input type=\"button\" onclick='Javascript:ServerAddCertificate()' alt=\""+Messages.getAttributeString(locale,"LivelinkConnector.AddCert")+"\" value=\""+Messages.getAttributeString(locale,"LivelinkConnector.Add")+"\"/>&nbsp;\n"+ " "+Messages.getBodyString(locale,"LivelinkConnector.Certificate")+"<input name=\"servercertificate\" size=\"50\" type=\"file\"/>\n"+ " </td>\n"+ " </tr>\n" ); out.print( "</table>\n" ); } else { // Hiddens for Server tab out.print( "<input type=\"hidden\" name=\"serverprotocol\" value=\""+serverProtocol+"\"/>\n"+ "<input type=\"hidden\" name=\"servername\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(serverName)+"\"/>\n"+ "<input type=\"hidden\" name=\"serverport\" value=\""+serverPort+"\"/>\n"+ "<input type=\"hidden\" name=\"serverusername\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(serverUserName)+"\"/>\n"+ "<input type=\"hidden\" name=\"serverpassword\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(serverPassword)+"\"/>\n"+ "<input type=\"hidden\" name=\"serverhttpcgipath\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(serverHTTPCgiPath)+"\"/>\n"+ "<input type=\"hidden\" name=\"serverhttpntlmdomain\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(serverHTTPNTLMDomain)+"\"/>\n"+ "<input type=\"hidden\" name=\"serverhttpntlmusername\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(serverHTTPNTLMUserName)+"\"/>\n"+ "<input type=\"hidden\" name=\"serverhttpntlmpassword\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(serverHTTPNTLMPassword)+"\"/>\n" ); } // The "Document Access" tab // Always pass the whole keystore as a hidden. out.print( "<input name=\"ingestconfigop\" type=\"hidden\" value=\"Continue\"/>\n" ); if (ingestKeystore != null) { out.print( "<input type=\"hidden\" name=\"ingestkeystoredata\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(ingestKeystore)+"\"/>\n" ); } if (tabName.equals(Messages.getString(locale,"LivelinkConnector.DocumentAccess"))) { out.print( "<table class=\"displaytable\">\n"+ " <tr><td class=\"separator\" colspan=\"2\"><hr/></td></tr>\n"+ " <tr>\n"+ " <td class=\"description\">"+Messages.getBodyString(locale,"LivelinkConnector.DocumentFetchProtocol")+"</td>\n"+ " <td class=\"value\">\n"+ " <select name=\"ingestprotocol\" size=\"3\">\n"+ " <option value=\"\" "+((ingestProtocol.equals(""))?"selected=\"selected\"":"")+">"+Messages.getBodyString(locale,"LivelinkConnector.UseLAPI")+"</option>\n"+ " <option value=\"http\" "+((ingestProtocol.equals("http"))?"selected=\"selected\"":"")+">http</option>\n"+ " <option value=\"https\" "+((ingestProtocol.equals("https"))?"selected=\"selected\"":"")+">https</option>\n"+ " </select>\n"+ " </td>\n"+ " </tr>\n"+ " <tr>\n"+ " <td class=\"description\"><nobr>"+Messages.getBodyString(locale,"LivelinkConnector.DocumentFetchPort")+"</nobr></td>\n"+ " <td class=\"value\"><input type=\"text\" size=\"5\" name=\"ingestport\" value=\""+ingestPort+"\"/></td>\n"+ " </tr>\n"+ " <tr><td class=\"separator\" colspan=\"2\"><hr/></td></tr>\n"+ " <tr>\n"+ " <td class=\"description\"><nobr>"+Messages.getBodyString(locale,"LivelinkConnector.DocumentFetchCGIPath")+"</nobr></td>\n"+ " <td class=\"value\"><input type=\"text\" size=\"32\" name=\"ingestcgipath\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(ingestCgiPath)+"\"/></td>\n"+ " </tr>\n"+ " <tr>\n"+ " <td class=\"description\"><nobr>"+Messages.getBodyString(locale,"LivelinkConnector.DocumentFetchNTLMDomain")+"</nobr><br/><nobr>"+Messages.getBodyString(locale,"LivelinkConnector.SetIfNTLMAuthDesired")+"</nobr></td>\n"+ " <td class=\"value\">\n"+ " <input type=\"text\" size=\"32\" name=\"ingestntlmdomain\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(ingestNtlmDomain)+"\"/>\n"+ " </td>\n"+ " </tr>\n"+ " <tr>\n"+ " <td class=\"description\"><nobr>"+Messages.getBodyString(locale,"LivelinkConnector.DocumentFetchNTLMUserName")+"</nobr><br/><nobr>"+Messages.getBodyString(locale,"LivelinkConnector.SetIfDifferentFromServerUserName")+"</nobr></td>\n"+ " <td class=\"value\">\n"+ " <input type=\"text\" size=\"32\" name=\"ingestntlmusername\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(ingestNtlmUsername)+"\"/>\n"+ " </td>\n"+ " </tr>\n"+ " <tr>\n"+ " <td class=\"description\"><nobr>"+Messages.getBodyString(locale,"LivelinkConnector.DocumentFetchNTLMPassword")+"</nobr><br/><nobr>"+Messages.getBodyString(locale,"LivelinkConnector.SetIfDifferentFromServerPassword")+"</nobr></td>\n"+ " <td class=\"value\">\n"+ " <input type=\"password\" size=\"32\" name=\"ingestntlmpassword\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(ingestNtlmPassword)+"\"/>\n"+ " </td>\n"+ " </tr>\n"+ " <tr><td class=\"separator\" colspan=\"2\"><hr/></td></tr>\n" ); out.print( " <tr>\n"+ " <td class=\"description\"><nobr>"+Messages.getBodyString(locale,"LivelinkConnector.DocumentFetchSSLCertificateList")+"</nobr></td>\n"+ " <td class=\"value\">\n"+ " <input type=\"hidden\" name=\"ingestkeystorealias\" value=\"\"/>\n"+ " <table class=\"displaytable\">\n" ); // List the individual certificates in the store, with a delete button for each String[] contents = localIngestKeystore.getContents(); if (contents.length == 0) { out.print( " <tr><td class=\"message\" colspan=\"2\"><nobr>"+Messages.getBodyString(locale,"LivelinkConnector.NoCertificatesPresent")+"</nobr></td></tr>\n" ); } else { int i = 0; while (i < contents.length) { String alias = contents[i]; String description = localIngestKeystore.getDescription(alias); if (description.length() > 128) description = description.substring(0,125) + "..."; out.print( " <tr>\n"+ " <td class=\"value\"><input type=\"button\" onclick='Javascript:IngestDeleteCertificate(\""+org.apache.manifoldcf.ui.util.Encoder.attributeJavascriptEscape(alias)+"\")' alt=\""+Messages.getAttributeString(locale,"LivelinkConnector.DeleteCert")+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(alias)+"\" value=\""+Messages.getAttributeString(locale,"LivelinkConnector.Delete")+"\"/></td>\n"+ " <td>"+org.apache.manifoldcf.ui.util.Encoder.bodyEscape(description)+"</td>\n"+ " </tr>\n" ); i++; } } out.print( " </table>\n"+ " <input type=\"button\" onclick='Javascript:IngestAddCertificate()' alt=\""+Messages.getAttributeString(locale,"LivelinkConnector.AddCert")+"\" value=\""+Messages.getAttributeString(locale,"LivelinkConnector.Add")+"\"/>&nbsp;\n"+ " "+Messages.getBodyString(locale,"LivelinkConnector.Certificate")+"<input name=\"ingestcertificate\" size=\"50\" type=\"file\"/>\n"+ " </td>\n"+ " </tr>\n" ); out.print( "</table>\n" ); } else { // Hiddens for Document Access tab out.print( "<input type=\"hidden\" name=\"ingestprotocol\" value=\""+ingestProtocol+"\"/>\n"+ "<input type=\"hidden\" name=\"ingestport\" value=\""+ingestPort+"\"/>\n"+ "<input type=\"hidden\" name=\"ingestcgipath\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(ingestCgiPath)+"\"/>\n"+ "<input type=\"hidden\" name=\"ingestntlmusername\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(ingestNtlmUsername)+"\"/>\n"+ "<input type=\"hidden\" name=\"ingestntlmpassword\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(ingestNtlmPassword)+"\"/>\n"+ "<input type=\"hidden\" name=\"ingestntlmdomain\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(ingestNtlmDomain)+"\"/>\n" ); } // Document View tab if (tabName.equals(Messages.getString(locale,"LivelinkConnector.DocumentView"))) { out.print( "<table class=\"displaytable\">\n"+ " <tr><td class=\"separator\" colspan=\"2\"><hr/></td></tr>\n"+ " <tr>\n"+ " <td class=\"description\">"+Messages.getBodyString(locale,"LivelinkConnector.DocumentViewProtocol")+"</td>\n"+ " <td class=\"value\">\n"+ " <select name=\"viewprotocol\" size=\"3\">\n"+ " <option value=\"\" "+((viewProtocol.equals(""))?"selected=\"selected\"":"")+">"+Messages.getBodyString(locale,"LivelinkConnector.SameAsFetchProtocol")+"</option>\n"+ " <option value=\"http\" "+((viewProtocol.equals("http"))?"selected=\"selected\"":"")+">http</option>\n"+ " <option value=\"https\" "+((viewProtocol.equals("https"))?"selected=\"selected\"":"")+">https</option>\n"+ " </select>\n"+ " </td>\n"+ " </tr>\n"+ " <tr>\n"+ " <td class=\"description\"><nobr>"+Messages.getBodyString(locale,"LivelinkConnector.DocumentViewServerName")+"</nobr><br/><nobr>"+Messages.getBodyString(locale,"LivelinkConnector.BlankSameAsFetchServer")+"</nobr></td>\n"+ " <td class=\"value\"><input type=\"text\" size=\"64\" name=\"viewservername\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(viewServerName)+"\"/></td>\n"+ " </tr>\n"+ " <tr>\n"+ " <td class=\"description\"><nobr>"+Messages.getBodyString(locale,"LivelinkConnector.DocumentViewPort")+"</nobr><br/><nobr>(blank = same as fetch port)</nobr></td>\n"+ " <td class=\"value\"><input type=\"text\" size=\"5\" name=\"viewport\" value=\""+viewPort+"\"/></td>\n"+ " </tr>\n"+ " <tr>\n"+ " <td class=\"description\"><nobr>"+Messages.getBodyString(locale,"LivelinkConnector.DocumentViewCGIPath")+"</nobr><br/><nobr>"+Messages.getBodyString(locale,"LivelinkConnector.BlankSameAsFetchServer")+"</nobr></td>\n"+ " <td class=\"value\"><input type=\"text\" size=\"32\" name=\"viewcgipath\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(viewCgiPath)+"\"/></td>\n"+ " </tr>\n"+ "</table>\n" ); } else { // Hiddens for Document View tab out.print( "<input type=\"hidden\" name=\"viewprotocol\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(viewProtocol)+"\"/>\n"+ "<input type=\"hidden\" name=\"viewservername\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(viewServerName)+"\"/>\n"+ "<input type=\"hidden\" name=\"viewport\" value=\""+viewPort+"\"/>\n"+ "<input type=\"hidden\" name=\"viewcgipath\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(viewCgiPath)+"\"/>\n" ); } } /** Process a configuration post. * This method is called at the start of the connector's configuration page, whenever there is a possibility that form data for a connection has been * posted. Its purpose is to gather form information and modify the configuration parameters accordingly. * The name of the posted form is "editconnection". *@param threadContext is the local thread context. *@param variableContext is the set of variables available from the post, including binary file post information. *@param parameters are the configuration parameters, as they currently exist, for this connection being configured. *@return null if all is well, or a string error message if there is an error that should prevent saving of the connection (and cause a redirection to an error page). */ @Override public String processConfigurationPost(IThreadContext threadContext, IPostParameters variableContext, Locale locale, ConfigParams parameters) throws ManifoldCFException { // View parameters String viewProtocol = variableContext.getParameter("viewprotocol"); if (viewProtocol != null) parameters.setParameter(LiveLinkParameters.viewProtocol,viewProtocol); String viewServerName = variableContext.getParameter("viewservername"); if (viewServerName != null) parameters.setParameter(LiveLinkParameters.viewServerName,viewServerName); String viewPort = variableContext.getParameter("viewport"); if (viewPort != null) parameters.setParameter(LiveLinkParameters.viewPort,viewPort); String viewCgiPath = variableContext.getParameter("viewcgipath"); if (viewCgiPath != null) parameters.setParameter(LiveLinkParameters.viewCgiPath,viewCgiPath); // Server parameters String serverProtocol = variableContext.getParameter("serverprotocol"); if (serverProtocol != null) parameters.setParameter(LiveLinkParameters.serverProtocol,serverProtocol); String serverName = variableContext.getParameter("servername"); if (serverName != null) parameters.setParameter(LiveLinkParameters.serverName,serverName); String serverPort = variableContext.getParameter("serverport"); if (serverPort != null) parameters.setParameter(LiveLinkParameters.serverPort,serverPort); String serverUserName = variableContext.getParameter("serverusername"); if (serverUserName != null) parameters.setParameter(LiveLinkParameters.serverUsername,serverUserName); String serverPassword = variableContext.getParameter("serverpassword"); if (serverPassword != null) parameters.setObfuscatedParameter(LiveLinkParameters.serverPassword,variableContext.mapKeyToPassword(serverPassword)); String serverHTTPCgiPath = variableContext.getParameter("serverhttpcgipath"); if (serverHTTPCgiPath != null) parameters.setParameter(LiveLinkParameters.serverHTTPCgiPath,serverHTTPCgiPath); String serverHTTPNTLMDomain = variableContext.getParameter("serverhttpntlmdomain"); if (serverHTTPNTLMDomain != null) parameters.setParameter(LiveLinkParameters.serverHTTPNTLMDomain,serverHTTPNTLMDomain); String serverHTTPNTLMUserName = variableContext.getParameter("serverhttpntlmusername"); if (serverHTTPNTLMUserName != null) parameters.setParameter(LiveLinkParameters.serverHTTPNTLMUsername,serverHTTPNTLMUserName); String serverHTTPNTLMPassword = variableContext.getParameter("serverhttpntlmpassword"); if (serverHTTPNTLMPassword != null) parameters.setObfuscatedParameter(LiveLinkParameters.serverHTTPNTLMPassword,variableContext.mapKeyToPassword(serverHTTPNTLMPassword)); String serverHTTPSKeystoreValue = variableContext.getParameter("serverhttpskeystoredata"); if (serverHTTPSKeystoreValue != null) parameters.setParameter(LiveLinkParameters.serverHTTPSKeystore,serverHTTPSKeystoreValue); String serverConfigOp = variableContext.getParameter("serverconfigop"); if (serverConfigOp != null) { if (serverConfigOp.equals("Delete")) { String alias = variableContext.getParameter("serverkeystorealias"); serverHTTPSKeystoreValue = parameters.getParameter(LiveLinkParameters.serverHTTPSKeystore); IKeystoreManager mgr; if (serverHTTPSKeystoreValue != null) mgr = KeystoreManagerFactory.make("",serverHTTPSKeystoreValue); else mgr = KeystoreManagerFactory.make(""); mgr.remove(alias); parameters.setParameter(LiveLinkParameters.serverHTTPSKeystore,mgr.getString()); } else if (serverConfigOp.equals("Add")) { String alias = IDFactory.make(threadContext); byte[] certificateValue = variableContext.getBinaryBytes("servercertificate"); serverHTTPSKeystoreValue = parameters.getParameter(LiveLinkParameters.serverHTTPSKeystore); IKeystoreManager mgr; if (serverHTTPSKeystoreValue != null) mgr = KeystoreManagerFactory.make("",serverHTTPSKeystoreValue); else mgr = KeystoreManagerFactory.make(""); java.io.InputStream is = new java.io.ByteArrayInputStream(certificateValue); String certError = null; try { mgr.importCertificate(alias,is); } catch (Throwable e) { certError = e.getMessage(); } finally { try { is.close(); } catch (IOException e) { // Eat this exception } } if (certError != null) { return "Illegal certificate: "+certError; } parameters.setParameter(LiveLinkParameters.serverHTTPSKeystore,mgr.getString()); } } // Ingest parameters String ingestProtocol = variableContext.getParameter("ingestprotocol"); if (ingestProtocol != null) parameters.setParameter(LiveLinkParameters.ingestProtocol,ingestProtocol); String ingestPort = variableContext.getParameter("ingestport"); if (ingestPort != null) parameters.setParameter(LiveLinkParameters.ingestPort,ingestPort); String ingestCgiPath = variableContext.getParameter("ingestcgipath"); if (ingestCgiPath != null) parameters.setParameter(LiveLinkParameters.ingestCgiPath,ingestCgiPath); String ingestNtlmDomain = variableContext.getParameter("ingestntlmdomain"); if (ingestNtlmDomain != null) parameters.setParameter(LiveLinkParameters.ingestNtlmDomain,ingestNtlmDomain); String ingestNtlmUsername = variableContext.getParameter("ingestntlmusername"); if (ingestNtlmUsername != null) parameters.setParameter(LiveLinkParameters.ingestNtlmUsername,ingestNtlmUsername); String ingestNtlmPassword = variableContext.getParameter("ingestntlmpassword"); if (ingestNtlmPassword != null) parameters.setObfuscatedParameter(LiveLinkParameters.ingestNtlmPassword,variableContext.mapKeyToPassword(ingestNtlmPassword)); String ingestKeystoreValue = variableContext.getParameter("ingestkeystoredata"); if (ingestKeystoreValue != null) parameters.setParameter(LiveLinkParameters.ingestKeystore,ingestKeystoreValue); String ingestConfigOp = variableContext.getParameter("ingestconfigop"); if (ingestConfigOp != null) { if (ingestConfigOp.equals("Delete")) { String alias = variableContext.getParameter("ingestkeystorealias"); ingestKeystoreValue = parameters.getParameter(LiveLinkParameters.ingestKeystore); IKeystoreManager mgr; if (ingestKeystoreValue != null) mgr = KeystoreManagerFactory.make("",ingestKeystoreValue); else mgr = KeystoreManagerFactory.make(""); mgr.remove(alias); parameters.setParameter(LiveLinkParameters.ingestKeystore,mgr.getString()); } else if (ingestConfigOp.equals("Add")) { String alias = IDFactory.make(threadContext); byte[] certificateValue = variableContext.getBinaryBytes("ingestcertificate"); ingestKeystoreValue = parameters.getParameter(LiveLinkParameters.ingestKeystore); IKeystoreManager mgr; if (ingestKeystoreValue != null) mgr = KeystoreManagerFactory.make("",ingestKeystoreValue); else mgr = KeystoreManagerFactory.make(""); java.io.InputStream is = new java.io.ByteArrayInputStream(certificateValue); String certError = null; try { mgr.importCertificate(alias,is); } catch (Throwable e) { certError = e.getMessage(); } finally { try { is.close(); } catch (IOException e) { // Eat this exception } } if (certError != null) { return "Illegal certificate: "+certError; } parameters.setParameter(LiveLinkParameters.ingestKeystore,mgr.getString()); } } return null; } /** View configuration. * This method is called in the body section of the connector's view configuration page. Its purpose is to present the connection information to the user. * The coder can presume that the HTML that is output from this configuration will be within appropriate <html> and <body> tags. *@param threadContext is the local thread context. *@param out is the output to which any HTML should be sent. *@param parameters are the configuration parameters, as they currently exist, for this connection being configured. */ @Override public void viewConfiguration(IThreadContext threadContext, IHTTPOutput out, Locale locale, ConfigParams parameters) throws ManifoldCFException, IOException { out.print( "<table class=\"displaytable\">\n"+ " <tr>\n"+ " <td class=\"description\" colspan=\"1\"><nobr>"+Messages.getBodyString(locale,"LivelinkConnector.Parameters")+"</nobr></td>\n"+ " <td class=\"value\" colspan=\"3\">\n" ); Iterator iter = parameters.listParameters(); while (iter.hasNext()) { String param = (String)iter.next(); String value = parameters.getParameter(param); if (param.length() >= "password".length() && param.substring(param.length()-"password".length()).equalsIgnoreCase("password")) { out.print( " <nobr>"+org.apache.manifoldcf.ui.util.Encoder.bodyEscape(param)+"=********</nobr><br/>\n" ); } else if (param.length() >="keystore".length() && param.substring(param.length()-"keystore".length()).equalsIgnoreCase("keystore") || param.length() > "truststore".length() && param.substring(param.length()-"truststore".length()).equalsIgnoreCase("truststore")) { IKeystoreManager kmanager = KeystoreManagerFactory.make("",value); out.print( " <nobr>"+org.apache.manifoldcf.ui.util.Encoder.bodyEscape(param)+"=&lt;"+Integer.toString(kmanager.getContents().length)+Messages.getBodyString(locale,"LivelinkConnector.certificates")+"&gt;</nobr><br/>\n" ); } else { out.print( " <nobr>"+org.apache.manifoldcf.ui.util.Encoder.bodyEscape(param)+"="+org.apache.manifoldcf.ui.util.Encoder.bodyEscape(value)+"</nobr><br/>\n" ); } } out.print( " </td>\n"+ " </tr>\n"+ "</table>\n" ); } /** Output the specification header section. * This method is called in the head section of a job page which has selected a repository connection of the * current type. Its purpose is to add the required tabs to the list, and to output any javascript methods * that might be needed by the job editing HTML. * The connector will be connected before this method can be called. *@param out is the output to which any HTML should be sent. *@param locale is the locale the output is preferred to be in. *@param ds is the current document specification for this job. *@param connectionSequenceNumber is the unique number of this connection within the job. *@param tabsArray is an array of tab names. Add to this array any tab names that are specific to the connector. */ @Override public void outputSpecificationHeader(IHTTPOutput out, Locale locale, Specification ds, int connectionSequenceNumber, List<String> tabsArray) throws ManifoldCFException, IOException { tabsArray.add(Messages.getString(locale,"LivelinkConnector.Paths")); tabsArray.add(Messages.getString(locale,"LivelinkConnector.Filters")); tabsArray.add(Messages.getString(locale,"LivelinkConnector.Security")); tabsArray.add(Messages.getString(locale,"LivelinkConnector.Metadata")); String seqPrefix = "s"+connectionSequenceNumber+"_"; out.print( "<script type=\"text/javascript\">\n"+ "<!--\n"+ "\n"+ "function "+seqPrefix+"SpecOp(n, opValue, anchorvalue)\n"+ "{\n"+ " eval(\"editjob.\"+n+\".value = \\\"\"+opValue+\"\\\"\");\n"+ " postFormSetAnchor(anchorvalue);\n"+ "}\n"+ "\n"+ "function "+seqPrefix+"SpecAddToPath(anchorvalue)\n"+ "{\n"+ " if (editjob."+seqPrefix+"pathaddon.value == \"\")\n"+ " {\n"+ " alert(\""+Messages.getBodyJavascriptString(locale,"LivelinkConnector.SelectAFolderFirst")+"\");\n"+ " editjob."+seqPrefix+"pathaddon.focus();\n"+ " return;\n"+ " }\n"+ "\n"+ " "+seqPrefix+"SpecOp(\""+seqPrefix+"pathop\",\"AddToPath\",anchorvalue);\n"+ "}\n"+ "\n"+ "function "+seqPrefix+"SpecAddFilespec(anchorvalue)\n"+ "{\n"+ " if (editjob."+seqPrefix+"specfile.value == \"\")\n"+ " {\n"+ " alert(\""+Messages.getBodyJavascriptString(locale,"LivelinkConnector.TypeInAFileSpecification")+"\");\n"+ " editjob."+seqPrefix+"specfile.focus();\n"+ " return;\n"+ " }\n"+ " "+seqPrefix+"SpecOp(\""+seqPrefix+"fileop\",\"Add\",anchorvalue);\n"+ "}\n"+ "\n"+ "function "+seqPrefix+"SpecAddToken(anchorvalue)\n"+ "{\n"+ " if (editjob."+seqPrefix+"spectoken.value == \"\")\n"+ " {\n"+ " alert(\""+Messages.getBodyJavascriptString(locale,"LivelinkConnector.TypeInAnAccessToken")+"\");\n"+ " editjob."+seqPrefix+"spectoken.focus();\n"+ " return;\n"+ " }\n"+ " "+seqPrefix+"SpecOp(\""+seqPrefix+"accessop\",\"Add\",anchorvalue);\n"+ "}\n"+ "\n"+ "function "+seqPrefix+"SpecAddToMetadata(anchorvalue)\n"+ "{\n"+ " if (editjob."+seqPrefix+"metadataaddon.value == \"\")\n"+ " {\n"+ " alert(\""+Messages.getBodyJavascriptString(locale,"LivelinkConnector.SelectAFolderFirst")+"\");\n"+ " editjob."+seqPrefix+"metadataaddon.focus();\n"+ " return;\n"+ " }\n"+ " "+seqPrefix+"SpecOp(\""+seqPrefix+"metadataop\",\"AddToPath\",anchorvalue);\n"+ "}\n"+ "\n"+ "function "+seqPrefix+"SpecSetWorkspace(anchorvalue)\n"+ "{\n"+ " if (editjob."+seqPrefix+"metadataaddon.value == \"\")\n"+ " {\n"+ " alert(\""+Messages.getBodyJavascriptString(locale,"LivelinkConnector.SelectAWorkspaceFirst")+"\");\n"+ " editjob."+seqPrefix+"metadataaddon.focus();\n"+ " return;\n"+ " }\n"+ " "+seqPrefix+"SpecOp(\""+seqPrefix+"metadataop\",\"SetWorkspace\",anchorvalue);\n"+ "}\n"+ "\n"+ "function "+seqPrefix+"SpecAddCategory(anchorvalue)\n"+ "{\n"+ " if (editjob."+seqPrefix+"categoryaddon.value == \"\")\n"+ " {\n"+ " alert(\""+Messages.getBodyJavascriptString(locale,"LivelinkConnector.SelectACategoryFirst")+"\");\n"+ " editjob."+seqPrefix+"categoryaddon.focus();\n"+ " return;\n"+ " }\n"+ " "+seqPrefix+"SpecOp(\""+seqPrefix+"metadataop\",\"AddCategory\",anchorvalue);\n"+ "}\n"+ "\n"+ "function "+seqPrefix+"SpecAddMetadata(anchorvalue)\n"+ "{\n"+ " if (editjob."+seqPrefix+"attributeselect.value == \"\" && editjob."+seqPrefix+"attributeall.value == \"\")\n"+ " {\n"+ " alert(\""+Messages.getBodyJavascriptString(locale,"LivelinkConnector.SelectAtLeastOneAttributeFirst")+"\");\n"+ " editjob."+seqPrefix+"attributeselect.focus();\n"+ " return;\n"+ " }\n"+ " "+seqPrefix+"SpecOp(\""+seqPrefix+"metadataop\",\"Add\",anchorvalue);\n"+ "}\n"+ "\n"+ "function "+seqPrefix+"SpecAddMapping(anchorvalue)\n"+ "{\n"+ " if (editjob."+seqPrefix+"specmatch.value == \"\")\n"+ " {\n"+ " alert(\""+Messages.getBodyJavascriptString(locale,"LivelinkConnector.MatchStringCannotBeEmpty")+"\");\n"+ " editjob."+seqPrefix+"specmatch.focus();\n"+ " return;\n"+ " }\n"+ " if (!isRegularExpression(editjob."+seqPrefix+"specmatch.value))\n"+ " {\n"+ " alert(\""+Messages.getBodyJavascriptString(locale,"LivelinkConnector.MatchStringMustBeValidRegularExpression")+"\");\n"+ " editjob."+seqPrefix+"specmatch.focus();\n"+ " return;\n"+ " }\n"+ " "+seqPrefix+"SpecOp(\""+seqPrefix+"specmappingop\",\"Add\",anchorvalue);\n"+ "}\n"+ "//-->\n"+ "</script>\n" ); } /** Output the specification body section. * This method is called in the body section of a job page which has selected a repository connection of the * current type. Its purpose is to present the required form elements for editing. * The coder can presume that the HTML that is output from this configuration will be within appropriate * <html>, <body>, and <form> tags. The name of the form is always "editjob". * The connector will be connected before this method can be called. *@param out is the output to which any HTML should be sent. *@param locale is the locale the output is preferred to be in. *@param ds is the current document specification for this job. *@param connectionSequenceNumber is the unique number of this connection within the job. *@param actualSequenceNumber is the connection within the job that has currently been selected. *@param tabName is the current tab name. (actualSequenceNumber, tabName) form a unique tuple within * the job. */ @Override public void outputSpecificationBody(IHTTPOutput out, Locale locale, Specification ds, int connectionSequenceNumber, int actualSequenceNumber, String tabName) throws ManifoldCFException, IOException { String seqPrefix = "s"+connectionSequenceNumber+"_"; int i; int k; // Paths tab boolean userWorkspaces = false; i = 0; while (i < ds.getChildCount()) { SpecificationNode sn = ds.getChild(i++); if (sn.getType().equals("userworkspace")) { String value = sn.getAttributeValue("value"); if (value != null && value.equals("true")) userWorkspaces = true; } } if (tabName.equals(Messages.getString(locale,"LivelinkConnector.Paths")) && connectionSequenceNumber == actualSequenceNumber) { out.print( "<table class=\"displaytable\">\n"+ " <tr><td class=\"separator\" colspan=\"2\"><hr/></td></tr>\n"+ " <tr>\n"+ " <td class=\"description\">\n"+ " <nobr>"+Messages.getBodyString(locale,"LivelinkConnector.CrawlUserWorkspaces")+"</nobr>\n"+ " </td>\n"+ " <td class=\"value\">\n"+ " <input type=\"checkbox\" name=\""+seqPrefix+"userworkspace\" value=\"true\""+(userWorkspaces?" checked=\"true\"":"")+"/>\n"+ " <input type=\"hidden\" name=\""+seqPrefix+"userworkspace_present\" value=\"true\"/>\n"+ " </td>\n"+ " </tr>\n"+ " <tr><td class=\"separator\" colspan=\"2\"><hr/></td></tr>\n" ); // Now, loop through paths i = 0; k = 0; while (i < ds.getChildCount()) { SpecificationNode sn = ds.getChild(i++); if (sn.getType().equals("startpoint")) { String pathDescription = "_"+Integer.toString(k); String pathOpName = seqPrefix+"pathop"+pathDescription; out.print( " <tr>\n"+ " <td class=\"description\">\n"+ " <input type=\"hidden\" name=\""+seqPrefix+"specpath"+pathDescription+"\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(sn.getAttributeValue("path"))+"\"/>\n"+ " <input type=\"hidden\" name=\""+pathOpName+"\" value=\"\"/>\n"+ " <a name=\""+seqPrefix+"path_"+Integer.toString(k)+"\">\n"+ " <input type=\"button\" value=\"Delete\" onClick='Javascript:"+seqPrefix+"SpecOp(\""+pathOpName+"\",\"Delete\",\""+seqPrefix+"path_"+Integer.toString(k)+"\")' alt=\""+Messages.getAttributeString(locale,"LivelinkConnector.DeletePath")+Integer.toString(k)+"\"/>\n"+ " </a>\n"+ " </td>\n"+ " <td class=\"value\">\n"+ " "+((sn.getAttributeValue("path").length() == 0)?"(root)":org.apache.manifoldcf.ui.util.Encoder.bodyEscape(sn.getAttributeValue("path")))+"\n"+ " </td>\n"+ " </tr>\n" ); k++; } } if (k == 0) { out.print( " <tr>\n"+ " <td class=\"message\" colspan=\"2\">"+Messages.getBodyString(locale,"LivelinkConnector.NoStartingPointsDefined")+"</td>\n"+ " </tr>\n" ); } out.print( " <tr><td class=\"lightseparator\" colspan=\"2\"><hr/></td></tr>\n"+ " <tr>\n"+ " <td class=\"description\">\n"+ " <input type=\"hidden\" name=\""+seqPrefix+"pathcount\" value=\""+Integer.toString(k)+"\"/>\n" ); String pathSoFar = (String)currentContext.get(seqPrefix+"specpath"); if (pathSoFar == null) pathSoFar = ""; // Grab next folder/project list try { String[] childList; childList = getChildFolderNames(pathSoFar); if (childList == null) { // Illegal path - set it back pathSoFar = ""; childList = getChildFolderNames(""); if (childList == null) throw new ManifoldCFException("Can't find any children for root folder"); } out.print( " <input type=\"hidden\" name=\""+seqPrefix+"specpath\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(pathSoFar)+"\"/>\n"+ " <input type=\"hidden\" name=\""+seqPrefix+"pathop\" value=\"\"/>\n"+ " <a name=\""+seqPrefix+"path_"+Integer.toString(k)+"\">\n"+ " <input type=\"button\" value=\"Add\" onClick='Javascript:"+seqPrefix+"SpecOp(\""+seqPrefix+"pathop\",\"Add\",\""+seqPrefix+"path_"+Integer.toString(k+1)+"\")' alt=\""+Messages.getAttributeString(locale,"LivelinkConnector.AddPath")+"\"/>\n"+ " </a>&nbsp;\n"+ " </td>\n"+ " <td class=\"value\">\n"+ " "+((pathSoFar.length()==0)?"(root)":org.apache.manifoldcf.ui.util.Encoder.bodyEscape(pathSoFar))+"\n" ); if (pathSoFar.length() > 0) { out.print( " <input type=\"button\" value=\"-\" onClick='Javascript:"+seqPrefix+"SpecOp(\""+seqPrefix+"pathop\",\"Up\",\""+seqPrefix+"path_"+Integer.toString(k)+"\")' alt=\"Back up path\"/>\n" ); } if (childList.length > 0) { out.print( " <input type=\"button\" value=\"+\" onClick='Javascript:"+seqPrefix+"SpecAddToPath(\""+seqPrefix+"path_"+Integer.toString(k)+"\")' alt=\""+Messages.getAttributeString(locale,"LivelinkConnector.AddToPath")+"\"/>&nbsp;\n"+ " <select multiple=\"false\" name=\""+seqPrefix+"pathaddon\" size=\"2\">\n"+ " <option value=\"\" selected=\"selected\">"+Messages.getBodyString(locale,"LivelinkConnector.PickAFolder")+"</option>\n" ); int j = 0; while (j < childList.length) { out.print( " <option value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(childList[j])+"\">"+org.apache.manifoldcf.ui.util.Encoder.bodyEscape(childList[j])+"</option>\n" ); j++; } out.print( " </select>\n" ); } } catch (ServiceInterruption e) { //e.printStackTrace(); out.println(org.apache.manifoldcf.ui.util.Encoder.bodyEscape(e.getMessage())); } catch (ManifoldCFException e) { //e.printStackTrace(); out.println(org.apache.manifoldcf.ui.util.Encoder.bodyEscape(e.getMessage())); } out.print( " </td>\n"+ " </tr>\n"+ "</table>\n" ); } else { // Now, loop through paths i = 0; k = 0; while (i < ds.getChildCount()) { SpecificationNode sn = ds.getChild(i++); if (sn.getType().equals("startpoint")) { String pathDescription = "_"+Integer.toString(k); out.print( "<input type=\"hidden\" name=\""+seqPrefix+"specpath"+pathDescription+"\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(sn.getAttributeValue("path"))+"\"/>\n" ); k++; } } out.print( "<input type=\"hidden\" name=\""+seqPrefix+"pathcount\" value=\""+Integer.toString(k)+"\"/>\n"+ "<input type=\"hidden\" name=\""+seqPrefix+"userworkspace\" value=\""+(userWorkspaces?"true":"false")+"\"/>\n"+ "<input type=\"hidden\" name=\""+seqPrefix+"userworkspace_present\" value=\"true\"/>\n" ); } // Filter tab if (tabName.equals(Messages.getString(locale,"LivelinkConnector.Filters")) && connectionSequenceNumber == actualSequenceNumber) { out.print( "<table class=\"displaytable\">\n"+ " <tr><td class=\"separator\" colspan=\"2\"><hr/></td></tr>\n" ); // Next, go through include/exclude filespecs i = 0; k = 0; while (i < ds.getChildCount()) { SpecificationNode sn = ds.getChild(i++); if (sn.getType().equals("include") || sn.getType().equals("exclude")) { String fileSpecDescription = "_"+Integer.toString(k); String fileOpName = seqPrefix+"fileop"+fileSpecDescription; String filespec = sn.getAttributeValue("filespec"); out.print( " <tr>\n"+ " <td class=\"description\">\n"+ " <input type=\"hidden\" name=\""+seqPrefix+"specfiletype"+fileSpecDescription+"\" value=\""+sn.getType()+"\"/>\n"+ " <input type=\"hidden\" name=\""+fileOpName+"\" value=\"\"/>\n"+ " <a name=\""+seqPrefix+"filespec_"+Integer.toString(k)+"\">\n"+ " <input type=\"button\" value=\"Delete\" onClick='Javascript:"+seqPrefix+"SpecOp(\""+fileOpName+"\",\"Delete\",\""+seqPrefix+"filespec_"+Integer.toString(k)+"\")' alt=\""+Messages.getAttributeString(locale,"LivelinkConnector.DeleteFilespec")+Integer.toString(k)+"\"/>\n"+ " </a>\n"+ " </td>\n"+ " <td class=\"value\">\n"+ " "+(sn.getType().equals("include")?"Include:":"")+"\n"+ " "+(sn.getType().equals("exclude")?"Exclude:":"")+"\n"+ " &nbsp;<input type=\"hidden\" name=\""+seqPrefix+"specfile"+fileSpecDescription+"\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(filespec)+"\"/>\n"+ " "+org.apache.manifoldcf.ui.util.Encoder.bodyEscape(filespec)+"\n"+ " </td>\n"+ " </tr>\n" ); k++; } } if (k == 0) { out.print( " <tr>\n"+ " <td class=\"message\" colspan=\"2\">"+Messages.getBodyString(locale,"LivelinkConnector.NoIncludeExcludeFilesDefined")+"</td>\n"+ " </tr>\n" ); } out.print( " <tr><td class=\"lightseparator\" colspan=\"2\"><hr/></td></tr>\n"+ " <tr>\n"+ " <td class=\"description\">\n"+ " <input type=\"hidden\" name=\""+seqPrefix+"filecount\" value=\""+Integer.toString(k)+"\"/>\n"+ " <input type=\"hidden\" name=\""+seqPrefix+"fileop\" value=\"\"/>\n"+ " <a name=\""+seqPrefix+"filespec_"+Integer.toString(k)+"\">\n"+ " <input type=\"button\" value=\"Add\" onClick='Javascript:"+seqPrefix+"SpecAddFilespec(\""+seqPrefix+"filespec_"+Integer.toString(k+1)+"\")' alt=\""+Messages.getAttributeString(locale,"LivelinkConnector.AddFileSpecification")+"\"/>\n"+ " </a>&nbsp;\n"+ " </td>\n"+ " <td class=\"value\">\n"+ " <select name=\""+seqPrefix+"specfiletype\" size=\"1\">\n"+ " <option value=\"include\" selected=\"selected\">"+Messages.getBodyString(locale,"LivelinkConnector.Include")+"</option>\n"+ " <option value=\"exclude\">"+Messages.getBodyString(locale,"LivelinkConnector.Exclude")+"</option>\n"+ " </select>&nbsp;\n"+ " <input type=\"text\" size=\"30\" name=\""+seqPrefix+"specfile\" value=\"\"/>\n"+ " </td>\n"+ " </tr>\n"+ "</table>\n" ); } else { // Next, go through include/exclude filespecs i = 0; k = 0; while (i < ds.getChildCount()) { SpecificationNode sn = ds.getChild(i++); if (sn.getType().equals("include") || sn.getType().equals("exclude")) { String fileSpecDescription = "_"+Integer.toString(k); String filespec = sn.getAttributeValue("filespec"); out.print( "<input type=\"hidden\" name=\""+seqPrefix+"specfiletype"+fileSpecDescription+"\" value=\""+sn.getType()+"\"/>\n"+ "<input type=\"hidden\" name=\""+seqPrefix+"specfile"+fileSpecDescription+"\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(filespec)+"\"/>\n" ); k++; } } out.print( "<input type=\"hidden\" name=\""+seqPrefix+"filecount\" value=\""+Integer.toString(k)+"\"/>\n" ); } // Security tab // Find whether security is on or off i = 0; boolean securityOn = true; while (i < ds.getChildCount()) { SpecificationNode sn = ds.getChild(i++); if (sn.getType().equals("security")) { String securityValue = sn.getAttributeValue("value"); if (securityValue.equals("off")) securityOn = false; else if (securityValue.equals("on")) securityOn = true; } } if (tabName.equals(Messages.getString(locale,"LivelinkConnector.Security")) && connectionSequenceNumber == actualSequenceNumber) { out.print( "<table class=\"displaytable\">\n"+ " <tr><td class=\"separator\" colspan=\"2\"><hr/></td></tr>\n"+ " <tr>\n"+ " <td class=\"description\"><nobr>"+Messages.getBodyString(locale,"LivelinkConnector.SecurityColon")+"</nobr></td>\n"+ " <td class=\"value\">\n"+ " <input type=\"radio\" name=\""+seqPrefix+"specsecurity\" value=\"on\" "+(securityOn?"checked=\"true\"":"")+" />"+Messages.getBodyString(locale,"LivelinkConnector.Enabled")+"\n"+ " <input type=\"radio\" name=\""+seqPrefix+"specsecurity\" value=\"off\" "+((securityOn==false)?"checked=\"true\"":"")+" />"+Messages.getBodyString(locale,"LivelinkConnector.Disabled")+"\n"+ " </td>\n"+ " </tr>\n"+ " <tr><td class=\"separator\" colspan=\"2\"><hr/></td></tr>\n" ); // Go through forced ACL i = 0; k = 0; while (i < ds.getChildCount()) { SpecificationNode sn = ds.getChild(i++); if (sn.getType().equals("access")) { String accessDescription = "_"+Integer.toString(k); String accessOpName = seqPrefix+"accessop"+accessDescription; String token = sn.getAttributeValue("token"); out.print( " <tr>\n"+ " <td class=\"description\">\n"+ " <input type=\"hidden\" name=\""+accessOpName+"\" value=\"\"/>\n"+ " <input type=\"hidden\" name=\""+seqPrefix+"spectoken"+accessDescription+"\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(token)+"\"/>\n"+ " <a name=\""+seqPrefix+"token_"+Integer.toString(k)+"\">\n"+ " <input type=\"button\" value=\"Delete\" onClick='Javascript:"+seqPrefix+"SpecOp(\""+accessOpName+"\",\"Delete\",\""+seqPrefix+"token_"+Integer.toString(k)+"\")' alt=\""+Messages.getAttributeString(locale,"LivelinkConnector.DeleteToken")+Integer.toString(k)+"\"/>\n"+ " </a>&nbsp;\n"+ " </td>\n"+ " <td class=\"value\">\n"+ " "+org.apache.manifoldcf.ui.util.Encoder.bodyEscape(token)+"\n"+ " </td>\n"+ " </tr>\n" ); k++; } } if (k == 0) { out.print( " <tr>\n"+ " <td class=\"message\" colspan=\"2\">" + Messages.getBodyString(locale,"LivelinkConnector.NoAccessTokensPresent") + "</td>\n"+ " </tr>\n" ); } out.print( " <tr><td class=\"lightseparator\" colspan=\"2\"><hr/></td></tr>\n"+ " <tr>\n"+ " <td class=\"description\">\n"+ " <input type=\"hidden\" name=\""+seqPrefix+"tokencount\" value=\""+Integer.toString(k)+"\"/>\n"+ " <input type=\"hidden\" name=\""+seqPrefix+"accessop\" value=\"\"/>\n"+ " <a name=\""+seqPrefix+"token_"+Integer.toString(k)+"\">\n"+ " <input type=\"button\" value=\"Add\" onClick='Javascript:"+seqPrefix+"SpecAddToken(\""+seqPrefix+"token_"+Integer.toString(k+1)+"\")' alt=\""+Messages.getAttributeString(locale,"LivelinkConnector.AddAccessToken")+"\"/>\n"+ " </a>&nbsp;\n"+ " </td>\n"+ " <td class=\"value\">\n"+ " <input type=\"text\" size=\"30\" name=\""+seqPrefix+"spectoken\" value=\"\"/>\n"+ " </td>\n"+ " </tr>\n"+ "</table>\n" ); } else { out.print( "<input type=\"hidden\" name=\""+seqPrefix+"specsecurity\" value=\""+(securityOn?"on":"off")+"\"/>\n" ); // Finally, go through forced ACL i = 0; k = 0; while (i < ds.getChildCount()) { SpecificationNode sn = ds.getChild(i++); if (sn.getType().equals("access")) { String accessDescription = "_"+Integer.toString(k); String token = sn.getAttributeValue("token"); out.print( "<input type=\"hidden\" name=\""+seqPrefix+"spectoken"+accessDescription+"\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(token)+"\"/>\n" ); k++; } } out.print( "<input type=\"hidden\" name=\""+seqPrefix+"tokencount\" value=\""+Integer.toString(k)+"\"/>\n" ); } // Metadata tab // Find the path-value metadata attribute name i = 0; String pathNameAttribute = ""; String pathNameSeparator = "/"; while (i < ds.getChildCount()) { SpecificationNode sn = ds.getChild(i++); if (sn.getType().equals("pathnameattribute")) { pathNameAttribute = sn.getAttributeValue("value"); if (sn.getAttributeValue("separator") != null) pathNameSeparator = sn.getAttributeValue("separator"); } } // Find the path-value mapping data i = 0; MatchMap matchMap = new MatchMap(); while (i < ds.getChildCount()) { SpecificationNode sn = ds.getChild(i++); if (sn.getType().equals("pathmap")) { String pathMatch = sn.getAttributeValue("match"); String pathReplace = sn.getAttributeValue("replace"); matchMap.appendMatchPair(pathMatch,pathReplace); } } i = 0; String ingestAllMetadata = "false"; while (i < ds.getChildCount()) { SpecificationNode sn = ds.getChild(i++); if (sn.getType().equals("allmetadata")) { ingestAllMetadata = sn.getAttributeValue("all"); if (ingestAllMetadata == null) ingestAllMetadata = "false"; } } if (tabName.equals(Messages.getString(locale,"LivelinkConnector.Metadata")) && connectionSequenceNumber == actualSequenceNumber) { out.print( "<input type=\"hidden\" name=\""+seqPrefix+"specmappingcount\" value=\""+Integer.toString(matchMap.getMatchCount())+"\"/>\n"+ "<input type=\"hidden\" name=\""+seqPrefix+"specmappingop\" value=\"\"/>\n"+ "\n"+ "<table class=\"displaytable\">\n"+ " <tr><td class=\"separator\" colspan=\"4\"><hr/></td></tr>\n"+ " <tr>\n"+ " <td class=\"description\" colspan=\"1\"><nobr>"+Messages.getBodyString(locale,"LivelinkConnector.IngestALLMetadata")+"</nobr></td>\n"+ " <td class=\"value\" colspan=\"3\">\n"+ " <nobr><input type=\"radio\" name=\""+seqPrefix+"specallmetadata\" value=\"true\" "+(ingestAllMetadata.equals("true")?"checked=\"true\"":"")+"/>"+Messages.getBodyString(locale,"LivelinkConnector.Yes")+"</nobr>&nbsp;\n"+ " <nobr><input type=\"radio\" name=\""+seqPrefix+"specallmetadata\" value=\"false\" "+(ingestAllMetadata.equals("false")?"checked=\"true\"":"")+"/>"+Messages.getBodyString(locale,"LivelinkConnector.No")+"</nobr>\n"+ " </td>\n"+ " </tr>\n"+ " <tr><td class=\"separator\" colspan=\"4\"><hr/></td></tr>\n" ); // Go through the selected metadata attributes i = 0; k = 0; while (i < ds.getChildCount()) { SpecificationNode sn = ds.getChild(i++); if (sn.getType().equals("metadata")) { String accessDescription = "_"+Integer.toString(k); String accessOpName = seqPrefix+"metadataop"+accessDescription; String categoryPath = sn.getAttributeValue("category"); String isAll = sn.getAttributeValue("all"); if (isAll == null) isAll = "false"; String attributeName = sn.getAttributeValue("attribute"); if (attributeName == null) attributeName = ""; out.print( " <tr>\n"+ " <td class=\"description\" colspan=\"1\">\n"+ " <input type=\"hidden\" name=\""+accessOpName+"\" value=\"\"/>\n"+ " <input type=\"hidden\" name=\""+seqPrefix+"speccategory"+accessDescription+"\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(categoryPath)+"\"/>\n"+ " <input type=\"hidden\" name=\""+seqPrefix+"specattributeall"+accessDescription+"\" value=\""+isAll+"\"/>\n"+ " <input type=\"hidden\" name=\""+seqPrefix+"specattribute"+accessDescription+"\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(attributeName)+"\"/>\n"+ " <a name=\""+seqPrefix+"metadata_"+Integer.toString(k)+"\">\n"+ " <input type=\"button\" value=\"Delete\" onClick='Javascript:"+seqPrefix+"SpecOp(\""+accessOpName+"\",\"Delete\",\""+seqPrefix+"metadata_"+Integer.toString(k)+"\")' alt=\""+Messages.getAttributeString(locale,"LivelinkConnector.DeleteMetadata")+Integer.toString(k)+"\"/>\n"+ " </a>&nbsp;\n"+ " </td>\n"+ " <td class=\"value\" colspan=\"3\">\n"+ " "+org.apache.manifoldcf.ui.util.Encoder.bodyEscape(categoryPath)+":"+((isAll!=null&&isAll.equals("true"))?"(All metadata attributes)":org.apache.manifoldcf.ui.util.Encoder.bodyEscape(attributeName))+"\n"+ " </td>\n"+ " </tr>\n" ); k++; } } if (k == 0) { out.print( " <tr>\n"+ " <td class=\"message\" colspan=\"4\">"+Messages.getBodyString(locale,"LivelinkConnector.NoMetadataSpecified")+"</td>\n"+ " </tr>\n" ); } out.print( " <tr><td class=\"lightseparator\" colspan=\"4\"><hr/></td></tr>\n"+ " <tr>\n"+ " <td class=\"description\" colspan=\"1\">\n"+ " <a name=\""+seqPrefix+"metadata_"+Integer.toString(k)+"\"></a>\n"+ " <input type=\"hidden\" name=\""+seqPrefix+"metadatacount\" value=\""+Integer.toString(k)+"\"/>\n" ); String categorySoFar = (String)currentContext.get(seqPrefix+"speccategory"); if (categorySoFar == null) categorySoFar = ""; // Grab next folder/project list, and the appropriate category list try { String[] childList = null; String[] workspaceList = null; String[] categoryList = null; String[] attributeList = null; if (categorySoFar.length() == 0) { workspaceList = getWorkspaceNames(); } else { attributeList = getCategoryAttributes(categorySoFar); if (attributeList == null) { childList = getChildFolderNames(categorySoFar); if (childList == null) { // Illegal path - set it back categorySoFar = ""; childList = getChildFolderNames(""); if (childList == null) throw new ManifoldCFException("Can't find any children for root folder"); } categoryList = getChildCategoryNames(categorySoFar); if (categoryList == null) throw new ManifoldCFException("Can't find any categories for root folder folder"); } } out.print( " <input type=\"hidden\" name=\""+seqPrefix+"speccategory\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(categorySoFar)+"\"/>\n"+ " <input type=\"hidden\" name=\""+seqPrefix+"metadataop\" value=\"\"/>\n" ); if (attributeList != null) { // We have a valid category! out.print( " <input type=\"button\" value=\"Add\" onClick='Javascript:"+seqPrefix+"SpecAddMetadata(\""+seqPrefix+"metadata_"+Integer.toString(k+1)+"\")' alt=\""+Messages.getAttributeString(locale,"LivelinkConnector.AddMetadataItem")+"\"/>&nbsp;\n"+ " </td>\n"+ " <td class=\"value\" colspan=\"3\">\n"+ " "+org.apache.manifoldcf.ui.util.Encoder.bodyEscape(categorySoFar)+":<input type=\"button\" value=\"-\" onClick='Javascript:"+seqPrefix+"SpecOp(\""+seqPrefix+"metadataop\",\"Up\",\""+seqPrefix+"metadata_"+Integer.toString(k)+"\")' alt=\""+Messages.getAttributeString(locale,"LivelinkConnector.BackUpMetadataPath")+"\"/>&nbsp;\n"+ " <table class=\"displaytable\">\n"+ " <tr>\n"+ " <td class=\"value\">\n"+ " <input type=\"checkbox\" name=\""+seqPrefix+"attributeall\" value=\"true\"/>"+Messages.getBodyString(locale,"LivelinkConnector.AllAttributesInThisCategory")+"<br/>\n"+ " <select multiple=\"true\" name=\""+seqPrefix+"attributeselect\" size=\"2\">\n"+ " <option value=\"\" selected=\"selected\">"+Messages.getBodyString(locale,"LivelinkConnector.PickAttributes")+"</option>\n" ); int l = 0; while (l < attributeList.length) { String attributeName = attributeList[l++]; out.print( " <option value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(attributeName)+"\">"+org.apache.manifoldcf.ui.util.Encoder.bodyEscape(attributeName)+"</option>\n" ); } out.print( " </select>\n"+ " </td>\n"+ " </tr>\n"+ " </table>\n" ); } else if (workspaceList != null) { out.print( " </td>\n"+ " <td class=\"value\" colspan=\"3\">\n"+ " <input type=\"button\" value=\"+\" onClick='Javascript:"+seqPrefix+"SpecSetWorkspace(\""+seqPrefix+"metadata_"+Integer.toString(k)+"\")' alt=\""+Messages.getAttributeString(locale,"LivelinkConnector.AddToMetadataPath")+"\"/>&nbsp;\n"+ " <select multiple=\"false\" name=\""+seqPrefix+"metadataaddon\" size=\"2\">\n"+ " <option value=\"\" selected=\"selected\">"+Messages.getBodyString(locale,"LivelinkConnector.PickWorkspace")+"</option>\n" ); int j = 0; while (j < workspaceList.length) { out.print( " <option value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(workspaceList[j])+"\">"+org.apache.manifoldcf.ui.util.Encoder.bodyEscape(workspaceList[j])+"</option>\n" ); j++; } out.print( " </select>\n" ); } else { out.print( " </td>\n"+ " <td class=\"value\" colspan=\"3\">\n"+ " "+((categorySoFar.length()==0)?"(root)":org.apache.manifoldcf.ui.util.Encoder.bodyEscape(categorySoFar))+"&nbsp;\n" ); if (categorySoFar.length() > 0) { out.print( " <input type=\"button\" value=\"-\" onClick='Javascript:"+seqPrefix+"SpecOp(\""+seqPrefix+"metadataop\",\"Up\",\""+seqPrefix+"metadata_"+Integer.toString(k)+"\")' alt=\""+Messages.getAttributeString(locale,"LivelinkConnector.BackUpMetadataPath")+"\"/>&nbsp;\n" ); } if (childList.length > 0) { out.print( " <input type=\"button\" value=\"+\" onClick='Javascript:"+seqPrefix+"SpecAddToMetadata(\""+seqPrefix+"metadata_"+Integer.toString(k)+"\")' alt=\""+Messages.getAttributeString(locale,"LivelinkConnector.AddToMetadataPath")+"\"/>&nbsp;\n"+ " <select multiple=\"false\" name=\""+seqPrefix+"metadataaddon\" size=\"2\">\n"+ " <option value=\"\" selected=\"selected\">"+Messages.getBodyString(locale,"LivelinkConnector.PickAFolder")+"</option>\n" ); int j = 0; while (j < childList.length) { out.print( " <option value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(childList[j])+"\">"+org.apache.manifoldcf.ui.util.Encoder.bodyEscape(childList[j])+"</option>\n" ); j++; } out.print( " </select>\n" ); } if (categoryList.length > 0) { out.print( " <input type=\"button\" value=\"+\" onClick='Javascript:"+seqPrefix+"SpecAddCategory(\""+seqPrefix+"metadata_"+Integer.toString(k)+"\")' alt=\""+Messages.getAttributeString(locale,"LivelinkConnector.AddCategory")+"\"/>&nbsp;\n"+ " <select multiple=\"false\" name=\""+seqPrefix+"categoryaddon\" size=\"2\">\n"+ " <option value=\"\" selected=\"selected\">"+Messages.getBodyString(locale,"LivelinkConnector.PickACategory")+"</option>\n" ); int j = 0; while (j < categoryList.length) { out.print( " <option value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(categoryList[j])+"\">"+org.apache.manifoldcf.ui.util.Encoder.bodyEscape(categoryList[j])+"</option>\n" ); j++; } out.print( " </select>\n" ); } } } catch (ServiceInterruption e) { //e.printStackTrace(); out.println(org.apache.manifoldcf.ui.util.Encoder.bodyEscape(e.getMessage())); } catch (ManifoldCFException e) { //e.printStackTrace(); out.println(org.apache.manifoldcf.ui.util.Encoder.bodyEscape(e.getMessage())); } out.print( " </td>\n"+ " </tr>\n"+ " <tr><td class=\"separator\" colspan=\"4\"><hr/></td></tr>\n"+ " <tr>\n"+ " <td class=\"description\" colspan=\"1\"><nobr>"+Messages.getBodyString(locale,"LivelinkConnector.PathAttributeName")+"</nobr></td>\n"+ " <td class=\"value\" colspan=\"1\">\n"+ " <input type=\"text\" name=\""+seqPrefix+"specpathnameattribute\" size=\"20\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(pathNameAttribute)+"\"/>\n"+ " </td>\n"+ " <td class=\"description\" colspan=\"1\"><nobr>"+Messages.getBodyString(locale,"LivelinkConnector.PathSeparatorString")+"</nobr></td>\n"+ " <td class=\"value\" colspan=\"1\">\n"+ " <input type=\"text\" name=\""+seqPrefix+"specpathnameseparator\" size=\"20\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(pathNameSeparator)+"\"/>\n"+ " </td>\n"+ " </tr>\n"+ " <tr><td class=\"separator\" colspan=\"4\"><hr/></td></tr>\n" ); i = 0; while (i < matchMap.getMatchCount()) { String matchString = matchMap.getMatchString(i); String replaceString = matchMap.getReplaceString(i); out.print( " <tr>\n"+ " <td class=\"description\">\n"+ " <input type=\"hidden\" name=\""+seqPrefix+"specmappingop_"+Integer.toString(i)+"\" value=\"\"/>\n"+ " <a name=\""+seqPrefix+"mapping_"+Integer.toString(i)+"\">\n"+ " <input type=\"button\" onClick='Javascript:"+seqPrefix+"SpecOp(\""+seqPrefix+"specmappingop_"+Integer.toString(i)+"\",\"Delete\",\""+seqPrefix+"mapping_"+Integer.toString(i)+"\")' alt=\""+Messages.getAttributeString(locale,"LivelinkConnector.DeleteMapping")+Integer.toString(i)+"\" value=\"Delete\"/>\n"+ " </a>\n"+ " </td>\n"+ " <td class=\"value\">\n"+ " <input type=\"hidden\" name=\""+seqPrefix+"specmatch_"+Integer.toString(i)+"\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(matchString)+"\"/>"+org.apache.manifoldcf.ui.util.Encoder.bodyEscape(matchString)+"\n"+ " </td>\n"+ " <td class=\"value\">==></td>\n"+ " <td class=\"value\">\n"+ " <input type=\"hidden\" name=\""+seqPrefix+"specreplace_"+Integer.toString(i)+"\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(replaceString)+"\"/>"+org.apache.manifoldcf.ui.util.Encoder.bodyEscape(replaceString)+"\n"+ " </td>\n"+ " </tr>\n" ); i++; } if (i == 0) { out.print( " <tr><td colspan=\"4\" class=\"message\">"+Messages.getBodyString(locale,"LivelinkConnector.NoMappingsSpecified")+"</td></tr>\n" ); } out.print( " <tr><td class=\"lightseparator\" colspan=\"4\"><hr/></td></tr>\n"+ " <tr>\n"+ " <td class=\"description\">\n"+ " <a name=\""+seqPrefix+"mapping_"+Integer.toString(i)+"\">\n"+ " <input type=\"button\" onClick='Javascript:"+seqPrefix+"SpecAddMapping(\""+seqPrefix+"mapping_"+Integer.toString(i+1)+"\")' alt=\""+Messages.getAttributeString(locale,"LivelinkConnector.AddToMappings")+"\" value=\"Add\"/>\n"+ " </a>\n"+ " </td>\n"+ " <td class=\"value\">Match regexp:&nbsp;<input type=\"text\" name=\""+seqPrefix+"specmatch\" size=\"32\" value=\"\"/></td>\n"+ " <td class=\"value\">==></td>\n"+ " <td class=\"value\">Replace string:&nbsp;<input type=\"text\" name=\""+seqPrefix+"specreplace\" size=\"32\" value=\"\"/></td>\n"+ " </tr>\n"+ "</table>\n" ); } else { out.print( "<input type=\"hidden\" name=\""+seqPrefix+"specallmetadata\" value=\""+ingestAllMetadata+"\"/>\n" ); // Go through the selected metadata attributes i = 0; k = 0; while (i < ds.getChildCount()) { SpecificationNode sn = ds.getChild(i++); if (sn.getType().equals("metadata")) { String accessDescription = "_"+Integer.toString(k); String categoryPath = sn.getAttributeValue("category"); String isAll = sn.getAttributeValue("all"); if (isAll == null) isAll = "false"; String attributeName = sn.getAttributeValue("attribute"); if (attributeName == null) attributeName = ""; out.print( "<input type=\"hidden\" name=\""+seqPrefix+"speccategory"+accessDescription+"\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(categoryPath)+"\"/>\n"+ "<input type=\"hidden\" name=\""+seqPrefix+"specattributeall"+accessDescription+"\" value=\""+isAll+"\"/>\n"+ "<input type=\"hidden\" name=\""+seqPrefix+"specattribute"+accessDescription+"\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(attributeName)+"\"/>\n" ); k++; } } out.print( "<input type=\"hidden\" name=\""+seqPrefix+"metadatacount\" value=\""+Integer.toString(k)+"\"/>\n"+ "<input type=\"hidden\" name=\""+seqPrefix+"specpathnameattribute\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(pathNameAttribute)+"\"/>\n"+ "<input type=\"hidden\" name=\""+seqPrefix+"specpathnameseparator\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(pathNameSeparator)+"\"/>\n"+ "<input type=\"hidden\" name=\""+seqPrefix+"specmappingcount\" value=\""+Integer.toString(matchMap.getMatchCount())+"\"/>\n" ); i = 0; while (i < matchMap.getMatchCount()) { String matchString = matchMap.getMatchString(i); String replaceString = matchMap.getReplaceString(i); out.print( "<input type=\"hidden\" name=\""+seqPrefix+"specmatch_"+Integer.toString(i)+"\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(matchString)+"\"/>\n"+ "<input type=\"hidden\" name=\""+seqPrefix+"specreplace_"+Integer.toString(i)+"\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(replaceString)+"\"/>\n" ); i++; } } } /** Process a specification post. * This method is called at the start of job's edit or view page, whenever there is a possibility that form * data for a connection has been posted. Its purpose is to gather form information and modify the * document specification accordingly. The name of the posted form is always "editjob". * The connector will be connected before this method can be called. *@param variableContext contains the post data, including binary file-upload information. *@param locale is the locale the output is preferred to be in. *@param ds is the current document specification for this job. *@param connectionSequenceNumber is the unique number of this connection within the job. *@return null if all is well, or a string error message if there is an error that should prevent saving of * the job (and cause a redirection to an error page). */ @Override public String processSpecificationPost(IPostParameters variableContext, Locale locale, Specification ds, int connectionSequenceNumber) throws ManifoldCFException { String seqPrefix = "s"+connectionSequenceNumber+"_"; String userWorkspacesPresent = variableContext.getParameter(seqPrefix+"userworkspace_present"); if (userWorkspacesPresent != null) { String value = variableContext.getParameter(seqPrefix+"userworkspace"); int i = 0; while (i < ds.getChildCount()) { SpecificationNode sn = ds.getChild(i); if (sn.getType().equals("userworkspace")) ds.removeChild(i); else i++; } SpecificationNode sn = new SpecificationNode("userworkspace"); sn.setAttribute("value",value); ds.addChild(ds.getChildCount(),sn); } String xc = variableContext.getParameter(seqPrefix+"pathcount"); if (xc != null) { // Delete all path specs first int i = 0; while (i < ds.getChildCount()) { SpecificationNode sn = ds.getChild(i); if (sn.getType().equals("startpoint")) ds.removeChild(i); else i++; } // Find out how many children were sent int pathCount = Integer.parseInt(xc); // Gather up these i = 0; while (i < pathCount) { String pathDescription = "_"+Integer.toString(i); String pathOpName = seqPrefix+"pathop"+pathDescription; xc = variableContext.getParameter(pathOpName); if (xc != null && xc.equals("Delete")) { // Skip to the next i++; continue; } // Path inserts won't happen until the very end String path = variableContext.getParameter(seqPrefix+"specpath"+pathDescription); SpecificationNode node = new SpecificationNode("startpoint"); node.setAttribute("path",path); ds.addChild(ds.getChildCount(),node); i++; } // See if there's a global add operation String op = variableContext.getParameter(seqPrefix+"pathop"); if (op != null && op.equals("Add")) { String path = variableContext.getParameter("specpath"); SpecificationNode node = new SpecificationNode("startpoint"); node.setAttribute("path",path); ds.addChild(ds.getChildCount(),node); } else if (op != null && op.equals("Up")) { // Strip off end String path = variableContext.getParameter(seqPrefix+"specpath"); int lastSlash = -1; int k = 0; while (k < path.length()) { char x = path.charAt(k++); if (x == '/') { lastSlash = k-1; continue; } if (x == '\\') k++; } if (lastSlash == -1) path = ""; else path = path.substring(0,lastSlash); currentContext.save(seqPrefix+"specpath",path); } else if (op != null && op.equals("AddToPath")) { String path = variableContext.getParameter(seqPrefix+"specpath"); String addon = variableContext.getParameter(seqPrefix+"pathaddon"); if (addon != null && addon.length() > 0) { StringBuilder sb = new StringBuilder(); int k = 0; while (k < addon.length()) { char x = addon.charAt(k++); if (x == '/' || x == '\\' || x == ':') sb.append('\\'); sb.append(x); } if (path.length() == 0) path = sb.toString(); else path += "/" + sb.toString(); } currentContext.save(seqPrefix+"specpath",path); } } xc = variableContext.getParameter(seqPrefix+"filecount"); if (xc != null) { // Delete all file specs first int i = 0; while (i < ds.getChildCount()) { SpecificationNode sn = ds.getChild(i); if (sn.getType().equals("include") || sn.getType().equals("exclude")) ds.removeChild(i); else i++; } int fileCount = Integer.parseInt(xc); i = 0; while (i < fileCount) { String fileSpecDescription = "_"+Integer.toString(i); String fileOpName = seqPrefix+"fileop"+fileSpecDescription; xc = variableContext.getParameter(fileOpName); if (xc != null && xc.equals("Delete")) { // Next row i++; continue; } // Get the stuff we need String filespecType = variableContext.getParameter(seqPrefix+"specfiletype"+fileSpecDescription); String filespec = variableContext.getParameter(seqPrefix+"specfile"+fileSpecDescription); SpecificationNode node = new SpecificationNode(filespecType); node.setAttribute("filespec",filespec); ds.addChild(ds.getChildCount(),node); i++; } String op = variableContext.getParameter(seqPrefix+"fileop"); if (op != null && op.equals("Add")) { String filespec = variableContext.getParameter(seqPrefix+"specfile"); String filespectype = variableContext.getParameter(seqPrefix+"specfiletype"); SpecificationNode node = new SpecificationNode(filespectype); node.setAttribute("filespec",filespec); ds.addChild(ds.getChildCount(),node); } } xc = variableContext.getParameter(seqPrefix+"specsecurity"); if (xc != null) { // Delete all security entries first int i = 0; while (i < ds.getChildCount()) { SpecificationNode sn = ds.getChild(i); if (sn.getType().equals("security")) ds.removeChild(i); else i++; } SpecificationNode node = new SpecificationNode("security"); node.setAttribute("value",xc); ds.addChild(ds.getChildCount(),node); } xc = variableContext.getParameter(seqPrefix+"tokencount"); if (xc != null) { // Delete all file specs first int i = 0; while (i < ds.getChildCount()) { SpecificationNode sn = ds.getChild(i); if (sn.getType().equals("access")) ds.removeChild(i); else i++; } int accessCount = Integer.parseInt(xc); i = 0; while (i < accessCount) { String accessDescription = "_"+Integer.toString(i); String accessOpName = seqPrefix+"accessop"+accessDescription; xc = variableContext.getParameter(accessOpName); if (xc != null && xc.equals("Delete")) { // Next row i++; continue; } // Get the stuff we need String accessSpec = variableContext.getParameter(seqPrefix+"spectoken"+accessDescription); SpecificationNode node = new SpecificationNode("access"); node.setAttribute("token",accessSpec); ds.addChild(ds.getChildCount(),node); i++; } String op = variableContext.getParameter(seqPrefix+"accessop"); if (op != null && op.equals("Add")) { String accessspec = variableContext.getParameter(seqPrefix+"spectoken"); SpecificationNode node = new SpecificationNode("access"); node.setAttribute("token",accessspec); ds.addChild(ds.getChildCount(),node); } } xc = variableContext.getParameter(seqPrefix+"specallmetadata"); if (xc != null) { // Look for the 'all metadata' checkbox int i = 0; while (i < ds.getChildCount()) { SpecificationNode sn = ds.getChild(i); if (sn.getType().equals("allmetadata")) ds.removeChild(i); else i++; } if (xc.equals("true")) { SpecificationNode newNode = new SpecificationNode("allmetadata"); newNode.setAttribute("all",xc); ds.addChild(ds.getChildCount(),newNode); } } xc = variableContext.getParameter(seqPrefix+"metadatacount"); if (xc != null) { // Delete all metadata specs first int i = 0; while (i < ds.getChildCount()) { SpecificationNode sn = ds.getChild(i); if (sn.getType().equals("metadata")) ds.removeChild(i); else i++; } // Find out how many children were sent int metadataCount = Integer.parseInt(xc); // Gather up these i = 0; while (i < metadataCount) { String pathDescription = "_"+Integer.toString(i); String pathOpName = seqPrefix+"metadataop"+pathDescription; xc = variableContext.getParameter(pathOpName); if (xc != null && xc.equals("Delete")) { // Skip to the next i++; continue; } // Metadata inserts won't happen until the very end String category = variableContext.getParameter(seqPrefix+"speccategory"+pathDescription); String attributeName = variableContext.getParameter(seqPrefix+"specattribute"+pathDescription); String isAll = variableContext.getParameter(seqPrefix+"specattributeall"+pathDescription); SpecificationNode node = new SpecificationNode("metadata"); node.setAttribute("category",category); if (isAll != null && isAll.equals("true")) node.setAttribute("all","true"); else node.setAttribute("attribute",attributeName); ds.addChild(ds.getChildCount(),node); i++; } // See if there's a global add operation String op = variableContext.getParameter(seqPrefix+"metadataop"); if (op != null && op.equals("Add")) { String category = variableContext.getParameter(seqPrefix+"speccategory"); String isAll = variableContext.getParameter(seqPrefix+"attributeall"); if (isAll != null && isAll.equals("true")) { SpecificationNode node = new SpecificationNode("metadata"); node.setAttribute("category",category); node.setAttribute("all","true"); ds.addChild(ds.getChildCount(),node); } else { String[] attributes = variableContext.getParameterValues(seqPrefix+"attributeselect"); if (attributes != null && attributes.length > 0) { int k = 0; while (k < attributes.length) { String attribute = attributes[k++]; SpecificationNode node = new SpecificationNode("metadata"); node.setAttribute("category",category); node.setAttribute("attribute",attribute); ds.addChild(ds.getChildCount(),node); } } } } else if (op != null && op.equals("Up")) { // Strip off end String category = variableContext.getParameter(seqPrefix+"speccategory"); int lastSlash = -1; int firstColon = -1; int k = 0; while (k < category.length()) { char x = category.charAt(k++); if (x == '/') { lastSlash = k-1; continue; } if (x == ':') { firstColon = k; continue; } if (x == '\\') k++; } if (lastSlash == -1) { if (firstColon == -1 || firstColon == category.length()) category = ""; else category = category.substring(0,firstColon); } else category = category.substring(0,lastSlash); currentContext.save(seqPrefix+"speccategory",category); } else if (op != null && op.equals("AddToPath")) { String category = variableContext.getParameter(seqPrefix+"speccategory"); String addon = variableContext.getParameter(seqPrefix+"metadataaddon"); if (addon != null && addon.length() > 0) { StringBuilder sb = new StringBuilder(); int k = 0; while (k < addon.length()) { char x = addon.charAt(k++); if (x == '/' || x == '\\' || x == ':') sb.append('\\'); sb.append(x); } if (category.length() == 0 || category.endsWith(":")) category += sb.toString(); else category += "/" + sb.toString(); } currentContext.save(seqPrefix+"speccategory",category); } else if (op != null && op.equals("SetWorkspace")) { String addon = variableContext.getParameter(seqPrefix+"metadataaddon"); if (addon != null && addon.length() > 0) { StringBuilder sb = new StringBuilder(); int k = 0; while (k < addon.length()) { char x = addon.charAt(k++); if (x == '/' || x == '\\' || x == ':') sb.append('\\'); sb.append(x); } String category = sb.toString() + ":"; currentContext.save(seqPrefix+"speccategory",category); } } else if (op != null && op.equals("AddCategory")) { String category = variableContext.getParameter(seqPrefix+"speccategory"); String addon = variableContext.getParameter(seqPrefix+"categoryaddon"); if (addon != null && addon.length() > 0) { StringBuilder sb = new StringBuilder(); int k = 0; while (k < addon.length()) { char x = addon.charAt(k++); if (x == '/' || x == '\\' || x == ':') sb.append('\\'); sb.append(x); } if (category.length() == 0 || category.endsWith(":")) category += sb.toString(); else category += "/" + sb.toString(); } currentContext.save(seqPrefix+"speccategory",category); } } xc = variableContext.getParameter(seqPrefix+"specpathnameattribute"); if (xc != null) { String separator = variableContext.getParameter(seqPrefix+"specpathnameseparator"); if (separator == null) separator = "/"; // Delete old one int i = 0; while (i < ds.getChildCount()) { SpecificationNode sn = ds.getChild(i); if (sn.getType().equals("pathnameattribute")) ds.removeChild(i); else i++; } if (xc.length() > 0) { SpecificationNode node = new SpecificationNode("pathnameattribute"); node.setAttribute("value",xc); node.setAttribute("separator",separator); ds.addChild(ds.getChildCount(),node); } } xc = variableContext.getParameter(seqPrefix+"specmappingcount"); if (xc != null) { // Delete old spec int i = 0; while (i < ds.getChildCount()) { SpecificationNode sn = ds.getChild(i); if (sn.getType().equals("pathmap")) ds.removeChild(i); else i++; } // Now, go through the data and assemble a new list. int mappingCount = Integer.parseInt(xc); // Gather up these i = 0; while (i < mappingCount) { String pathDescription = "_"+Integer.toString(i); String pathOpName = seqPrefix+"specmappingop"+pathDescription; xc = variableContext.getParameter(pathOpName); if (xc != null && xc.equals("Delete")) { // Skip to the next i++; continue; } // Inserts won't happen until the very end String match = variableContext.getParameter(seqPrefix+"specmatch"+pathDescription); String replace = variableContext.getParameter(seqPrefix+"specreplace"+pathDescription); SpecificationNode node = new SpecificationNode("pathmap"); node.setAttribute("match",match); node.setAttribute("replace",replace); ds.addChild(ds.getChildCount(),node); i++; } // Check for add xc = variableContext.getParameter(seqPrefix+"specmappingop"); if (xc != null && xc.equals("Add")) { String match = variableContext.getParameter(seqPrefix+"specmatch"); String replace = variableContext.getParameter(seqPrefix+"specreplace"); SpecificationNode node = new SpecificationNode("pathmap"); node.setAttribute("match",match); node.setAttribute("replace",replace); ds.addChild(ds.getChildCount(),node); } } return null; } /** View specification. * This method is called in the body section of a job's view page. Its purpose is to present the document * specification information to the user. The coder can presume that the HTML that is output from * this configuration will be within appropriate <html> and <body> tags. * The connector will be connected before this method can be called. *@param out is the output to which any HTML should be sent. *@param locale is the locale the output is preferred to be in. *@param ds is the current document specification for this job. *@param connectionSequenceNumber is the unique number of this connection within the job. */ @Override public void viewSpecification(IHTTPOutput out, Locale locale, Specification ds, int connectionSequenceNumber) throws ManifoldCFException, IOException { out.print( "<table class=\"displaytable\">\n"+ " <tr>\n" ); int i = 0; boolean userWorkspaces = false; while (i < ds.getChildCount()) { SpecificationNode sn = ds.getChild(i++); if (sn.getType().equals("userworkspace")) { String value = sn.getAttributeValue("value"); if (value != null && value.equals("true")) userWorkspaces = true; } } out.print( " <td class=\"description\"/>\n"+ " <nobr>"+Messages.getBodyString(locale,"LivelinkConnector.CrawlUserWorkspaces")+"</nobr>\n"+ " </td>\n"+ " <td class=\"value\"/>\n"+ " "+(userWorkspaces?Messages.getBodyString(locale,"LivelinkConnector.Yes"):Messages.getBodyString(locale,"LivelinkConnector.No"))+"\n"+ " </td>\n"+ " </tr>" ); out.print( " <tr><td class=\"separator\" colspan=\"2\"><hr/></td></tr>\n" ); out.print( " <tr>" ); i = 0; boolean seenAny = false; while (i < ds.getChildCount()) { SpecificationNode sn = ds.getChild(i++); if (sn.getType().equals("startpoint")) { if (seenAny == false) { out.print( " <td class=\"description\">"+Messages.getBodyString(locale,"LivelinkConnector.Roots")+"</td>\n"+ " <td class=\"value\">\n" ); seenAny = true; } out.print( " "+org.apache.manifoldcf.ui.util.Encoder.bodyEscape(sn.getAttributeValue("path"))+"<br/>\n" ); } } if (seenAny) { out.print( " </td>\n"+ " </tr>\n" ); } else { out.print( " <tr><td class=\"message\" colspan=\"2\">"+Messages.getBodyString(locale,"LivelinkConnector.NoStartPointsSpecified")+"</td></tr>\n" ); } out.print( " <tr><td class=\"separator\" colspan=\"2\"><hr/></td></tr>\n" ); seenAny = false; // Go through looking for include or exclude file specs i = 0; while (i < ds.getChildCount()) { SpecificationNode sn = ds.getChild(i++); if (sn.getType().equals("include") || sn.getType().equals("exclude")) { if (seenAny == false) { out.print( " <tr><td class=\"description\">"+Messages.getBodyString(locale,"LivelinkConnector.FileSpecs")+"</td>\n"+ " <td class=\"value\">\n" ); seenAny = true; } String filespec = sn.getAttributeValue("filespec"); out.print( " "+(sn.getType().equals("include")?"Include file:":"")+"\n"+ " "+(sn.getType().equals("exclude")?"Exclude file:":"")+"\n"+ " "+org.apache.manifoldcf.ui.util.Encoder.bodyEscape(filespec)+"<br/>\n" ); } } if (seenAny) { out.print( " </td>\n"+ " </tr>\n" ); } else { out.print( " <tr><td class=\"message\" colspan=\"2\">"+Messages.getBodyString(locale,"LivelinkConnector.NoFileSpecsSpecified")+"</td></tr>\n" ); } out.print( " <tr><td class=\"separator\" colspan=\"2\"><hr/></td></tr>\n" ); // Find whether security is on or off i = 0; boolean securityOn = true; while (i < ds.getChildCount()) { SpecificationNode sn = ds.getChild(i++); if (sn.getType().equals("security")) { String securityValue = sn.getAttributeValue("value"); if (securityValue.equals("off")) securityOn = false; else if (securityValue.equals("on")) securityOn = true; } } out.print( " <tr>\n"+ " <td class=\"description\">"+Messages.getBodyString(locale,"LivelinkConnector.SecurityColon")+"</td>\n"+ " <td class=\"value\">"+(securityOn?Messages.getBodyString(locale,"LivelinkConnector.Enabled2"):Messages.getBodyString(locale,"LivelinkConnector.Disabled"))+"</td>\n"+ " </tr>\n"+ "\n"+ " <tr><td class=\"separator\" colspan=\"2\"><hr/></td></tr>\n" ); // Go through looking for access tokens seenAny = false; i = 0; while (i < ds.getChildCount()) { SpecificationNode sn = ds.getChild(i++); if (sn.getType().equals("access")) { if (seenAny == false) { out.print( " <tr><td class=\"description\">"+Messages.getBodyString(locale,"LivelinkConnector.AccessTokens")+"</td>\n"+ " <td class=\"value\">\n" ); seenAny = true; } String token = sn.getAttributeValue("token"); out.print( " "+org.apache.manifoldcf.ui.util.Encoder.bodyEscape(token)+"<br/>\n" ); } } if (seenAny) { out.print( " </td>\n"+ " </tr>\n" ); } else { out.print( " <tr><td class=\"message\" colspan=\"2\">" + Messages.getBodyString(locale,"LivelinkConnector.NoAccessTokensSpecified") + "</td></tr>\n" ); } out.print( " <tr><td class=\"separator\" colspan=\"2\"><hr/></td></tr>\n" ); i = 0; String allMetadata = Messages.getBodyString(locale,"LivelinkConnector.OnlySpecifiedMetadataWillBeIngested"); while (i < ds.getChildCount()) { SpecificationNode sn = ds.getChild(i++); if (sn.getType().equals("allmetadata")) { String value = sn.getAttributeValue("all"); if (value != null && value.equals("true")) { allMetadata=Messages.getBodyString(locale,"LivelinkConnector.AllDocumentMetadataWillBeIngested"); } } } out.print( " <tr>\n"+ " <td class=\"description\"><nobr>"+Messages.getBodyString(locale,"LivelinkConnector.MetadataSpecification")+"</nobr></td>\n"+ " <td class=\"value\"><nobr>"+allMetadata+"</nobr></td>\n"+ " </tr>\n"+ " <tr><td class=\"separator\" colspan=\"2\"><hr/></td></tr>\n" ); // Go through looking for metadata spec seenAny = false; i = 0; while (i < ds.getChildCount()) { SpecificationNode sn = ds.getChild(i++); if (sn.getType().equals("metadata")) { if (seenAny == false) { out.print( " <tr><td class=\"description\"><nobr>"+Messages.getBodyString(locale,"LivelinkConnector.SpecificMetadata")+"</nobr></td>\n"+ " <td class=\"value\">\n" ); seenAny = true; } String category = sn.getAttributeValue("category"); String attribute = sn.getAttributeValue("attribute"); String isAll = sn.getAttributeValue("all"); out.print( " "+org.apache.manifoldcf.ui.util.Encoder.bodyEscape(category)+":"+((isAll!=null&&isAll.equals("true"))?"(All metadata attributes)":org.apache.manifoldcf.ui.util.Encoder.bodyEscape(attribute))+"<br/>\n" ); } } if (seenAny) { out.print( " </td>\n"+ " </tr>\n" ); } else { out.print( " <tr><td class=\"message\" colspan=\"2\">"+Messages.getBodyString(locale,"LivelinkConnector.NoMetadataSpecified")+"</td></tr>\n" ); } out.print( " <tr><td class=\"separator\" colspan=\"2\"><hr/></td></tr>\n" ); // Find the path-name metadata attribute name i = 0; String pathNameAttribute = ""; String pathSeparator = "/"; while (i < ds.getChildCount()) { SpecificationNode sn = ds.getChild(i++); if (sn.getType().equals("pathnameattribute")) { pathNameAttribute = sn.getAttributeValue("value"); if (sn.getAttributeValue("separator") != null) pathSeparator = sn.getAttributeValue("separator"); } } if (pathNameAttribute.length() > 0) { out.print( " <tr>\n"+ " <td class=\"description\">"+Messages.getBodyString(locale,"LivelinkConnector.PathNameMetadataAttribute")+"</td>\n"+ " <td class=\"value\">"+org.apache.manifoldcf.ui.util.Encoder.bodyEscape(pathNameAttribute)+"</td>\n"+ " </tr>\n"+ " <tr>\n"+ " <td class=\"description\">"+Messages.getBodyString(locale,"LivelinkConnector.PathSeparatorString")+"</td>\n"+ " <td class=\"value\">"+org.apache.manifoldcf.ui.util.Encoder.bodyEscape(pathSeparator)+"</td>\n"+ " </tr>\n" ); } else { out.print( " <tr>\n"+ " <td class=\"message\" colspan=\"2\">"+Messages.getBodyString(locale,"LivelinkConnector.NoPathNameMetadataAttributeSpecified")+"</td>\n"+ " </tr>\n" ); } out.print( "\n"+ " <tr><td class=\"separator\" colspan=\"2\"><hr/></td></tr>\n"+ "\n"+ " <tr>\n" ); // Find the path-value mapping data i = 0; MatchMap matchMap = new MatchMap(); while (i < ds.getChildCount()) { SpecificationNode sn = ds.getChild(i++); if (sn.getType().equals("pathmap")) { String pathMatch = sn.getAttributeValue("match"); String pathReplace = sn.getAttributeValue("replace"); matchMap.appendMatchPair(pathMatch,pathReplace); } } if (matchMap.getMatchCount() > 0) { out.print( " <td class=\"description\">"+Messages.getBodyString(locale,"LivelinkConnector.PathValueMapping")+"</td>\n"+ " <td class=\"value\">\n"+ " <table class=\"displaytable\">\n" ); i = 0; while (i < matchMap.getMatchCount()) { String matchString = matchMap.getMatchString(i); String replaceString = matchMap.getReplaceString(i); out.print( " <tr>\n"+ " <td class=\"value\">"+org.apache.manifoldcf.ui.util.Encoder.bodyEscape(matchString)+"</td>\n"+ " <td class=\"value\">--></td>\n"+ " <td class=\"value\">"+org.apache.manifoldcf.ui.util.Encoder.bodyEscape(replaceString)+"</td>\n"+ " </tr>\n" ); i++; } out.print( " </table>\n"+ " </td>\n" ); } else { out.print( " <td class=\"message\" colspan=\"2\">"+Messages.getBodyString(locale,"LivelinkConnector.NoMappingsSpecified")+"</td>\n" ); } out.print( " </tr>\n"+ "</table>\n" ); } // The following public methods are NOT part of the interface. They are here so that the UI can present information // that will allow users to select what they need. protected final static String CATEGORY_NAME = "CATEGORY"; protected final static String ENTWKSPACE_NAME = "ENTERPRISE"; /** Get the allowed workspace names. *@return a list of workspace names. */ public String[] getWorkspaceNames() throws ManifoldCFException, ServiceInterruption { return new String[]{CATEGORY_NAME,ENTWKSPACE_NAME}; } /** Given a path string, get a list of folders and projects under that node. *@param pathString is the current path (folder names and project names, separated by dots (.)). *@return a list of folder and project names, in sorted order, or null if the path was invalid. */ public String[] getChildFolderNames(String pathString) throws ManifoldCFException, ServiceInterruption { getSession(); return getChildFolders(new LivelinkContext(),pathString); } /** Given a path string, get a list of categories under that node. *@param pathString is the current path (folder names and project names, separated by dots (.)). *@return a list of category names, in sorted order, or null if the path was invalid. */ public String[] getChildCategoryNames(String pathString) throws ManifoldCFException, ServiceInterruption { getSession(); return getChildCategories(new LivelinkContext(),pathString); } /** Given a category path, get a list of legal attribute names. *@param pathString is the current path of a category (with path components separated by dots). *@return a list of attribute names, in sorted order, or null of the path was invalid. */ public String[] getCategoryAttributes(String pathString) throws ManifoldCFException, ServiceInterruption { getSession(); return getCategoryAttributes(new LivelinkContext(), pathString); } protected String[] getCategoryAttributes(LivelinkContext llc, String pathString) throws ManifoldCFException, ServiceInterruption { // Start at root RootValue rv = new RootValue(llc,pathString); // Get the object id of the category the path describes int catObjectID = getCategoryId(rv); if (catObjectID == -1) return null; String[] rval = getCategoryAttributes(catObjectID); if (rval == null) return new String[0]; return rval; } // Protected methods and classes /** Create the login URI. This must be a relative URI. */ protected String createLivelinkLoginURI() throws ManifoldCFException { StringBuilder llURI = new StringBuilder(); llURI.append(ingestCgiPath); llURI.append("?func=ll.login&CurrentClientTime=D%2F2005%2F3%2F9%3A13%3A16%3A30&NextURL="); llURI.append(org.apache.manifoldcf.core.util.URLEncoder.encode(ingestCgiPath)); llURI.append("%3FRedirect%3D1&Username="); llURI.append(org.apache.manifoldcf.core.util.URLEncoder.encode(llServer.getLLUser())); llURI.append("&Password="); llURI.append(org.apache.manifoldcf.core.util.URLEncoder.encode(llServer.getLLPwd())); return llURI.toString(); } /** * Connects to the specified Livelink document using HTTP protocol * @param documentIdentifier is the document identifier (as far as the crawler knows). * @param activities is the process activity structure, so we can ingest */ protected void ingestFromLiveLink(LivelinkContext llc, String documentIdentifier, String version, String[] actualAcls, String[] denyAcls, String[] categoryPaths, IProcessActivity activities, MetadataDescription desc, SystemMetadataDescription sDesc) throws ManifoldCFException, ServiceInterruption { String contextMsg = "for '"+documentIdentifier+"'"; // Fetch logging long startTime = System.currentTimeMillis(); String resultCode = null; String resultDescription = null; Long readSize = null; int objID; int vol; int colonPos = documentIdentifier.indexOf(":",1); if (colonPos == -1) { objID = new Integer(documentIdentifier.substring(1)).intValue(); vol = LLENTWK_VOL; } else { objID = new Integer(documentIdentifier.substring(colonPos+1)).intValue(); vol = new Integer(documentIdentifier.substring(1,colonPos)).intValue(); } // Try/finally for fetch logging try { String viewHttpAddress = convertToViewURI(documentIdentifier); if (viewHttpAddress == null) { if (Logging.connectors.isDebugEnabled()) Logging.connectors.debug("Livelink: No view URI "+contextMsg+" - not ingesting"); resultCode = "NOVIEWURI"; resultDescription = "Document had no view URI"; activities.noDocument(documentIdentifier,version); return; } // Check URL first if (!activities.checkURLIndexable(viewHttpAddress)) { // Document not ingestable due to URL resultCode = activities.EXCLUDED_URL; resultDescription = "URL ("+viewHttpAddress+") was rejected by output connector"; if (Logging.connectors.isDebugEnabled()) Logging.connectors.debug("Livelink: Excluding document "+documentIdentifier+" because its URL ("+viewHttpAddress+") was rejected by output connector"); activities.noDocument(documentIdentifier,version); return; } // Add general metadata ObjectInformation objInfo = llc.getObjectInformation(vol,objID); VersionInformation versInfo = llc.getVersionInformation(vol,objID,0); if (!objInfo.exists()) { resultCode = "OBJECTNOTFOUND"; resultDescription = "Object was not found in Livelink"; Logging.connectors.debug("Livelink: No object "+contextMsg+": not ingesting"); activities.noDocument(documentIdentifier,version); return; } if (!versInfo.exists()) { resultCode = "VERSIONNOTFOUND"; resultDescription = "Version was not found in Livelink"; Logging.connectors.debug("Livelink: No version data "+contextMsg+": not ingesting"); activities.noDocument(documentIdentifier,version); return; } String mimeType = versInfo.getMimeType(); if (!activities.checkMimeTypeIndexable(mimeType)) { // Document not indexable because of its mime type resultCode = activities.EXCLUDED_MIMETYPE; resultDescription = "Mime type ("+mimeType+") was rejected by output connector"; if (Logging.connectors.isDebugEnabled()) Logging.connectors.debug("Livelink: Excluding document "+documentIdentifier+" because its mime type ("+mimeType+") was rejected by output connector"); activities.noDocument(documentIdentifier,version); return; } Long dataSize = versInfo.getDataSize(); if (dataSize == null) { // Document had no length resultCode = "DOCUMENTNOLENGTH"; resultDescription = "Document had no length in Livelink"; if (Logging.connectors.isDebugEnabled()) Logging.connectors.debug("Livelink: Excluding document "+documentIdentifier+" because it had no length"); activities.noDocument(documentIdentifier,version); return; } if (!activities.checkLengthIndexable(dataSize.longValue())) { // Document not indexable because of its length resultCode = activities.EXCLUDED_LENGTH; resultDescription = "Document length ("+dataSize+") was rejected by output connector"; if (Logging.connectors.isDebugEnabled()) Logging.connectors.debug("Livelink: Excluding document "+documentIdentifier+" because its length ("+dataSize+") was rejected by output connector"); activities.noDocument(documentIdentifier,version); return; } Date modifyDate = versInfo.getModifyDate(); if (!activities.checkDateIndexable(modifyDate)) { // Document not indexable because of its date resultCode = activities.EXCLUDED_DATE; resultDescription = "Document date ("+modifyDate+") was rejected by output connector"; if (Logging.connectors.isDebugEnabled()) Logging.connectors.debug("Livelink: Excluding document "+documentIdentifier+" because its date ("+modifyDate+") was rejected by output connector"); activities.noDocument(documentIdentifier,version); return; } String fileName = versInfo.getFileName(); Date creationDate = objInfo.getCreationDate(); Integer parentID = objInfo.getParentId(); RepositoryDocument rd = new RepositoryDocument(); // Add general data we need for the output connector if (mimeType != null) rd.setMimeType(mimeType); if (fileName != null) rd.setFileName(fileName); if (creationDate != null) rd.setCreatedDate(creationDate); if (modifyDate != null) rd.setModifiedDate(modifyDate); rd.addField(GENERAL_NAME_FIELD,objInfo.getName()); rd.addField(GENERAL_DESCRIPTION_FIELD,objInfo.getComments()); if (creationDate != null) rd.addField(GENERAL_CREATIONDATE_FIELD,DateParser.formatISO8601Date(creationDate)); if (modifyDate != null) rd.addField(GENERAL_MODIFYDATE_FIELD,DateParser.formatISO8601Date(modifyDate)); if (parentID != null) rd.addField(GENERAL_PARENTID,parentID.toString()); UserInformation owner = llc.getUserInformation(objInfo.getOwnerId().intValue()); UserInformation creator = llc.getUserInformation(objInfo.getCreatorId().intValue()); UserInformation modifier = llc.getUserInformation(versInfo.getOwnerId().intValue()); if (owner != null) rd.addField(GENERAL_OWNER,owner.getName()); if (creator != null) rd.addField(GENERAL_CREATOR,creator.getName()); if (modifier != null) rd.addField(GENERAL_MODIFIER,modifier.getName()); // Iterate over the metadata items. These are organized by category // for speed of lookup. Iterator<MetadataItem> catIter = desc.getItems(categoryPaths); while (catIter.hasNext()) { MetadataItem item = catIter.next(); MetadataPathItem pathItem = item.getPathItem(); if (pathItem != null) { int catID = pathItem.getCatID(); // grab the associated catversion LLValue catVersion = getCatVersion(objID,catID); if (catVersion != null) { // Go through attributes now Iterator<String> attrIter = item.getAttributeNames(); while (attrIter.hasNext()) { String attrName = attrIter.next(); // Create a unique metadata name String metadataName = pathItem.getCatName()+":"+attrName; // Fetch the metadata and stuff it into the RepositoryData structure String[] metadataValue = getAttributeValue(catVersion,attrName); if (metadataValue != null) rd.addField(metadataName,metadataValue); else Logging.connectors.warn("Livelink: Metadata attribute '"+metadataName+"' does not seem to exist; please correct the job"); } } } } if (actualAcls != null && denyAcls != null) rd.setSecurity(RepositoryDocument.SECURITY_TYPE_DOCUMENT,actualAcls,denyAcls); // Add the path metadata item into the mix, if enabled String pathAttributeName = sDesc.getPathAttributeName(); if (pathAttributeName != null && pathAttributeName.length() > 0) { String pathString = sDesc.getPathAttributeValue(documentIdentifier); if (pathString != null) { if (Logging.connectors.isDebugEnabled()) Logging.connectors.debug("Livelink: Path attribute name is '"+pathAttributeName+"'"+contextMsg+", value is '"+pathString+"'"); rd.addField(pathAttributeName,pathString); } } if (ingestProtocol != null) { // Use HTTP to fetch document! String ingestHttpAddress = convertToIngestURI(documentIdentifier); if (ingestHttpAddress == null) { if (Logging.connectors.isDebugEnabled()) Logging.connectors.debug("Livelink: No fetch URI "+contextMsg+" - not ingesting"); resultCode = "NOURI"; resultDescription = "Document had no fetch URI"; activities.noDocument(documentIdentifier,version); return; } // Set up connection HttpClient client = getInitializedClient(contextMsg); long currentTime; if (Logging.connectors.isInfoEnabled()) Logging.connectors.info("Livelink: " + ingestHttpAddress); HttpGet method = new HttpGet(getHost().toURI() + ingestHttpAddress); method.setHeader(new BasicHeader("Accept","*/*")); boolean wasInterrupted = false; ExecuteMethodThread methodThread = new ExecuteMethodThread(client,method); methodThread.start(); try { int statusCode = methodThread.getResponseCode(); switch (statusCode) { case 500: case 502: Logging.connectors.warn("Livelink: Service interruption during fetch "+contextMsg+" with Livelink HTTP Server, retrying..."); resultCode = "FETCHFAILED"; resultDescription = "HTTP error code "+statusCode+" fetching document"; throw new ServiceInterruption("Service interruption during fetch",new ManifoldCFException(Integer.toString(statusCode)+" error while fetching"),System.currentTimeMillis()+60000L, System.currentTimeMillis()+600000L,-1,true); case HttpStatus.SC_UNAUTHORIZED: Logging.connectors.warn("Livelink: Document fetch unauthorized for "+ingestHttpAddress+" ("+contextMsg+")"); // Since we logged in, we should fail here if the ingestion user doesn't have access to the // the document, but if we do, don't fail hard. resultCode = "UNAUTHORIZED"; resultDescription = "Document fetch was unauthorized by IIS"; activities.noDocument(documentIdentifier,version); return; case HttpStatus.SC_OK: if (Logging.connectors.isDebugEnabled()) Logging.connectors.debug("Livelink: Created http document connection to Livelink "+contextMsg); // A non-existent content length will cause a value of -1 to be returned. This seems to indicate that the session login did not work right. if (methodThread.getResponseContentLength() < 0) { resultCode = "SESSIONLOGINFAILED"; resultDescription = "Response content length was -1, which usually means session login did not succeed"; activities.noDocument(documentIdentifier,version); return; } try { InputStream is = methodThread.getSafeInputStream(); try { rd.setBinary(is,dataSize); activities.ingestDocumentWithException(documentIdentifier,version,viewHttpAddress,rd); resultCode = "OK"; readSize = dataSize; if (Logging.connectors.isDebugEnabled()) Logging.connectors.debug("Livelink: Ingesting done "+contextMsg); } finally { // Close stream via thread, since otherwise this can hang is.close(); } } catch (InterruptedException e) { wasInterrupted = true; throw new ManifoldCFException("Interrupted: "+e.getMessage(),e,ManifoldCFException.INTERRUPTED); } catch (HttpException e) { resultCode = e.getClass().getSimpleName().toUpperCase(Locale.ROOT); resultDescription = e.getMessage(); handleHttpException(contextMsg,e); } catch (IOException e) { resultCode = e.getClass().getSimpleName().toUpperCase(Locale.ROOT); resultDescription = e.getMessage(); handleIOException(contextMsg,e); } break; case HttpStatus.SC_BAD_REQUEST: case HttpStatus.SC_USE_PROXY: case HttpStatus.SC_GONE: resultCode = "HTTPERROR"; resultDescription = "Http request returned status "+Integer.toString(statusCode); throw new ManifoldCFException("Unrecoverable request failure; error = "+Integer.toString(statusCode)); default: resultCode = "UNKNOWNHTTPCODE"; resultDescription = "Http request returned status "+Integer.toString(statusCode); Logging.connectors.warn("Livelink: Attempt to retrieve document from '"+ingestHttpAddress+"' received a response of "+Integer.toString(statusCode)+"; retrying in one minute"); currentTime = System.currentTimeMillis(); throw new ServiceInterruption("Fetch failed; retrying in 1 minute",new ManifoldCFException("Fetch failed with unknown code "+Integer.toString(statusCode)), currentTime+60000L,currentTime+600000L,-1,true); } } catch (InterruptedException e) { // Drop the connection on the floor methodThread.interrupt(); methodThread = null; throw new ManifoldCFException("Interrupted: "+e.getMessage(),e,ManifoldCFException.INTERRUPTED); } catch (HttpException e) { resultCode = e.getClass().getSimpleName().toUpperCase(Locale.ROOT); resultDescription = e.getMessage(); handleHttpException(contextMsg,e); } catch (IOException e) { resultCode = e.getClass().getSimpleName().toUpperCase(Locale.ROOT); resultDescription = e.getMessage(); handleIOException(contextMsg,e); } finally { if (methodThread != null) { methodThread.abort(); try { if (!wasInterrupted) methodThread.finishUp(); } catch (InterruptedException e) { throw new ManifoldCFException(e.getMessage(),e,ManifoldCFException.INTERRUPTED); } } } } else { // Use FetchVersion instead long currentTime; // Fire up the document reading thread DocumentReadingThread t = new DocumentReadingThread(vol,objID,0); boolean wasInterrupted = false; t.start(); try { try { InputStream is = t.getSafeInputStream(); try { // Can only index while background thread is running! rd.setBinary(is, dataSize); activities.ingestDocumentWithException(documentIdentifier, version, viewHttpAddress, rd); resultCode = "OK"; readSize = dataSize; } finally { is.close(); } } catch (java.net.SocketTimeoutException e) { throw e; } catch (InterruptedIOException e) { wasInterrupted = true; throw e; } finally { if (!wasInterrupted) t.finishUp(); } // No errors. Record the fact that we made it. } catch (InterruptedException e) { t.interrupt(); throw new ManifoldCFException("Interrupted: " + e.getMessage(), e, ManifoldCFException.INTERRUPTED); } catch (IOException e) { resultCode = e.getClass().getSimpleName().toUpperCase(Locale.ROOT); resultDescription = e.getMessage(); handleIOException(contextMsg,e); } catch (RuntimeException e) { resultCode = e.getClass().getSimpleName().toUpperCase(Locale.ROOT); resultDescription = e.getMessage(); handleLivelinkRuntimeException(e,0,true); } } } catch (ManifoldCFException e) { if (e.getErrorCode() == ManifoldCFException.INTERRUPTED) resultCode = null; throw e; } finally { if (resultCode != null) activities.recordActivity(new Long(startTime),ACTIVITY_FETCH,readSize,vol+":"+objID,resultCode,resultDescription,null); } } protected static void handleHttpException(String contextMsg, HttpException e) throws ManifoldCFException, ServiceInterruption { long currentTime = System.currentTimeMillis(); // Treat unknown error ingesting data as a transient condition Logging.connectors.warn("Livelink: HTTP exception ingesting "+contextMsg+": "+e.getMessage(),e); throw new ServiceInterruption("HTTP exception ingesting "+contextMsg+": "+e.getMessage(),e,currentTime+300000L,currentTime+6*3600000L,-1,false); } protected static void handleIOException(String contextMsg, IOException e) throws ManifoldCFException, ServiceInterruption { long currentTime = System.currentTimeMillis(); if (e instanceof java.net.SocketTimeoutException) { Logging.connectors.warn("Livelink: Livelink socket timed out ingesting from the Livelink HTTP Server "+contextMsg+": "+e.getMessage(), e); throw new ServiceInterruption("Socket timed out: "+e.getMessage(),e,currentTime+300000L,currentTime+6*3600000L,-1,false); } if (e instanceof java.net.SocketException) { Logging.connectors.warn("Livelink: Livelink socket error ingesting from the Livelink HTTP Server "+contextMsg+": "+e.getMessage(), e); throw new ServiceInterruption("Socket error: "+e.getMessage(),e,currentTime+300000L,currentTime+6*3600000L,-1,false); } if (e instanceof javax.net.ssl.SSLHandshakeException) { Logging.connectors.warn("Livelink: SSL handshake failed authenticating "+contextMsg+": "+e.getMessage(),e); throw new ServiceInterruption("SSL handshake error: "+e.getMessage(),e,currentTime+60000L,currentTime+300000L,-1,true); } if (e instanceof ConnectTimeoutException) { Logging.connectors.warn("Livelink: Livelink socket timed out connecting to the Livelink HTTP Server "+contextMsg+": "+e.getMessage(), e); throw new ServiceInterruption("Connect timed out: "+e.getMessage(),e,currentTime+300000L,currentTime+6*3600000L,-1,false); } if (e instanceof InterruptedIOException) throw new ManifoldCFException("Interrupted: "+e.getMessage(),e,ManifoldCFException.INTERRUPTED); // Treat unknown error ingesting data as a transient condition Logging.connectors.warn("Livelink: IO exception ingesting "+contextMsg+": "+e.getMessage(),e); throw new ServiceInterruption("IO exception ingesting "+contextMsg+": "+e.getMessage(),e,currentTime+300000L,currentTime+6*3600000L,-1,false); } /** Initialize a livelink client connection */ protected HttpClient getInitializedClient(String contextMsg) throws ServiceInterruption, ManifoldCFException { long currentTime; if (Logging.connectors.isDebugEnabled()) Logging.connectors.debug("Livelink: Session authenticating via http "+contextMsg+"..."); HttpGet authget = new HttpGet(getHost().toURI() + createLivelinkLoginURI()); authget.setHeader(new BasicHeader("Accept","*/*")); try { if (Logging.connectors.isDebugEnabled()) Logging.connectors.debug("Livelink: Created new HttpGet "+contextMsg+"; executing authentication method"); int statusCode = executeMethodViaThread(httpClient,authget); if (statusCode == 502 || statusCode == 500) { Logging.connectors.warn("Livelink: Service interruption during authentication "+contextMsg+" with Livelink HTTP Server, retrying..."); currentTime = System.currentTimeMillis(); throw new ServiceInterruption("502 error during authentication",new ManifoldCFException("502 error while authenticating"), currentTime+60000L,currentTime+600000L,-1,true); } if (statusCode != HttpStatus.SC_OK) { Logging.connectors.error("Livelink: Failed to authenticate "+contextMsg+" against Livelink HTTP Server; Status code: " + statusCode); // Ok, so we didn't get in - simply do not ingest if (statusCode == HttpStatus.SC_UNAUTHORIZED) throw new ManifoldCFException("Session authorization failed with a 401 code; are credentials correct?"); else throw new ManifoldCFException("Session authorization failed with code "+Integer.toString(statusCode)); } } catch (InterruptedException e) { throw new ManifoldCFException("Interrupted: "+e.getMessage(),e,ManifoldCFException.INTERRUPTED); } catch (java.net.SocketTimeoutException e) { currentTime = System.currentTimeMillis(); Logging.connectors.warn("Livelink: Socket timed out authenticating to the Livelink HTTP Server "+contextMsg+": "+e.getMessage(), e); throw new ServiceInterruption("Socket timed out: "+e.getMessage(),e,currentTime+300000L,currentTime+6*3600000L,-1,true); } catch (java.net.SocketException e) { currentTime = System.currentTimeMillis(); Logging.connectors.warn("Livelink: Socket error authenticating to the Livelink HTTP Server "+contextMsg+": "+e.getMessage(), e); throw new ServiceInterruption("Socket error: "+e.getMessage(),e,currentTime+300000L,currentTime+6*3600000L,-1,true); } catch (javax.net.ssl.SSLHandshakeException e) { currentTime = System.currentTimeMillis(); Logging.connectors.warn("Livelink: SSL handshake failed authenticating "+contextMsg+": "+e.getMessage(),e); throw new ServiceInterruption("SSL handshake error: "+e.getMessage(),e,currentTime+60000L,currentTime+300000L,-1,true); } catch (ConnectTimeoutException e) { currentTime = System.currentTimeMillis(); Logging.connectors.warn("Livelink: Connect timed out authenticating to the Livelink HTTP Server "+contextMsg+": "+e.getMessage(), e); throw new ServiceInterruption("Connect timed out: "+e.getMessage(),e,currentTime+300000L,currentTime+6*3600000L,-1,true); } catch (InterruptedIOException e) { throw new ManifoldCFException("Interrupted: "+e.getMessage(),e,ManifoldCFException.INTERRUPTED); } catch (HttpException e) { Logging.connectors.error("Livelink: HTTP exception when authenticating to the Livelink HTTP Server "+contextMsg+": "+e.getMessage(), e); throw new ManifoldCFException("Unable to communicate with the Livelink HTTP Server: "+e.getMessage(), e); } catch (IOException e) { Logging.connectors.error("Livelink: IO exception when authenticating to the Livelink HTTP Server "+contextMsg+": "+e.getMessage(), e); throw new ManifoldCFException("Unable to communicate with the Livelink HTTP Server: "+e.getMessage(), e); } return httpClient; } /** Pack category and attribute */ protected static String packCategoryAttribute(String category, String attribute) { StringBuilder sb = new StringBuilder(); pack(sb,category,':'); pack(sb,attribute,':'); return sb.toString(); } /** Unpack category and attribute */ protected static void unpackCategoryAttribute(StringBuilder category, StringBuilder attribute, String value) { int startPos = 0; startPos = unpack(category,value,startPos,':'); startPos = unpack(attribute,value,startPos,':'); } /** Given a path string, get a list of folders and projects under that node. *@param pathString is the current path (folder names and project names, separated by dots (.)). *@return a list of folder and project names, in sorted order, or null if the path was invalid. */ protected String[] getChildFolders(LivelinkContext llc, String pathString) throws ManifoldCFException, ServiceInterruption { RootValue rv = new RootValue(llc,pathString); // Get the volume, object id of the folder/project the path describes VolumeAndId vid = getPathId(rv); if (vid == null) return null; String filterString = "(SubType="+ LAPI_DOCUMENTS.FOLDERSUBTYPE + " or SubType=" + LAPI_DOCUMENTS.PROJECTSUBTYPE + " or SubType=" + LAPI_DOCUMENTS.COMPOUNDDOCUMENTSUBTYPE + ")"; int sanityRetryCount = FAILURE_RETRY_COUNT; while (true) { ListObjectsThread t = new ListObjectsThread(vid.getVolumeID(), vid.getPathId(), filterString); try { t.start(); LLValue children; try { children = t.finishUp(); } catch (ManifoldCFException e) { sanityRetryCount = assessRetry(sanityRetryCount,e); continue; } String[] rval = new String[children.size()]; int j = 0; while (j < children.size()) { rval[j] = children.toString(j,"Name"); j++; } return rval; } catch (InterruptedException e) { t.interrupt(); throw new ManifoldCFException("Interrupted: "+e.getMessage(),e,ManifoldCFException.INTERRUPTED); } catch (RuntimeException e) { sanityRetryCount = handleLivelinkRuntimeException(e,sanityRetryCount,true); continue; } } } /** Given a path string, get a list of categories under that node. *@param pathString is the current path (folder names and project names, separated by dots (.)). *@return a list of category names, in sorted order, or null if the path was invalid. */ protected String[] getChildCategories(LivelinkContext llc, String pathString) throws ManifoldCFException, ServiceInterruption { // Start at root RootValue rv = new RootValue(llc,pathString); // Get the volume, object id of the folder/project the path describes VolumeAndId vid = getPathId(rv); if (vid == null) return null; // We want only folders that are children of the current object and which match the specified subfolder String filterString = "SubType="+ LAPI_DOCUMENTS.CATEGORYSUBTYPE; int sanityRetryCount = FAILURE_RETRY_COUNT; while (true) { ListObjectsThread t = new ListObjectsThread(vid.getVolumeID(), vid.getPathId(), filterString); try { t.start(); LLValue children; try { children = t.finishUp(); } catch (ManifoldCFException e) { sanityRetryCount = assessRetry(sanityRetryCount,e); continue; } String[] rval = new String[children.size()]; int j = 0; while (j < children.size()) { rval[j] = children.toString(j,"Name"); j++; } return rval; } catch (InterruptedException e) { t.interrupt(); throw new ManifoldCFException("Interrupted: "+e.getMessage(),e,ManifoldCFException.INTERRUPTED); } catch (RuntimeException e) { sanityRetryCount = handleLivelinkRuntimeException(e,sanityRetryCount,true); continue; } } } protected class GetCategoryAttributesThread extends Thread { protected final int catObjectID; protected Throwable exception = null; protected LLValue rval = null; public GetCategoryAttributesThread(int catObjectID) { super(); setDaemon(true); this.catObjectID = catObjectID; } public void run() { try { LLValue catID = new LLValue(); catID.setAssoc(); catID.add("ID", catObjectID); catID.add("Type", LAPI_ATTRIBUTES.CATEGORY_TYPE_LIBRARY); LLValue catVersion = new LLValue(); int status = LLDocs.FetchCategoryVersion(catID,catVersion); if (status == 107105 || status == 107106) return; if (status != 0) { throw new ManifoldCFException("Error getting category version: "+Integer.toString(status)); } LLValue children = new LLValue(); status = LLAttributes.AttrListNames(catVersion,null,children); if (status != 0) { throw new ManifoldCFException("Error getting attribute names: "+Integer.toString(status)); } rval = children; } catch (Throwable e) { this.exception = e; } } public LLValue finishUp() throws ManifoldCFException, InterruptedException { join(); Throwable thr = exception; if (thr != null) { if (thr instanceof RuntimeException) throw (RuntimeException)thr; else if (thr instanceof ManifoldCFException) throw (ManifoldCFException)thr; else if (thr instanceof Error) throw (Error)thr; else throw new RuntimeException("Unrecognized exception type: "+thr.getClass().getName()+": "+thr.getMessage(),thr); } return rval; } } /** Given a category path, get a list of legal attribute names. *@param catObjectID is the object id of the category. *@return a list of attribute names, in sorted order, or null of the path was invalid. */ protected String[] getCategoryAttributes(int catObjectID) throws ManifoldCFException, ServiceInterruption { int sanityRetryCount = FAILURE_RETRY_COUNT; while (true) { GetCategoryAttributesThread t = new GetCategoryAttributesThread(catObjectID); try { t.start(); LLValue children; try { children = t.finishUp(); } catch (ManifoldCFException e) { sanityRetryCount = assessRetry(sanityRetryCount,e); continue; } if (children == null) return null; String[] rval = new String[children.size()]; LLValueEnumeration en = children.enumerateValues(); int j = 0; while (en.hasMoreElements()) { LLValue v = (LLValue)en.nextElement(); rval[j] = v.toString(); j++; } return rval; } catch (InterruptedException e) { t.interrupt(); throw new ManifoldCFException("Interrupted: "+e.getMessage(),e,ManifoldCFException.INTERRUPTED); } catch (RuntimeException e) { sanityRetryCount = handleLivelinkRuntimeException(e,sanityRetryCount,true); continue; } } } protected class GetCategoryVersionThread extends Thread { protected final int objID; protected final int catID; protected Throwable exception = null; protected LLValue rval = null; public GetCategoryVersionThread(int objID, int catID) { super(); setDaemon(true); this.objID = objID; this.catID = catID; } public void run() { try { // Set up the right llvalues // Object ID LLValue objIDValue = new LLValue().setAssoc(); objIDValue.add("ID", objID); // Current version, so don't set the "Version" field // CatID LLValue catIDValue = new LLValue().setAssoc(); catIDValue.add("ID", catID); catIDValue.add("Type", LAPI_ATTRIBUTES.CATEGORY_TYPE_LIBRARY); LLValue rvalue = new LLValue(); int status = LLDocs.GetObjectAttributesEx(objIDValue,catIDValue,rvalue); // If either the object is wrong, or the object does not have the specified category, return null. if (status == 103101 || status == 107205) return; if (status != 0) { throw new ManifoldCFException("Error retrieving category version: "+Integer.toString(status)+": "+llServer.getErrors()); } rval = rvalue; } catch (Throwable e) { this.exception = e; } } public LLValue finishUp() throws ManifoldCFException, InterruptedException { join(); Throwable thr = exception; if (thr != null) { if (thr instanceof RuntimeException) throw (RuntimeException)thr; else if (thr instanceof ManifoldCFException) throw (ManifoldCFException)thr; else if (thr instanceof Error) throw (Error)thr; else throw new RuntimeException("Unrecognized exception type: "+thr.getClass().getName()+": "+thr.getMessage(),thr); } return rval; } } /** Get a category version for document. */ protected LLValue getCatVersion(int objID, int catID) throws ManifoldCFException, ServiceInterruption { int sanityRetryCount = FAILURE_RETRY_COUNT; while (true) { GetCategoryVersionThread t = new GetCategoryVersionThread(objID,catID); try { t.start(); try { return t.finishUp(); } catch (ManifoldCFException e) { sanityRetryCount = assessRetry(sanityRetryCount,e); continue; } } catch (InterruptedException e) { t.interrupt(); throw new ManifoldCFException("Interrupted: "+e.getMessage(),e,ManifoldCFException.INTERRUPTED); } catch (NullPointerException npe) { // LAPI throws a null pointer exception under very rare conditions when the GetObjectAttributesEx is // called. The conditions are not clear at this time - it could even be due to Livelink corruption. // However, I'm going to have to treat this as // indicating that this category version does not exist for this document. Logging.connectors.warn("Livelink: Null pointer exception thrown trying to get cat version for category "+ Integer.toString(catID)+" for object "+Integer.toString(objID)); return null; } catch (RuntimeException e) { sanityRetryCount = handleLivelinkRuntimeException(e,sanityRetryCount,true); continue; } } } protected class GetAttributeValueThread extends Thread { protected final LLValue categoryVersion; protected final String attributeName; protected Throwable exception = null; protected LLValue rval = null; public GetAttributeValueThread(LLValue categoryVersion, String attributeName) { super(); setDaemon(true); this.categoryVersion = categoryVersion; this.attributeName = attributeName; } public void run() { try { // Set up the right llvalues LLValue children = new LLValue(); int status = LLAttributes.AttrGetValues(categoryVersion,attributeName, 0,null,children); // "Not found" status - I don't know if it possible to get this here, but if so, behave civilly if (status == 103101) return; // This seems to be the real error LAPI returns if you don't have an attribute of this name if (status == 8000604) return; if (status != 0) { throw new ManifoldCFException("Error retrieving attribute value: "+Integer.toString(status)+": "+llServer.getErrors()); } rval = children; } catch (Throwable e) { this.exception = e; } } public LLValue finishUp() throws ManifoldCFException, InterruptedException { join(); Throwable thr = exception; if (thr != null) { if (thr instanceof RuntimeException) throw (RuntimeException)thr; else if (thr instanceof ManifoldCFException) throw (ManifoldCFException)thr; else if (thr instanceof Error) throw (Error)thr; else throw new RuntimeException("Unrecognized exception type: "+thr.getClass().getName()+": "+thr.getMessage(),thr); } return rval; } } /** Get an attribute value from a category version. */ protected String[] getAttributeValue(LLValue categoryVersion, String attributeName) throws ManifoldCFException, ServiceInterruption { int sanityRetryCount = FAILURE_RETRY_COUNT; while (true) { GetAttributeValueThread t = new GetAttributeValueThread(categoryVersion, attributeName); try { t.start(); LLValue children; try { children = t.finishUp(); } catch (ManifoldCFException e) { sanityRetryCount = assessRetry(sanityRetryCount,e); continue; } if (children == null) return null; String[] rval = new String[children.size()]; LLValueEnumeration en = children.enumerateValues(); int j = 0; while (en.hasMoreElements()) { LLValue v = (LLValue)en.nextElement(); rval[j] = v.toString(); j++; } return rval; } catch (InterruptedException e) { t.interrupt(); throw new ManifoldCFException("Interrupted: "+e.getMessage(),e,ManifoldCFException.INTERRUPTED); } catch (RuntimeException e) { sanityRetryCount = handleLivelinkRuntimeException(e,sanityRetryCount,true); continue; } } } protected class GetObjectRightsThread extends Thread { protected final int vol; protected final int objID; protected Throwable exception = null; protected LLValue rval = null; public GetObjectRightsThread(int vol, int objID) { super(); setDaemon(true); this.vol = vol; this.objID = objID; } public void run() { try { LLValue childrenObjects = new LLValue(); int status = LLDocs.GetObjectRights(vol, objID, childrenObjects); // If the rights object doesn't exist, behave civilly if (status == 103101) return; if (status != 0) { throw new ManifoldCFException("Error retrieving document rights: "+Integer.toString(status)+": "+llServer.getErrors()); } rval = childrenObjects; } catch (Throwable e) { this.exception = e; } } public LLValue finishUp() throws ManifoldCFException, InterruptedException { join(); Throwable thr = exception; if (thr != null) { if (thr instanceof RuntimeException) throw (RuntimeException)thr; else if (thr instanceof ManifoldCFException) throw (ManifoldCFException)thr; else if (thr instanceof Error) throw (Error)thr; else throw new RuntimeException("Unrecognized exception type: "+thr.getClass().getName()+": "+thr.getMessage(),thr); } return rval; } } /** Get an object's rights. This will be an array of right id's, including the special * ones defined by Livelink, or null will be returned (if the object is not found). *@param vol is the volume id *@param objID is the object id *@return the array. */ protected int[] getObjectRights(int vol, int objID) throws ManifoldCFException, ServiceInterruption { int sanityRetryCount = FAILURE_RETRY_COUNT; while (true) { GetObjectRightsThread t = new GetObjectRightsThread(vol,objID); try { t.start(); LLValue childrenObjects; try { childrenObjects = t.finishUp(); } catch (ManifoldCFException e) { sanityRetryCount = assessRetry(sanityRetryCount,e); continue; } if (childrenObjects == null) return null; int size; if (childrenObjects.isRecord()) size = 1; else if (childrenObjects.isTable()) size = childrenObjects.size(); else size = 0; int minPermission = LAPI_DOCUMENTS.PERM_SEE + LAPI_DOCUMENTS.PERM_SEECONTENTS; int j = 0; int count = 0; while (j < size) { int permission = childrenObjects.toInteger(j, "Permissions"); // Only if the permission is "see contents" can we consider this // access token! if ((permission & minPermission) == minPermission) count++; j++; } int[] rval = new int[count]; j = 0; count = 0; while (j < size) { int token = childrenObjects.toInteger(j, "RightID"); int permission = childrenObjects.toInteger(j, "Permissions"); // Only if the permission is "see contents" can we consider this // access token! if ((permission & minPermission) == minPermission) rval[count++] = token; j++; } return rval; } catch (InterruptedException e) { t.interrupt(); throw new ManifoldCFException("Interrupted: "+e.getMessage(),e,ManifoldCFException.INTERRUPTED); } catch (RuntimeException e) { sanityRetryCount = handleLivelinkRuntimeException(e,sanityRetryCount,true); continue; } } } /** Local cache for various kinds of objects that may be useful more than once. */ protected class LivelinkContext { /** Cache of ObjectInformation objects. */ protected final Map<ObjectInformation,ObjectInformation> objectInfoMap = new HashMap<ObjectInformation,ObjectInformation>(); /** Cache of VersionInformation objects. */ protected final Map<VersionInformation,VersionInformation> versionInfoMap = new HashMap<VersionInformation,VersionInformation>(); /** Cache of UserInformation objects */ protected final Map<UserInformation,UserInformation> userInfoMap = new HashMap<UserInformation,UserInformation>(); public LivelinkContext() { } public ObjectInformation getObjectInformation(int volumeID, int objectID) { ObjectInformation oi = new ObjectInformation(volumeID,objectID); ObjectInformation lookupValue = objectInfoMap.get(oi); if (lookupValue == null) { objectInfoMap.put(oi,oi); return oi; } return lookupValue; } public VersionInformation getVersionInformation(int volumeID, int objectID, int revisionNumber) { VersionInformation vi = new VersionInformation(volumeID,objectID,revisionNumber); VersionInformation lookupValue = versionInfoMap.get(vi); if (lookupValue == null) { versionInfoMap.put(vi,vi); return vi; } return lookupValue; } public UserInformation getUserInformation(int userID) { UserInformation ui = new UserInformation(userID); UserInformation lookupValue = userInfoMap.get(ui); if (lookupValue == null) { userInfoMap.put(ui,ui); return ui; } return lookupValue; } } /** This object represents a cache of user information. * Initialize it with the user ID. Then, request desired fields from it. */ protected class UserInformation { protected final int userID; protected LLValue userValue = null; public UserInformation(int userID) { this.userID = userID; } public boolean exists() throws ServiceInterruption, ManifoldCFException { return getUserValue() != null; } public String getName() throws ServiceInterruption, ManifoldCFException { LLValue userValue = getUserValue(); if (userValue == null) return null; return userValue.toString("NAME"); } protected LLValue getUserValue() throws ServiceInterruption, ManifoldCFException { if (userValue == null) { int sanityRetryCount = FAILURE_RETRY_COUNT; while (true) { GetUserInfoThread t = new GetUserInfoThread(userID); try { t.start(); try { userValue = t.finishUp(); } catch (ManifoldCFException e) { sanityRetryCount = assessRetry(sanityRetryCount,e); continue; } break; } catch (InterruptedException e) { t.interrupt(); throw new ManifoldCFException("Interrupted: "+e.getMessage(),e,ManifoldCFException.INTERRUPTED); } catch (RuntimeException e) { sanityRetryCount = handleLivelinkRuntimeException(e,sanityRetryCount,true); continue; } } } return userValue; } @Override public String toString() { return "("+userID+")"; } @Override public int hashCode() { return (userID << 5) ^ (userID >> 3); } @Override public boolean equals(Object o) { if (!(o instanceof UserInformation)) return false; UserInformation other = (UserInformation)o; return userID == other.userID; } } /** This object represents a cache of version information. * Initialize it with the volume ID and object ID and revision number (usually zero). * Then, request the desired fields from it. */ protected class VersionInformation { protected final int volumeID; protected final int objectID; protected final int revisionNumber; protected LLValue versionValue = null; public VersionInformation(int volumeID, int objectID, int revisionNumber) { this.volumeID = volumeID; this.objectID = objectID; this.revisionNumber = revisionNumber; } public boolean exists() throws ServiceInterruption, ManifoldCFException { return getVersionValue() != null; } /** Get data size. */ public Long getDataSize() throws ServiceInterruption, ManifoldCFException { LLValue elem = getVersionValue(); if (elem == null) return null; return new Long(elem.toLong("FILEDATASIZE")); } /** Get file name. */ public String getFileName() throws ServiceInterruption, ManifoldCFException { LLValue elem = getVersionValue(); if (elem == null) return null; return elem.toString("FILENAME"); } /** Get mime type. */ public String getMimeType() throws ServiceInterruption, ManifoldCFException { LLValue elem = getVersionValue(); if (elem == null) return null; return elem.toString("MIMETYPE"); } /** Get modify date. */ public Date getModifyDate() throws ServiceInterruption, ManifoldCFException { LLValue elem = getVersionValue(); if (elem == null) return null; return elem.toDate("MODIFYDATE"); } /** Get modifier. */ public Integer getOwnerId() throws ServiceInterruption, ManifoldCFException { LLValue elem = getVersionValue(); if (elem == null) return null; return new Integer(elem.toInteger("OWNER")); } /** Get version LLValue */ protected LLValue getVersionValue() throws ServiceInterruption, ManifoldCFException { if (versionValue == null) { int sanityRetryCount = FAILURE_RETRY_COUNT; while (true) { GetVersionInfoThread t = new GetVersionInfoThread(volumeID,objectID,revisionNumber); try { t.start(); try { versionValue = t.finishUp(); } catch (ManifoldCFException e) { sanityRetryCount = assessRetry(sanityRetryCount,e); continue; } break; } catch (InterruptedException e) { t.interrupt(); throw new ManifoldCFException("Interrupted: "+e.getMessage(),e,ManifoldCFException.INTERRUPTED); } catch (RuntimeException e) { sanityRetryCount = handleLivelinkRuntimeException(e,sanityRetryCount,true); continue; } } } return versionValue; } @Override public int hashCode() { return (volumeID << 5) ^ (volumeID >> 3) ^ (objectID << 5) ^ (objectID >> 3) ^ (revisionNumber << 5) ^ (revisionNumber >> 3); } @Override public boolean equals(Object o) { if (!(o instanceof VersionInformation)) return false; VersionInformation other = (VersionInformation)o; return volumeID == other.volumeID && objectID == other.objectID && revisionNumber == other.revisionNumber; } } /** This object represents an object information cache. * Initialize it with the volume ID and object ID, and then request * the appropriate fields from it. Keep it around as long as needed; it functions as a cache * of sorts... */ protected class ObjectInformation { protected final int volumeID; protected final int objectID; protected LLValue objectValue = null; public ObjectInformation(int volumeID, int objectID) { this.volumeID = volumeID; this.objectID = objectID; } /** * Check whether object seems to exist or not. */ public boolean exists() throws ServiceInterruption, ManifoldCFException { return getObjectValue() != null; } /** Check if this object is the category workspace. */ public boolean isCategoryWorkspace() { return objectID == LLCATWK_ID; } /** Check if this object is the entity workspace. */ public boolean isEntityWorkspace() { return objectID == LLENTWK_ID; } /** toString override */ @Override public String toString() { return "(Volume: "+volumeID+", Object: "+objectID+")"; } /** * Returns the object ID specified by the path name. * @param startPath is the folder name (a string with dots as separators) */ public VolumeAndId getPathId(String startPath) throws ServiceInterruption, ManifoldCFException { LLValue objInfo = getObjectValue(); if (objInfo == null) return null; // Grab the volume ID and starting object int obj = objInfo.toInteger("ID"); int vol = objInfo.toInteger("VolumeID"); // Pick apart the start path. This is a string separated by slashes. int charindex = 0; while (charindex < startPath.length()) { StringBuilder currentTokenBuffer = new StringBuilder(); // Find the current token while (charindex < startPath.length()) { char x = startPath.charAt(charindex++); if (x == '/') break; if (x == '\\') { // Attempt to escape what follows x = startPath.charAt(charindex); charindex++; } currentTokenBuffer.append(x); } String subFolder = currentTokenBuffer.toString(); // We want only folders that are children of the current object and which match the specified subfolder String filterString = "(SubType="+ LAPI_DOCUMENTS.FOLDERSUBTYPE + " or SubType=" + LAPI_DOCUMENTS.PROJECTSUBTYPE + " or SubType=" + LAPI_DOCUMENTS.COMPOUNDDOCUMENTSUBTYPE + ") and Name='" + subFolder + "'"; int sanityRetryCount = FAILURE_RETRY_COUNT; while (true) { ListObjectsThread t = new ListObjectsThread(vol,obj,filterString); try { t.start(); LLValue children; try { children = t.finishUp(); } catch (ManifoldCFException e) { sanityRetryCount = assessRetry(sanityRetryCount,e); continue; } if (children == null) return null; // If there is one child, then we are okay. if (children.size() == 1) { // New starting point is the one we found. obj = children.toInteger(0, "ID"); int subtype = children.toInteger(0, "SubType"); if (subtype == LAPI_DOCUMENTS.PROJECTSUBTYPE) { vol = obj; obj = -obj; } } else { // Couldn't find the path. Instead of throwing up, return null to indicate // illegal node. return null; } break; } catch (InterruptedException e) { t.interrupt(); throw new ManifoldCFException("Interrupted: "+e.getMessage(),e,ManifoldCFException.INTERRUPTED); } catch (RuntimeException e) { sanityRetryCount = handleLivelinkRuntimeException(e,sanityRetryCount,true); continue; } } } return new VolumeAndId(vol,obj); } /** * Returns the category ID specified by the path name. * @param startPath is the folder name, ending in a category name (a string with slashes as separators) */ public int getCategoryId(String startPath) throws ManifoldCFException, ServiceInterruption { LLValue objInfo = getObjectValue(); if (objInfo == null) return -1; // Grab the volume ID and starting object int obj = objInfo.toInteger("ID"); int vol = objInfo.toInteger("VolumeID"); // Pick apart the start path. This is a string separated by slashes. if (startPath.length() == 0) return -1; int charindex = 0; while (charindex < startPath.length()) { StringBuilder currentTokenBuffer = new StringBuilder(); // Find the current token while (charindex < startPath.length()) { char x = startPath.charAt(charindex++); if (x == '/') break; if (x == '\\') { // Attempt to escape what follows x = startPath.charAt(charindex); charindex++; } currentTokenBuffer.append(x); } String subFolder = currentTokenBuffer.toString(); String filterString; // We want only folders that are children of the current object and which match the specified subfolder if (charindex < startPath.length()) filterString = "(SubType="+ LAPI_DOCUMENTS.FOLDERSUBTYPE + " or SubType=" + LAPI_DOCUMENTS.PROJECTSUBTYPE + " or SubType=" + LAPI_DOCUMENTS.COMPOUNDDOCUMENTSUBTYPE + ")"; else filterString = "SubType="+LAPI_DOCUMENTS.CATEGORYSUBTYPE; filterString += " and Name='" + subFolder + "'"; int sanityRetryCount = FAILURE_RETRY_COUNT; while (true) { ListObjectsThread t = new ListObjectsThread(vol,obj,filterString); try { t.start(); LLValue children; try { children = t.finishUp(); } catch (ManifoldCFException e) { sanityRetryCount = assessRetry(sanityRetryCount,e); continue; } if (children == null) return -1; // If there is one child, then we are okay. if (children.size() == 1) { // New starting point is the one we found. obj = children.toInteger(0, "ID"); int subtype = children.toInteger(0, "SubType"); if (subtype == LAPI_DOCUMENTS.PROJECTSUBTYPE) { vol = obj; obj = -obj; } } else { // Couldn't find the path. Instead of throwing up, return null to indicate // illegal node. return -1; } break; } catch (InterruptedException e) { t.interrupt(); throw new ManifoldCFException("Interrupted: "+e.getMessage(),e,ManifoldCFException.INTERRUPTED); } catch (RuntimeException e) { sanityRetryCount = handleLivelinkRuntimeException(e,sanityRetryCount,true); continue; } } } return obj; } /** Get permissions. */ public Integer getPermissions() throws ServiceInterruption, ManifoldCFException { LLValue elem = getObjectValue(); if (elem == null) return null; return new Integer(objectValue.toInteger("Permissions")); } /** Get OpenText document name. */ public String getName() throws ServiceInterruption, ManifoldCFException { LLValue elem = getObjectValue(); if (elem == null) return null; return elem.toString("NAME"); } /** Get OpenText comments/description. */ public String getComments() throws ServiceInterruption, ManifoldCFException { LLValue elem = getObjectValue(); if (elem == null) return null; return elem.toString("COMMENT"); } /** Get parent ID. */ public Integer getParentId() throws ServiceInterruption, ManifoldCFException { LLValue elem = getObjectValue(); if (elem == null) return null; return new Integer(elem.toInteger("ParentId")); } /** Get owner ID. */ public Integer getOwnerId() throws ServiceInterruption, ManifoldCFException { LLValue elem = getObjectValue(); if (elem == null) return null; return new Integer(elem.toInteger("UserId")); } /** Get group ID. */ public Integer getGroupId() throws ServiceInterruption, ManifoldCFException { LLValue elem = getObjectValue(); if (elem == null) return null; return new Integer(elem.toInteger("GroupId")); } /** Get creation date. */ public Date getCreationDate() throws ServiceInterruption, ManifoldCFException { LLValue elem = getObjectValue(); if (elem == null) return null; return elem.toDate("CREATEDATE"); } /** Get creator ID. */ public Integer getCreatorId() throws ServiceInterruption, ManifoldCFException { LLValue elem = getObjectValue(); if (elem == null) return null; return new Integer(elem.toInteger("CREATEDBY")); } /* Get modify date. */ public Date getModifyDate() throws ServiceInterruption, ManifoldCFException { LLValue elem = getObjectValue(); if (elem == null) return null; return elem.toDate("ModifyDate"); } /** Get the objInfo object. */ protected LLValue getObjectValue() throws ServiceInterruption, ManifoldCFException { if (objectValue == null) { int sanityRetryCount = FAILURE_RETRY_COUNT; while (true) { GetObjectInfoThread t = new GetObjectInfoThread(volumeID,objectID); try { t.start(); try { objectValue = t.finishUp(); } catch (ManifoldCFException e) { sanityRetryCount = assessRetry(sanityRetryCount,e); continue; } break; } catch (InterruptedException e) { t.interrupt(); throw new ManifoldCFException("Interrupted: "+e.getMessage(),e,ManifoldCFException.INTERRUPTED); } catch (RuntimeException e) { sanityRetryCount = handleLivelinkRuntimeException(e,sanityRetryCount,true); continue; } } } return objectValue; } @Override public int hashCode() { return (volumeID << 5) ^ (volumeID >> 3) ^ (objectID << 5) ^ (objectID >> 3); } @Override public boolean equals(Object o) { if (!(o instanceof ObjectInformation)) return false; ObjectInformation other = (ObjectInformation)o; return volumeID == other.volumeID && objectID == other.objectID; } } /** Thread we can abandon that lists all users (except admin). */ protected class ListUsersThread extends Thread { protected LLValue rval = null; protected Throwable exception = null; public ListUsersThread() { super(); setDaemon(true); } public void run() { try { LLValue userList = new LLValue(); int status = LLUsers.ListUsers(userList); if (Logging.connectors.isDebugEnabled()) { Logging.connectors.debug("Livelink: User list retrieved: status="+Integer.toString(status)); } if (status < 0) { Logging.connectors.debug("Livelink: User list inaccessable ("+llServer.getErrors()+")"); return; } if (status != 0) { throw new ManifoldCFException("Error retrieving user list: status="+Integer.toString(status)+" ("+llServer.getErrors()+")"); } rval = userList; } catch (Throwable e) { this.exception = e; } } public LLValue finishUp() throws ManifoldCFException, InterruptedException { join(); Throwable thr = exception; if (thr != null) { if (thr instanceof RuntimeException) throw (RuntimeException)thr; else if (thr instanceof ManifoldCFException) throw (ManifoldCFException)thr; else if (thr instanceof Error) throw (Error)thr; else throw new RuntimeException("Unrecognized exception type: "+thr.getClass().getName()+": "+thr.getMessage(),thr); } return rval; } } /** Thread we can abandon that gets user information for a userID. */ protected class GetUserInfoThread extends Thread { protected final int user; protected Throwable exception = null; protected LLValue rval = null; public GetUserInfoThread(int user) { super(); setDaemon(true); this.user = user; } public void run() { try { LLValue userinfo = new LLValue().setAssoc(); int status = LLUsers.GetUserByID(user,userinfo); // Need to detect if object was deleted, and return null in this case!!! if (Logging.connectors.isDebugEnabled()) { Logging.connectors.debug("Livelink: User status retrieved for "+Integer.toString(user)+": status="+Integer.toString(status)); } // Treat both 103101 and 103102 as 'object not found'. 401101 is 'user not found'. if (status == 103101 || status == 103102 || status == 401101) return; // This error means we don't have permission to get the object's status, apparently if (status < 0) { Logging.connectors.debug("Livelink: User info inaccessable for user "+Integer.toString(user)+ " ("+llServer.getErrors()+")"); return; } if (status != 0) { throw new ManifoldCFException("Error retrieving user "+Integer.toString(user)+": status="+Integer.toString(status)+" ("+llServer.getErrors()+")"); } rval = userinfo; } catch (Throwable e) { this.exception = e; } } public LLValue finishUp() throws ManifoldCFException, InterruptedException { join(); Throwable thr = exception; if (thr != null) { if (thr instanceof RuntimeException) throw (RuntimeException)thr; else if (thr instanceof ManifoldCFException) throw (ManifoldCFException)thr; else if (thr instanceof Error) throw (Error)thr; else throw new RuntimeException("Unrecognized exception type: "+thr.getClass().getName()+": "+thr.getMessage(),thr); } return rval; } } /** Thread we can abandon that gets version information for a volume and an id and a revision. */ protected class GetVersionInfoThread extends Thread { protected final int vol; protected final int id; protected final int revNumber; protected Throwable exception = null; protected LLValue rval = null; public GetVersionInfoThread(int vol, int id, int revNumber) { super(); setDaemon(true); this.vol = vol; this.id = id; this.revNumber = revNumber; } public void run() { try { LLValue versioninfo = new LLValue().setAssocNotSet(); int status = LLDocs.GetVersionInfo(vol,id,revNumber,versioninfo); // Need to detect if object was deleted, and return null in this case!!! if (Logging.connectors.isDebugEnabled()) { Logging.connectors.debug("Livelink: Version status retrieved for "+Integer.toString(vol)+":"+Integer.toString(id)+", rev "+revNumber+": status="+Integer.toString(status)); } // Treat both 103101 and 103102 as 'object not found'. if (status == 103101 || status == 103102) return; // This error means we don't have permission to get the object's status, apparently if (status < 0) { Logging.connectors.debug("Livelink: Version info inaccessable for object "+Integer.toString(vol)+":"+Integer.toString(id)+", rev "+revNumber+ " ("+llServer.getErrors()+")"); return; } if (status != 0) { throw new ManifoldCFException("Error retrieving document version "+Integer.toString(vol)+":"+Integer.toString(id)+", rev "+revNumber+": status="+Integer.toString(status)+" ("+llServer.getErrors()+")"); } rval = versioninfo; } catch (Throwable e) { this.exception = e; } } public LLValue finishUp() throws ManifoldCFException, InterruptedException { join(); Throwable thr = exception; if (thr != null) { if (thr instanceof RuntimeException) throw (RuntimeException)thr; else if (thr instanceof ManifoldCFException) throw (ManifoldCFException)thr; else if (thr instanceof Error) throw (Error)thr; else throw new RuntimeException("Unrecognized exception type: "+thr.getClass().getName()+": "+thr.getMessage(),thr); } return rval; } } /** Thread we can abandon that gets object information for a volume and an id. */ protected class GetObjectInfoThread extends Thread { protected int vol; protected int id; protected Throwable exception = null; protected LLValue rval = null; public GetObjectInfoThread(int vol, int id) { super(); setDaemon(true); this.vol = vol; this.id = id; } public void run() { try { LLValue objinfo = new LLValue().setAssocNotSet(); int status = LLDocs.GetObjectInfo(vol,id,objinfo); // Need to detect if object was deleted, and return null in this case!!! if (Logging.connectors.isDebugEnabled()) { Logging.connectors.debug("Livelink: Status retrieved for "+Integer.toString(vol)+":"+Integer.toString(id)+": status="+Integer.toString(status)); } // Treat both 103101 and 103102 as 'object not found'. if (status == 103101 || status == 103102) return; // This error means we don't have permission to get the object's status, apparently if (status < 0) { Logging.connectors.debug("Livelink: Object info inaccessable for object "+Integer.toString(vol)+":"+Integer.toString(id)+ " ("+llServer.getErrors()+")"); return; } if (status != 0) { throw new ManifoldCFException("Error retrieving document object "+Integer.toString(vol)+":"+Integer.toString(id)+": status="+Integer.toString(status)+" ("+llServer.getErrors()+")"); } rval = objinfo; } catch (Throwable e) { this.exception = e; } } public LLValue finishUp() throws ManifoldCFException, InterruptedException { join(); Throwable thr = exception; if (thr != null) { if (thr instanceof RuntimeException) throw (RuntimeException)thr; else if (thr instanceof ManifoldCFException) throw (ManifoldCFException)thr; else if (thr instanceof Error) throw (Error)thr; else throw new RuntimeException("Unrecognized exception type: "+thr.getClass().getName()+": "+thr.getMessage(),thr); } return rval; } } /** Build a set of actual acls given a set of rights */ protected String[] lookupTokens(int[] rights, ObjectInformation objInfo) throws ManifoldCFException, ServiceInterruption { if (!objInfo.exists()) return null; String[] convertedAcls = new String[rights.length]; LLValue infoObject = null; int j = 0; int k = 0; while (j < rights.length) { int token = rights[j++]; String tokenValue; // Consider this token switch (token) { case LAPI_DOCUMENTS.RIGHT_OWNER: // Look up user for current document (UserID attribute) tokenValue = objInfo.getOwnerId().toString(); break; case LAPI_DOCUMENTS.RIGHT_GROUP: tokenValue = objInfo.getGroupId().toString(); break; case LAPI_DOCUMENTS.RIGHT_WORLD: // Add "Guest" token tokenValue = "GUEST"; break; case LAPI_DOCUMENTS.RIGHT_SYSTEM: // Add "System" token tokenValue = "SYSTEM"; break; default: tokenValue = Integer.toString(token); break; } // This might return a null if we could not look up the object corresponding to the right. If so, it is safe to skip it because // that always RESTRICTS view of the object (maybe erroneously), but does not expand visibility. if (tokenValue != null) convertedAcls[k++] = tokenValue; } String[] actualAcls = new String[k]; j = 0; while (j < k) { actualAcls[j] = convertedAcls[j]; j++; } return actualAcls; } protected class GetObjectCategoryIDsThread extends Thread { protected final int vol; protected final int id; protected Throwable exception = null; protected LLValue rval = null; public GetObjectCategoryIDsThread(int vol, int id) { super(); setDaemon(true); this.vol = vol; this.id = id; } public void run() { try { // Object ID LLValue objIDValue = new LLValue().setAssocNotSet(); objIDValue.add("ID", id); // Category ID List LLValue catIDList = new LLValue().setAssocNotSet(); int status = LLDocs.ListObjectCategoryIDs(objIDValue,catIDList); // Need to detect if object was deleted, and return null in this case!!! if (Logging.connectors.isDebugEnabled()) { Logging.connectors.debug("Livelink: Status value for getting object categories for "+Integer.toString(vol)+":"+Integer.toString(id)+" is: "+Integer.toString(status)); } if (status == 103101) return; if (status != 0) { throw new ManifoldCFException("Error retrieving document categories for "+Integer.toString(vol)+":"+Integer.toString(id)+": status="+Integer.toString(status)+" ("+llServer.getErrors()+")"); } rval = catIDList; } catch (Throwable e) { this.exception = e; } } public LLValue finishUp() throws ManifoldCFException, InterruptedException { join(); Throwable thr = exception; if (thr != null) { if (thr instanceof RuntimeException) throw (RuntimeException)thr; else if (thr instanceof ManifoldCFException) throw (ManifoldCFException)thr; else if (thr instanceof Error) throw (Error)thr; else throw new RuntimeException("Unrecognized exception type: "+thr.getClass().getName()+": "+thr.getMessage(),thr); } return rval; } } /** Get category IDs associated with an object. * @param vol is the volume ID * @param id the object ID * @return an array of integers containing category identifiers, or null if the object is not found. */ protected int[] getObjectCategoryIDs(int vol, int id) throws ManifoldCFException, ServiceInterruption { int sanityRetryCount = FAILURE_RETRY_COUNT; while (true) { GetObjectCategoryIDsThread t = new GetObjectCategoryIDsThread(vol,id); try { t.start(); LLValue catIDList; try { catIDList = t.finishUp(); } catch (ManifoldCFException e) { sanityRetryCount = assessRetry(sanityRetryCount,e); continue; } if (catIDList == null) return null; int size = catIDList.size(); if (Logging.connectors.isDebugEnabled()) { Logging.connectors.debug("Livelink: Object "+Integer.toString(vol)+":"+Integer.toString(id)+" has "+Integer.toString(size)+" attached categories"); } // Count the category ids int count = 0; int j = 0; while (j < size) { int type = catIDList.toValue(j).toInteger("Type"); if (type == LAPI_ATTRIBUTES.CATEGORY_TYPE_LIBRARY) count++; j++; } int[] rval = new int[count]; // Do the scan j = 0; count = 0; while (j < size) { int type = catIDList.toValue(j).toInteger("Type"); if (type == LAPI_ATTRIBUTES.CATEGORY_TYPE_LIBRARY) { int childID = catIDList.toValue(j).toInteger("ID"); rval[count++] = childID; } j++; } if (Logging.connectors.isDebugEnabled()) { Logging.connectors.debug("Livelink: Object "+Integer.toString(vol)+":"+Integer.toString(id)+" has "+Integer.toString(rval.length)+" attached library categories"); } return rval; } catch (InterruptedException e) { t.interrupt(); throw new ManifoldCFException("Interrupted: "+e.getMessage(),e,ManifoldCFException.INTERRUPTED); } catch (RuntimeException e) { sanityRetryCount = handleLivelinkRuntimeException(e,sanityRetryCount,true); continue; } } } /** RootValue version of getPathId. */ protected VolumeAndId getPathId(RootValue rv) throws ManifoldCFException, ServiceInterruption { return rv.getRootValue().getPathId(rv.getRemainderPath()); } /** Rootvalue version of getCategoryId. */ protected int getCategoryId(RootValue rv) throws ManifoldCFException, ServiceInterruption { return rv.getRootValue().getCategoryId(rv.getRemainderPath()); } // Protected static methods /** Check if a file or directory should be included, given a document specification. *@param filename is the name of the "file". *@param documentSpecification is the specification. *@return true if it should be included. */ protected static boolean checkInclude(String filename, Specification documentSpecification) throws ManifoldCFException { // Scan includes to insure we match int i = 0; while (i < documentSpecification.getChildCount()) { SpecificationNode sn = documentSpecification.getChild(i); if (sn.getType().equals("include")) { String filespec = sn.getAttributeValue("filespec"); // If it matches, we can exit this loop. if (checkMatch(filename,0,filespec)) break; } i++; } if (i == documentSpecification.getChildCount()) return false; // We matched an include. Now, scan excludes to ditch it if needed. i = 0; while (i < documentSpecification.getChildCount()) { SpecificationNode sn = documentSpecification.getChild(i); if (sn.getType().equals("exclude")) { String filespec = sn.getAttributeValue("filespec"); // If it matches, we return false. if (checkMatch(filename,0,filespec)) return false; } i++; } // System.out.println("Match!"); return true; } /** Check if a file should be ingested, given a document specification. It is presumed that * documents that pass checkInclude() will be checked with this method. *@param objID is the file ID. *@param documentSpecification is the specification. */ protected boolean checkIngest(LivelinkContext llc, int objID, Specification documentSpecification) throws ManifoldCFException { // Since the only exclusions at this point are not based on file contents, this is a no-op. return true; } /** Check a match between two strings with wildcards. *@param sourceMatch is the expanded string (no wildcards) *@param sourceIndex is the starting point in the expanded string. *@param match is the wildcard-based string. *@return true if there is a match. */ protected static boolean checkMatch(String sourceMatch, int sourceIndex, String match) { // Note: The java regex stuff looks pretty heavyweight for this purpose. // I've opted to try and do a simple recursive version myself, which is not compiled. // Basically, the match proceeds by recursive descent through the string, so that all *'s cause // recursion. boolean caseSensitive = false; return processCheck(caseSensitive, sourceMatch, sourceIndex, match, 0); } /** Recursive worker method for checkMatch. Returns 'true' if there is a path that consumes both * strings in their entirety in a matched way. *@param caseSensitive is true if file names are case sensitive. *@param sourceMatch is the source string (w/o wildcards) *@param sourceIndex is the current point in the source string. *@param match is the match string (w/wildcards) *@param matchIndex is the current point in the match string. *@return true if there is a match. */ protected static boolean processCheck(boolean caseSensitive, String sourceMatch, int sourceIndex, String match, int matchIndex) { // Logging.connectors.debug("Matching '"+sourceMatch+"' position "+Integer.toString(sourceIndex)+ // " against '"+match+"' position "+Integer.toString(matchIndex)); // Match up through the next * we encounter while (true) { // If we've reached the end, it's a match. if (sourceMatch.length() == sourceIndex && match.length() == matchIndex) return true; // If one has reached the end but the other hasn't, no match if (match.length() == matchIndex) return false; if (sourceMatch.length() == sourceIndex) { if (match.charAt(matchIndex) != '*') return false; matchIndex++; continue; } char x = sourceMatch.charAt(sourceIndex); char y = match.charAt(matchIndex); if (!caseSensitive) { if (x >= 'A' && x <= 'Z') x -= 'A'-'a'; if (y >= 'A' && y <= 'Z') y -= 'A'-'a'; } if (y == '*') { // Wildcard! // We will recurse at this point. // Basically, we want to combine the results for leaving the "*" in the match string // at this point and advancing the source index, with skipping the "*" and leaving the source // string alone. return processCheck(caseSensitive,sourceMatch,sourceIndex+1,match,matchIndex) || processCheck(caseSensitive,sourceMatch,sourceIndex,match,matchIndex+1); } if (y == '?' || x == y) { sourceIndex++; matchIndex++; } else return false; } } /** Class for returning volume id/folder id combination on path lookup. */ protected static class VolumeAndId { protected final int volumeID; protected final int folderID; public VolumeAndId(int volumeID, int folderID) { this.volumeID = volumeID; this.folderID = folderID; } public int getVolumeID() { return volumeID; } public int getPathId() { return folderID; } } /** Class that describes a metadata catid and path. */ protected static class MetadataPathItem { protected final int catID; protected final String catName; /** Constructor. */ public MetadataPathItem(int catID, String catName) { this.catID = catID; this.catName = catName; } /** Get the cat ID. *@return the id. */ public int getCatID() { return catID; } /** Get the cat name. *@return the category name path. */ public String getCatName() { return catName; } } /** Class that describes a metadata catid and attribute set. */ protected static class MetadataItem { protected final MetadataPathItem pathItem; protected final Set<String> attributeNames = new HashSet<String>(); /** Constructor. */ public MetadataItem(MetadataPathItem pathItem) { this.pathItem = pathItem; } /** Add an attribute name. */ public void addAttribute(String attributeName) { attributeNames.add(attributeName); } /** Get the path object. *@return the object. */ public MetadataPathItem getPathItem() { return pathItem; } /** Get an iterator over the attribute names. *@return the iterator. */ public Iterator<String> getAttributeNames() { return attributeNames.iterator(); } } /** Class that tracks paths associated with nodes, and also keeps track of the name * of the metadata attribute to use for the path. */ protected class SystemMetadataDescription { // The livelink context protected final LivelinkContext llc; // The path attribute name protected final String pathAttributeName; // The path separator protected final String pathSeparator; // The node ID to path name mapping (which acts like a cache) protected final Map<String,String> pathMap = new HashMap<String,String>(); // The path name map protected final MatchMap matchMap = new MatchMap(); // Acls protected final Set<String> aclMap = new HashSet<String>(); protected final boolean securityOn; // Filter string protected final String filterString; protected final Set<String> holder = new HashSet<String>(); protected final boolean includeAllMetadata; /** Constructor */ public SystemMetadataDescription(LivelinkContext llc, Specification spec) throws ManifoldCFException, ServiceInterruption { this.llc = llc; String pathAttributeName = null; String pathSeparator = null; boolean securityOn = true; StringBuilder fsb = new StringBuilder(); boolean first = true; boolean includeAllMetadata = false; for (int i = 0; i < spec.getChildCount(); i++) { SpecificationNode n = spec.getChild(i); if (n.getType().equals("pathnameattribute")) { pathAttributeName = n.getAttributeValue("value"); pathSeparator = n.getAttributeValue("separator"); if (pathSeparator == null) pathSeparator = "/"; } else if (n.getType().equals("pathmap")) { String pathMatch = n.getAttributeValue("match"); String pathReplace = n.getAttributeValue("replace"); matchMap.appendMatchPair(pathMatch,pathReplace); } else if (n.getType().equals("access")) { String token = n.getAttributeValue("token"); aclMap.add(token); } else if (n.getType().equals("security")) { String value = n.getAttributeValue("value"); if (value.equals("on")) securityOn = true; else if (value.equals("off")) securityOn = false; } else if (n.getType().equals("include")) { String includeMatch = n.getAttributeValue("filespec"); if (includeMatch != null) { // Peel off the extension int index = includeMatch.lastIndexOf("."); if (index != -1) { String type = includeMatch.substring(index+1).toLowerCase().replace('*','%'); if (first) first = false; else fsb.append(" or "); fsb.append("lower(FileType) like '").append(type).append("'"); } } } else if (n.getType().equals("allmetadata")) { String isAll = n.getAttributeValue("all"); if (isAll != null && isAll.equals("true")) includeAllMetadata = true; } else if (n.getType().equals("metadata")) { String category = n.getAttributeValue("category"); String attributeName = n.getAttributeValue("attribute"); String isAll = n.getAttributeValue("all"); if (isAll != null && isAll.equals("true")) { // Locate all metadata items for the specified category path, // and enter them into the array getSession(); String[] attrs = getCategoryAttributes(llc,category); if (attrs != null) { int j = 0; while (j < attrs.length) { attributeName = attrs[j++]; String metadataName = packCategoryAttribute(category,attributeName); holder.add(metadataName); } } } else { String metadataName = packCategoryAttribute(category,attributeName); holder.add(metadataName); } } } this.includeAllMetadata = includeAllMetadata; this.pathAttributeName = pathAttributeName; this.pathSeparator = pathSeparator; this.securityOn = securityOn; String filterStringPiece = fsb.toString(); if (filterStringPiece.length() == 0) this.filterString = "0>1"; else { StringBuilder sb = new StringBuilder(); sb.append("SubType=").append(new Integer(LAPI_DOCUMENTS.FOLDERSUBTYPE).toString()); sb.append(" or SubType=").append(new Integer(LAPI_DOCUMENTS.COMPOUNDDOCUMENTSUBTYPE).toString()); sb.append(" or SubType=").append(new Integer(LAPI_DOCUMENTS.PROJECTSUBTYPE).toString()); sb.append(" or (SubType=").append(new Integer(LAPI_DOCUMENTS.DOCUMENTSUBTYPE).toString()); sb.append(" and ("); // Walk through the document spec to find the documents that match under the specified root // include lower(column)=spec sb.append(filterStringPiece); sb.append("))"); this.filterString = sb.toString(); } } public boolean includeAllMetadata() { return includeAllMetadata; } public String[] getMetadataAttributes() { // Put into an array String[] specifiedMetadataAttributes = new String[holder.size()]; int i = 0; for (String attrName : holder) { specifiedMetadataAttributes[i++] = attrName; } return specifiedMetadataAttributes; } public String getFilterString() { return filterString; } public String[] getAcls() { if (!securityOn) return null; String[] rval = new String[aclMap.size()]; int i = 0; for (String token : aclMap) { rval[i++] = token; } return rval; } /** Get the path attribute name. *@return the path attribute name, or null if none specified. */ public String getPathAttributeName() { return pathAttributeName; } /** Get the path separator. */ public String getPathSeparator() { return pathSeparator; } /** Given an identifier, get the translated string that goes into the metadata. */ public String getPathAttributeValue(String documentIdentifier) throws ManifoldCFException, ServiceInterruption { String path = getNodePathString(documentIdentifier); if (path == null) return null; return matchMap.translate(path); } /** Get the matchmap string. */ public String getMatchMapString() { return matchMap.toString(); } /** For a given node, get its path. */ public String getNodePathString(String documentIdentifier) throws ManifoldCFException, ServiceInterruption { if (Logging.connectors.isDebugEnabled()) Logging.connectors.debug("Looking up path for '"+documentIdentifier+"'"); String path = pathMap.get(documentIdentifier); if (path == null) { // Not yet present. Look it up, recursively String identifierPart = documentIdentifier; // Get the current node's name first // D = Document; anything else = Folder if (identifierPart.startsWith("D") || identifierPart.startsWith("F")) { // Strip off the letter identifierPart = identifierPart.substring(1); } // See if there's a volume label; if not, use the default. int colonPosition = identifierPart.indexOf(":"); int volumeID; int objectID; try { if (colonPosition == -1) { // Default volume ID volumeID = LLENTWK_VOL; objectID = Integer.parseInt(identifierPart); } else { volumeID = Integer.parseInt(identifierPart.substring(0,colonPosition)); objectID = Integer.parseInt(identifierPart.substring(colonPosition+1)); } } catch (NumberFormatException e) { throw new ManifoldCFException("Bad document identifier: "+e.getMessage(),e); } ObjectInformation objInfo = llc.getObjectInformation(volumeID,objectID); if (!objInfo.exists()) { // The document identifier describes a path that does not exist. // This is unexpected, but don't die: just log a warning and allow the higher level to deal with it. Logging.connectors.warn("Livelink: Bad document identifier: '"+documentIdentifier+"' apparently does not exist, but need to find its path"); return null; } // Get the name attribute String name = objInfo.getName(); // Get the parentID attribute int parentID = objInfo.getParentId().intValue(); if (parentID == -1) path = name; else { String parentIdentifier = "F"+Integer.toString(volumeID)+":"+Integer.toString(parentID); String parentPath = getNodePathString(parentIdentifier); if (parentPath == null) return null; path = parentPath + pathSeparator + name; } pathMap.put(documentIdentifier,path); } return path; } } /** Class that manages to find catid's and attribute names that have been specified. * This accepts a part of the version string which contains the string-ified metadata * spec, rather than pulling it out of the document specification. That guarantees that * the version string actually corresponds to the document that was ingested. */ protected class MetadataDescription { protected final LivelinkContext llc; // This is a map of category name to category ID and attributes protected final Map<String,MetadataPathItem> categoryMap = new HashMap<String,MetadataPathItem>(); /** Constructor. */ public MetadataDescription(LivelinkContext llc) { this.llc = llc; } /** Iterate over the metadata items represented by the specified chunk of version string. *@return an iterator over MetadataItem objects. */ public Iterator<MetadataItem> getItems(String[] metadataItems) throws ManifoldCFException, ServiceInterruption { // This is the map that will be iterated over for a return value. // It gets built out of (hopefully cached) data from categoryMap. Map<String,MetadataItem> newMap = new HashMap<String,MetadataItem>(); // Start at root ObjectInformation rootValue = null; // Walk through string and process each metadata element in turn. for (String metadataSpec : metadataItems) { StringBuilder categoryBuffer = new StringBuilder(); StringBuilder attributeBuffer = new StringBuilder(); unpackCategoryAttribute(categoryBuffer,attributeBuffer,metadataSpec); String category = categoryBuffer.toString(); String attributeName = attributeBuffer.toString(); // If there's already an entry for this category in the return map, use it MetadataItem mi = newMap.get(category); if (mi == null) { // Now, look up the node information // Convert category to cat id. MetadataPathItem item = categoryMap.get(category); if (item == null) { RootValue rv = new RootValue(llc,category); if (rootValue == null) { rootValue = rv.getRootValue(); } // Get the object id of the category the path describes. // NOTE: We don't use the RootValue version of getCategoryId because // we want to use the cached value of rootValue, if it was around. int catObjectID = rootValue.getCategoryId(rv.getRemainderPath()); if (catObjectID != -1) { item = new MetadataPathItem(catObjectID,rv.getRemainderPath()); categoryMap.put(category,item); } } mi = new MetadataItem(item); newMap.put(category,mi); } // Add attribute name to category mi.addAttribute(attributeName); } return newMap.values().iterator(); } } /** This class caches the category path strings associated with a given category object identifier. * The goal is to allow reasonably speedy lookup of the path name, so we can put it into the metadata part of the * version string. */ protected class CategoryPathAccumulator { // Livelink context protected final LivelinkContext llc; // This is the map from category ID to category path name. // It's keyed by an Integer formed from the id, and has String values. protected final Map<Integer,String> categoryPathMap = new HashMap<Integer,String>(); // This is the map from category ID to attribute names. Keyed // by an Integer formed from the id, and has a String[] value. protected final Map<Integer,String[]> attributeMap = new HashMap<Integer,String[]>(); /** Constructor */ public CategoryPathAccumulator(LivelinkContext llc) { this.llc = llc; } /** Get a specified set of packed category paths with attribute names, given the category identifiers */ public String[] getCategoryPathsAttributeNames(int[] catIDs) throws ManifoldCFException, ServiceInterruption { Set<String> set = new HashSet<String>(); for (int x : catIDs) { Integer key = new Integer(x); String pathValue = categoryPathMap.get(key); if (pathValue == null) { // Chase the path back up the chain pathValue = findPath(key.intValue()); if (pathValue == null) continue; categoryPathMap.put(key,pathValue); } String[] attributeNames = attributeMap.get(key); if (attributeNames == null) { // Get the attributes for this category attributeNames = findAttributes(key.intValue()); if (attributeNames == null) continue; attributeMap.put(key,attributeNames); } // Now, put the path and the attributes into the hash. for (String attributeName : attributeNames) { String metadataName = packCategoryAttribute(pathValue,attributeName); set.add(metadataName); } } String[] rval = new String[set.size()]; int i = 0; for (String value : set) { rval[i++] = value; } return rval; } /** Find a category path given a category ID */ protected String findPath(int catID) throws ManifoldCFException, ServiceInterruption { return getObjectPath(llc.getObjectInformation(0,catID)); } /** Get the complete path for an object. */ protected String getObjectPath(ObjectInformation currentObject) throws ManifoldCFException, ServiceInterruption { String path = null; while (true) { if (currentObject.isCategoryWorkspace()) return CATEGORY_NAME + ((path==null)?"":":" + path); else if (currentObject.isEntityWorkspace()) return ENTWKSPACE_NAME + ((path==null)?"":":" + path); if (!currentObject.exists()) { // The document identifier describes a path that does not exist. // This is unexpected, but an exception would terminate the job, and we don't want that. Logging.connectors.warn("Livelink: Bad identifier found? "+currentObject.toString()+" apparently does not exist, but need to look up its path"); return null; } // Get the name attribute String name = currentObject.getName(); if (path == null) path = name; else path = name + "/" + path; // Get the parentID attribute int parentID = currentObject.getParentId().intValue(); if (parentID == -1) { // Oops, hit the top of the path without finding the workspace we're in. // No idea where it lives; note this condition and exit. Logging.connectors.warn("Livelink: Object ID "+currentObject.toString()+" doesn't seem to live in enterprise or category workspace! Path I got was '"+path+"'"); return null; } currentObject = llc.getObjectInformation(0,parentID); } } /** Find a set of attributes given a category ID */ protected String[] findAttributes(int catID) throws ManifoldCFException, ServiceInterruption { return getCategoryAttributes(catID); } } /** Class representing a root value object, plus remainder string. * This class peels off the workspace name prefix from a path string or * attribute string, and finds the right workspace root node and remainder * path. */ protected class RootValue { protected final LivelinkContext llc; protected final String workspaceName; protected ObjectInformation rootValue = null; protected final String remainderPath; /** Constructor. *@param pathString is the path string. */ public RootValue(LivelinkContext llc, String pathString) { this.llc = llc; int colonPos = pathString.indexOf(":"); if (colonPos == -1) { remainderPath = pathString; workspaceName = ENTWKSPACE_NAME; } else { workspaceName = pathString.substring(0,colonPos); remainderPath = pathString.substring(colonPos+1); } } /** Get the path string. *@return the path string (without the workspace name prefix). */ public String getRemainderPath() { return remainderPath; } /** Get the root node. *@return the root node. */ public ObjectInformation getRootValue() throws ManifoldCFException, ServiceInterruption { if (rootValue == null) { if (workspaceName.equals(CATEGORY_NAME)) rootValue = llc.getObjectInformation(LLCATWK_VOL,LLCATWK_ID); else if (workspaceName.equals(ENTWKSPACE_NAME)) rootValue = llc.getObjectInformation(LLENTWK_VOL,LLENTWK_ID); else throw new ManifoldCFException("Bad workspace name: "+workspaceName); } if (!rootValue.exists()) { Logging.connectors.warn("Livelink: Could not get workspace/volume ID! Retrying..."); // This cannot mean a real failure; it MUST mean that we have had an intermittent communication hiccup. So, pass it off as a service interruption. throw new ServiceInterruption("Service interruption getting root value",new ManifoldCFException("Could not get workspace/volume id"),System.currentTimeMillis()+60000L, System.currentTimeMillis()+600000L,-1,true); } return rootValue; } } // Here's an interesting note. All of the LAPI exceptions are subclassed off of RuntimeException. This makes life // hell because there is no superclass exception to capture, and even tweaky server communication issues wind up throwing // uncaught RuntimeException's up the stack. // // To fix this rather bad design, all places that invoke LAPI need to catch RuntimeException and run it through the following // method for interpretation and logging. // /** Interpret runtimeexception to search for livelink API errors. Throws an appropriately reinterpreted exception, or * just returns if the exception indicates that a short-cycle retry attempt should be made. (In that case, the appropriate * wait has been already performed). *@param e is the RuntimeException caught *@param failIfTimeout is true if, for transient conditions, we want to signal failure if the timeout condition is acheived. */ protected int handleLivelinkRuntimeException(RuntimeException e, int sanityRetryCount, boolean failIfTimeout) throws ManifoldCFException, ServiceInterruption { if ( e instanceof com.opentext.api.LLHTTPAccessDeniedException || e instanceof com.opentext.api.LLHTTPClientException || e instanceof com.opentext.api.LLHTTPServerException || e instanceof com.opentext.api.LLIndexOutOfBoundsException || e instanceof com.opentext.api.LLNoFieldSpecifiedException || e instanceof com.opentext.api.LLNoValueSpecifiedException || e instanceof com.opentext.api.LLSecurityProviderException || e instanceof com.opentext.api.LLUnknownFieldException || e instanceof NumberFormatException || e instanceof ArrayIndexOutOfBoundsException ) { String details = llServer.getErrors(); long currentTime = System.currentTimeMillis(); throw new ServiceInterruption("Livelink API error: "+e.getMessage()+((details==null)?"":"; "+details),e,currentTime + 5*60000L,currentTime+12*60*60000L,-1,failIfTimeout); } else if ( e instanceof com.opentext.api.LLBadServerCertificateException || e instanceof com.opentext.api.LLHTTPCGINotFoundException || e instanceof com.opentext.api.LLCouldNotConnectHTTPException || e instanceof com.opentext.api.LLHTTPForbiddenException || e instanceof com.opentext.api.LLHTTPProxyAuthRequiredException || e instanceof com.opentext.api.LLHTTPRedirectionException || e instanceof com.opentext.api.LLUnsupportedAuthMethodException || e instanceof com.opentext.api.LLWebAuthInitException ) { String details = llServer.getErrors(); throw new ManifoldCFException("Livelink API error: "+e.getMessage()+((details==null)?"":"; "+details),e); } else if (e instanceof com.opentext.api.LLSSLNotAvailableException) { String details = llServer.getErrors(); throw new ManifoldCFException("Missing llssl.jar error: "+e.getMessage()+((details==null)?"":"; "+details),e); } else if (e instanceof com.opentext.api.LLIllegalOperationException) { // This usually means that LAPI has had a minor communication difficulty but hasn't reported it accurately. // We *could* throw a ServiceInterruption, but OpenText recommends to just retry almost immediately. String details = llServer.getErrors(); return assessRetry(sanityRetryCount,new ManifoldCFException("Livelink API illegal operation error: "+e.getMessage()+((details==null)?"":"; "+details),e)); } else if (e instanceof com.opentext.api.LLIOException || (e instanceof RuntimeException && e.getClass().getName().startsWith("com.opentext.api."))) { // Catching obfuscated and unspecified opentext runtime exceptions now too - these come from llssl.jar. We // have to presume these are SSL connection errors; nothing else to go by unfortunately. UGH. // Treat this as a transient error; try again in 5 minutes, and only fail after 12 hours of trying // LAPI is returning errors that are not terribly explicit, and I don't have control over their wording, so check that server can be resolved by DNS, // so that a better error message can be returned. try { InetAddress.getByName(serverName); } catch (UnknownHostException e2) { throw new ManifoldCFException("Server name '"+serverName+"' cannot be resolved",e2); } long currentTime = System.currentTimeMillis(); throw new ServiceInterruption(e.getMessage(),e,currentTime + 5*60000L,currentTime+12*60*60000L,-1,failIfTimeout); } else throw e; } /** Do a retry, or throw an exception if the retry count has been exhausted */ protected static int assessRetry(int sanityRetryCount, ManifoldCFException e) throws ManifoldCFException { if (sanityRetryCount == 0) { throw e; } sanityRetryCount--; try { ManifoldCF.sleep(1000L); } catch (InterruptedException e2) { throw new ManifoldCFException(e2.getMessage(),e2,ManifoldCFException.INTERRUPTED); } // Exit the method return sanityRetryCount; } /** This thread performs a LAPI FetchVersion command, streaming the resulting * document back through a XThreadInputStream to the invoking thread. */ protected class DocumentReadingThread extends Thread { protected Throwable exception = null; protected final int volumeID; protected final int docID; protected final int versionNumber; protected final XThreadInputStream stream; public DocumentReadingThread(int volumeID, int docID, int versionNumber) { super(); this.volumeID = volumeID; this.docID = docID; this.versionNumber = versionNumber; this.stream = new XThreadInputStream(); setDaemon(true); } @Override public void run() { try { XThreadOutputStream outputStream = new XThreadOutputStream(stream); try { int status = LLDocs.FetchVersion(volumeID, docID, versionNumber, outputStream); if (status != 0) { throw new ManifoldCFException("Error retrieving contents of document "+Integer.toString(volumeID)+":"+Integer.toString(docID)+" revision "+versionNumber+" : Status="+Integer.toString(status)+" ("+llServer.getErrors()+")"); } } finally { outputStream.close(); } } catch (Throwable e) { this.exception = e; } } public InputStream getSafeInputStream() { return stream; } public void finishUp() throws InterruptedException, ManifoldCFException { // This will be called during the finally // block in the case where all is well (and // the stream completed) and in the case where // there were exceptions. stream.abort(); join(); Throwable thr = exception; if (thr != null) { if (thr instanceof ManifoldCFException) throw (ManifoldCFException) thr; else if (thr instanceof RuntimeException) throw (RuntimeException) thr; else if (thr instanceof Error) throw (Error) thr; else throw new RuntimeException("Unhandled exception of type: "+thr.getClass().getName(),thr); } } } /** This thread does the actual socket communication with the server. * It's set up so that it can be abandoned at shutdown time. * * The way it works is as follows: * - it starts the transaction * - it receives the response, and saves that for the calling class to inspect * - it transfers the data part to an input stream provided to the calling class * - it shuts the connection down * * If there is an error, the sequence is aborted, and an exception is recorded * for the calling class to examine. * * The calling class basically accepts the sequence above. It starts the * thread, and tries to get a response code. If instead an exception is seen, * the exception is thrown up the stack. */ protected static class ExecuteMethodThread extends Thread { /** Client and method, all preconfigured */ protected final HttpClient httpClient; protected final HttpRequestBase executeMethod; protected HttpResponse response = null; protected Throwable responseException = null; protected XThreadInputStream threadStream = null; protected InputStream bodyStream = null; protected boolean streamCreated = false; protected Throwable streamException = null; protected boolean abortThread = false; protected Throwable shutdownException = null; protected Throwable generalException = null; public ExecuteMethodThread(HttpClient httpClient, HttpRequestBase executeMethod) { super(); setDaemon(true); this.httpClient = httpClient; this.executeMethod = executeMethod; } public void run() { try { try { // Call the execute method appropriately synchronized (this) { if (!abortThread) { try { response = httpClient.execute(executeMethod); } catch (java.net.SocketTimeoutException e) { responseException = e; } catch (ConnectTimeoutException e) { responseException = e; } catch (InterruptedIOException e) { throw e; } catch (Throwable e) { responseException = e; } this.notifyAll(); } } // Start the transfer of the content if (responseException == null) { synchronized (this) { if (!abortThread) { try { bodyStream = response.getEntity().getContent(); if (bodyStream != null) { threadStream = new XThreadInputStream(bodyStream); } streamCreated = true; } catch (java.net.SocketTimeoutException e) { streamException = e; } catch (ConnectTimeoutException e) { streamException = e; } catch (InterruptedIOException e) { throw e; } catch (Throwable e) { streamException = e; } this.notifyAll(); } } } if (responseException == null && streamException == null) { if (threadStream != null) { // Stuff the content until we are done threadStream.stuffQueue(); } } } finally { if (bodyStream != null) { try { bodyStream.close(); } catch (IOException e) { } bodyStream = null; } synchronized (this) { try { executeMethod.abort(); } catch (Throwable e) { shutdownException = e; } this.notifyAll(); } } } catch (Throwable e) { // We catch exceptions here that should ONLY be InterruptedExceptions, as a result of the thread being aborted. this.generalException = e; } } public int getResponseCode() throws InterruptedException, IOException, HttpException { // Must wait until the response object is there while (true) { synchronized (this) { checkException(responseException); if (response != null) return response.getStatusLine().getStatusCode(); wait(); } } } public long getResponseContentLength() throws InterruptedException, IOException, HttpException { String contentLength = getFirstHeader("Content-Length"); if (contentLength == null || contentLength.length() == 0) return -1L; return new Long(contentLength.trim()).longValue(); } public String getFirstHeader(String headerName) throws InterruptedException, IOException, HttpException { // Must wait for the response object to appear while (true) { synchronized (this) { checkException(responseException); if (response != null) { Header h = response.getFirstHeader(headerName); if (h == null) return null; return h.getValue(); } wait(); } } } public InputStream getSafeInputStream() throws InterruptedException, IOException, HttpException { // Must wait until stream is created, or until we note an exception was thrown. while (true) { synchronized (this) { if (responseException != null) throw new IllegalStateException("Check for response before getting stream"); checkException(streamException); if (streamCreated) return threadStream; wait(); } } } public void abort() { // This will be called during the finally // block in the case where all is well (and // the stream completed) and in the case where // there were exceptions. synchronized (this) { if (streamCreated) { if (threadStream != null) threadStream.abort(); } abortThread = true; } } public void finishUp() throws InterruptedException { join(); } protected synchronized void checkException(Throwable exception) throws IOException, HttpException { if (exception != null) { // Throw the current exception, but clear it, so no further throwing is possible on the same problem. Throwable e = exception; if (e instanceof IOException) throw (IOException)e; else if (e instanceof HttpException) throw (HttpException)e; else if (e instanceof RuntimeException) throw (RuntimeException)e; else if (e instanceof Error) throw (Error)e; else throw new RuntimeException("Unhandled exception of type: "+e.getClass().getName(),e); } } } }
connectors/livelink/connector/src/main/java/org/apache/manifoldcf/crawler/connectors/livelink/LivelinkConnector.java
/* $Id: LivelinkConnector.java 996524 2010-09-13 13:38:01Z kwright $ */ /** * 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.manifoldcf.crawler.connectors.livelink; import org.apache.manifoldcf.core.interfaces.*; import org.apache.manifoldcf.agents.interfaces.*; import org.apache.manifoldcf.crawler.interfaces.*; import org.apache.manifoldcf.crawler.system.Logging; import org.apache.manifoldcf.crawler.system.ManifoldCF; import org.apache.manifoldcf.core.common.XThreadInputStream; import org.apache.manifoldcf.core.common.XThreadOutputStream; import org.apache.manifoldcf.core.common.InterruptibleSocketFactory; import org.apache.manifoldcf.core.common.DateParser; import org.apache.manifoldcf.livelink.*; import java.io.*; import java.util.*; import java.net.*; import java.util.concurrent.TimeUnit; import com.opentext.api.*; import org.apache.http.conn.HttpClientConnectionManager; import org.apache.http.client.HttpClient; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.protocol.HttpRequestExecutor; import org.apache.http.impl.client.HttpClients; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.CredentialsProvider; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.config.SocketConfig; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.NameValuePair; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.conn.ssl.BrowserCompatHostnameVerifier; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.auth.AuthScope; import org.apache.http.auth.NTCredentials; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpRequestBase; import org.apache.http.impl.client.DefaultRedirectStrategy; import org.apache.http.util.EntityUtils; import org.apache.http.HttpStatus; import org.apache.http.HttpHost; import org.apache.http.Header; import org.apache.http.message.BasicHeader; import org.apache.http.message.BasicNameValuePair; import org.apache.http.protocol.HTTP; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.HttpRequestRetryHandler; import org.apache.http.protocol.HttpContext; import org.apache.http.conn.ConnectTimeoutException; import org.apache.http.client.RedirectException; import org.apache.http.client.CircularRedirectException; import org.apache.http.NoHttpResponseException; import org.apache.http.HttpException; /** This is the Livelink implementation of the IRepositoryConnectr interface. * The original Volant code forced there to be one livelink session per JVM, with * lots of buggy synchronization present to try to enforce this. This implementation * is multi-session. However, since it is possible that the Volant restriction was * indeed needed, I have attempted to structure things to allow me to turn on * single-session if needed. * * For livelink, the document identifiers are the object identifiers. * */ public class LivelinkConnector extends org.apache.manifoldcf.crawler.connectors.BaseRepositoryConnector { public static final String _rcsid = "@(#)$Id: LivelinkConnector.java 996524 2010-09-13 13:38:01Z kwright $"; // Activities we will report on private final static String ACTIVITY_SEED = "find documents"; private final static String ACTIVITY_FETCH = "fetch document"; /** Deny access token for default authority */ private final static String defaultAuthorityDenyToken = GLOBAL_DENY_TOKEN; // A couple of very important points. // First, the canonical document identifier has the following form: // <D|F>[<volume_id>:]<object_id> // Second, the only LEGAL objects for a document identifier to describe // are folders, documents, and volume objects. Project objects are NOT // allowed; they must be mapped to the appropriate volume object before // being returned to the crawler. // Metadata names for general metadata fields protected final static String GENERAL_NAME_FIELD = "general_name"; protected final static String GENERAL_DESCRIPTION_FIELD = "general_description"; protected final static String GENERAL_CREATIONDATE_FIELD = "general_creationdate"; protected final static String GENERAL_MODIFYDATE_FIELD = "general_modifydate"; protected final static String GENERAL_OWNER = "general_owner"; protected final static String GENERAL_CREATOR = "general_creator"; protected final static String GENERAL_MODIFIER = "general_modifier"; protected final static String GENERAL_PARENTID = "general_parentid"; // Signal that we have set up connection parameters properly private boolean hasSessionParameters = false; // Signal that we have set up a connection properly private boolean hasConnected = false; // Session expiration time private long expirationTime = -1L; // Idle session expiration interval private final static long expirationInterval = 300000L; // Data required for maintaining livelink connection private LAPI_DOCUMENTS LLDocs = null; private LAPI_ATTRIBUTES LLAttributes = null; private LAPI_USERS LLUsers = null; private LLSERVER llServer = null; private int LLENTWK_VOL; private int LLENTWK_ID; private int LLCATWK_VOL; private int LLCATWK_ID; // Parameter values we need private String serverProtocol = null; private String serverName = null; private int serverPort = -1; private String serverUsername = null; private String serverPassword = null; private String serverHTTPCgi = null; private String serverHTTPNTLMDomain = null; private String serverHTTPNTLMUsername = null; private String serverHTTPNTLMPassword = null; private IKeystoreManager serverHTTPSKeystore = null; private String ingestProtocol = null; private String ingestPort = null; private String ingestCgiPath = null; private String viewProtocol = null; private String viewServerName = null; private String viewPort = null; private String viewCgiPath = null; private String ingestNtlmDomain = null; private String ingestNtlmUsername = null; private String ingestNtlmPassword = null; // SSL support for ingestion private IKeystoreManager ingestKeystoreManager = null; // Connection management private HttpClientConnectionManager connectionManager = null; private HttpClient httpClient = null; // Base path for viewing private String viewBasePath = null; // Ingestion port number private int ingestPortNumber = -1; // Activities list private static final String[] activitiesList = new String[]{ACTIVITY_SEED,ACTIVITY_FETCH}; // Retry count. This is so we can try to install some measure of sanity into situations where LAPI gets confused communicating to the server. // So, for some kinds of errors, we just retry for a while hoping it will go away. private static final int FAILURE_RETRY_COUNT = 10; // Current host name private static String currentHost = null; private static java.net.InetAddress currentAddr = null; static { // Find the current host name try { currentAddr = java.net.InetAddress.getLocalHost(); // Get hostname currentHost = currentAddr.getHostName(); } catch (UnknownHostException e) { } } /** Constructor. */ public LivelinkConnector() { } /** Tell the world what model this connector uses for getDocumentIdentifiers(). * This must return a model value as specified above. *@return the model type value. */ @Override public int getConnectorModel() { // Livelink is a chained hierarchy model return MODEL_CHAINED_ADD_CHANGE; } /** Connect. The configuration parameters are included. *@param configParams are the configuration parameters for this connection. */ @Override public void connect(ConfigParams configParams) { super.connect(configParams); // This is required by getBins() serverName = params.getParameter(LiveLinkParameters.serverName); } protected class GetSessionThread extends Thread { protected Throwable exception = null; public GetSessionThread() { super(); setDaemon(true); } public void run() { try { // Create the session llServer = new LLSERVER(!serverProtocol.equals("internal"),serverProtocol.equals("https"), serverName,serverPort,serverUsername,serverPassword, serverHTTPCgi,serverHTTPNTLMDomain,serverHTTPNTLMUsername,serverHTTPNTLMPassword, serverHTTPSKeystore); LLDocs = new LAPI_DOCUMENTS(llServer.getLLSession()); LLAttributes = new LAPI_ATTRIBUTES(llServer.getLLSession()); LLUsers = new LAPI_USERS(llServer.getLLSession()); if (Logging.connectors.isDebugEnabled()) { String passwordExists = (serverPassword!=null&&serverPassword.length()>0)?"password exists":""; Logging.connectors.debug("Livelink: Livelink Session: Server='"+serverName+"'; port='"+serverPort+"'; user name='"+serverUsername+"'; "+passwordExists); } LLValue entinfo = new LLValue().setAssoc(); int status; status = LLDocs.AccessEnterpriseWS(entinfo); if (status == 0) { LLENTWK_ID = entinfo.toInteger("ID"); LLENTWK_VOL = entinfo.toInteger("VolumeID"); } else throw new ManifoldCFException("Error accessing enterprise workspace: "+status); entinfo = new LLValue().setAssoc(); status = LLDocs.AccessCategoryWS(entinfo); if (status == 0) { LLCATWK_ID = entinfo.toInteger("ID"); LLCATWK_VOL = entinfo.toInteger("VolumeID"); } else throw new ManifoldCFException("Error accessing category workspace: "+status); } catch (Throwable e) { this.exception = e; } } public void finishUp() throws ManifoldCFException, InterruptedException { join(); Throwable thr = exception; if (thr != null) { if (thr instanceof RuntimeException) throw (RuntimeException)thr; else if (thr instanceof ManifoldCFException) throw (ManifoldCFException)thr; else if (thr instanceof Error) throw (Error)thr; else throw new RuntimeException("Unrecognized exception type: "+thr.getClass().getName()+": "+thr.getMessage(),thr); } } } /** Get the bin name string for a document identifier. The bin name describes the queue to which the * document will be assigned for throttling purposes. Throttling controls the rate at which items in a * given queue are fetched; it does not say anything about the overall fetch rate, which may operate on * multiple queues or bins. * For example, if you implement a web crawler, a good choice of bin name would be the server name, since * that is likely to correspond to a real resource that will need real throttle protection. *@param documentIdentifier is the document identifier. *@return the bin name. */ @Override public String[] getBinNames(String documentIdentifier) { // This should return server name return new String[]{serverName}; } protected HttpHost getHost() { return new HttpHost(llServer.getHost(),ingestPortNumber,ingestProtocol); } protected void getSessionParameters() throws ManifoldCFException { if (hasSessionParameters == false) { // Do the initial setup part (what used to be part of connect() itself) // Get the parameters ingestProtocol = params.getParameter(LiveLinkParameters.ingestProtocol); ingestPort = params.getParameter(LiveLinkParameters.ingestPort); ingestCgiPath = params.getParameter(LiveLinkParameters.ingestCgiPath); viewProtocol = params.getParameter(LiveLinkParameters.viewProtocol); viewServerName = params.getParameter(LiveLinkParameters.viewServerName); viewPort = params.getParameter(LiveLinkParameters.viewPort); viewCgiPath = params.getParameter(LiveLinkParameters.viewCgiPath); ingestNtlmDomain = params.getParameter(LiveLinkParameters.ingestNtlmDomain); ingestNtlmUsername = params.getParameter(LiveLinkParameters.ingestNtlmUsername); ingestNtlmPassword = params.getObfuscatedParameter(LiveLinkParameters.ingestNtlmPassword); serverProtocol = params.getParameter(LiveLinkParameters.serverProtocol); String serverPortString = params.getParameter(LiveLinkParameters.serverPort); serverUsername = params.getParameter(LiveLinkParameters.serverUsername); serverPassword = params.getObfuscatedParameter(LiveLinkParameters.serverPassword); serverHTTPCgi = params.getParameter(LiveLinkParameters.serverHTTPCgiPath); serverHTTPNTLMDomain = params.getParameter(LiveLinkParameters.serverHTTPNTLMDomain); serverHTTPNTLMUsername = params.getParameter(LiveLinkParameters.serverHTTPNTLMUsername); serverHTTPNTLMPassword = params.getObfuscatedParameter(LiveLinkParameters.serverHTTPNTLMPassword); if (ingestProtocol == null || ingestProtocol.length() == 0) ingestProtocol = null; if (viewProtocol == null || viewProtocol.length() == 0) { if (ingestProtocol == null) viewProtocol = "http"; else viewProtocol = ingestProtocol; } if (ingestPort == null || ingestPort.length() == 0) { if (ingestProtocol != null) { if (!ingestProtocol.equals("https")) ingestPort = "80"; else ingestPort = "443"; } else ingestPort = null; } if (viewPort == null || viewPort.length() == 0) { if (ingestProtocol == null || !viewProtocol.equals(ingestProtocol)) { if (!viewProtocol.equals("https")) viewPort = "80"; else viewPort = "443"; } else viewPort = ingestPort; } if (ingestPort != null) { try { ingestPortNumber = Integer.parseInt(ingestPort); } catch (NumberFormatException e) { throw new ManifoldCFException("Bad ingest port: "+e.getMessage(),e); } } String viewPortString; try { int portNumber = Integer.parseInt(viewPort); viewPortString = ":" + Integer.toString(portNumber); if (!viewProtocol.equals("https")) { if (portNumber == 80) viewPortString = ""; } else { if (portNumber == 443) viewPortString = ""; } } catch (NumberFormatException e) { throw new ManifoldCFException("Bad view port: "+e.getMessage(),e); } if (viewCgiPath == null || viewCgiPath.length() == 0) viewCgiPath = ingestCgiPath; if (ingestNtlmDomain != null && ingestNtlmDomain.length() == 0) ingestNtlmDomain = null; if (ingestNtlmDomain == null) { ingestNtlmUsername = null; ingestNtlmPassword = null; } else { if (ingestNtlmUsername == null || ingestNtlmUsername.length() == 0) { ingestNtlmUsername = serverUsername; if (ingestNtlmPassword == null || ingestNtlmPassword.length() == 0) ingestNtlmPassword = serverPassword; } else { if (ingestNtlmPassword == null) ingestNtlmPassword = ""; } } // Set up ingest ssl if indicated String ingestKeystoreData = params.getParameter(LiveLinkParameters.ingestKeystore); if (ingestKeystoreData != null) ingestKeystoreManager = KeystoreManagerFactory.make("",ingestKeystoreData); // Server parameter processing if (serverProtocol == null || serverProtocol.length() == 0) serverProtocol = "internal"; if (serverPortString == null) serverPort = 2099; else serverPort = new Integer(serverPortString).intValue(); if (serverHTTPNTLMDomain != null && serverHTTPNTLMDomain.length() == 0) serverHTTPNTLMDomain = null; if (serverHTTPNTLMUsername == null || serverHTTPNTLMUsername.length() == 0) { serverHTTPNTLMUsername = null; serverHTTPNTLMPassword = null; } // Set up server ssl if indicated String serverHTTPSKeystoreData = params.getParameter(LiveLinkParameters.serverHTTPSKeystore); if (serverHTTPSKeystoreData != null) serverHTTPSKeystore = KeystoreManagerFactory.make("",serverHTTPSKeystoreData); // View parameters if (viewServerName == null || viewServerName.length() == 0) viewServerName = serverName; viewBasePath = viewProtocol+"://"+viewServerName+viewPortString+viewCgiPath; hasSessionParameters = true; } } protected void getSession() throws ManifoldCFException, ServiceInterruption { getSessionParameters(); if (hasConnected == false) { int socketTimeout = 900000; int connectionTimeout = 300000; // Set up connection manager connectionManager = new PoolingHttpClientConnectionManager(); CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); // Set up ingest ssl if indicated SSLConnectionSocketFactory myFactory = null; if (ingestKeystoreManager != null) { myFactory = new SSLConnectionSocketFactory(new InterruptibleSocketFactory(ingestKeystoreManager.getSecureSocketFactory(), connectionTimeout), new BrowserCompatHostnameVerifier()); } // Set up authentication to use if (ingestNtlmDomain != null) { credentialsProvider.setCredentials(AuthScope.ANY, new NTCredentials(ingestNtlmUsername,ingestNtlmPassword,currentHost,ingestNtlmDomain)); } HttpClientBuilder builder = HttpClients.custom() .setConnectionManager(connectionManager) .setMaxConnTotal(1) .disableAutomaticRetries() .setDefaultRequestConfig(RequestConfig.custom() .setCircularRedirectsAllowed(true) .setSocketTimeout(socketTimeout) .setStaleConnectionCheckEnabled(true) .setExpectContinueEnabled(true) .setConnectTimeout(connectionTimeout) .setConnectionRequestTimeout(socketTimeout) .build()) .setDefaultSocketConfig(SocketConfig.custom() .setTcpNoDelay(true) .setSoTimeout(socketTimeout) .build()) .setDefaultCredentialsProvider(credentialsProvider) .setRequestExecutor(new HttpRequestExecutor(socketTimeout)) .setRedirectStrategy(new DefaultRedirectStrategy()); if (myFactory != null) builder.setSSLSocketFactory(myFactory); httpClient = builder.build(); // System.out.println("Connection server object = "+llServer.toString()); // Establish the actual connection int sanityRetryCount = FAILURE_RETRY_COUNT; while (true) { GetSessionThread t = new GetSessionThread(); try { t.start(); t.finishUp(); hasConnected = true; break; } catch (InterruptedException e) { t.interrupt(); throw new ManifoldCFException("Interrupted: "+e.getMessage(),e,ManifoldCFException.INTERRUPTED); } catch (RuntimeException e2) { sanityRetryCount = handleLivelinkRuntimeException(e2,sanityRetryCount,true); } } } expirationTime = System.currentTimeMillis() + expirationInterval; } // All methods below this line will ONLY be called if a connect() call succeeded // on this instance! protected static int executeMethodViaThread(HttpClient client, HttpRequestBase executeMethod) throws InterruptedException, HttpException, IOException { ExecuteMethodThread t = new ExecuteMethodThread(client,executeMethod); t.start(); try { return t.getResponseCode(); } catch (InterruptedException e) { t.interrupt(); throw e; } finally { t.abort(); t.finishUp(); } } /** Check status of connection. */ @Override public String check() throws ManifoldCFException { try { // Destroy saved session setup and repeat it hasConnected = false; getSession(); // Now, set up trial of ingestion connection if (ingestProtocol != null) { String contextMsg = "for document access"; String ingestHttpAddress = ingestCgiPath; HttpClient client = getInitializedClient(contextMsg); HttpGet method = new HttpGet(getHost().toURI() + ingestHttpAddress); method.setHeader(new BasicHeader("Accept","*/*")); try { int statusCode = executeMethodViaThread(client,method); switch (statusCode) { case 502: return "Fetch test had transient 502 error response"; case HttpStatus.SC_UNAUTHORIZED: return "Fetch test returned UNAUTHORIZED (401) response; check the security credentials and configuration"; case HttpStatus.SC_OK: return super.check(); default: return "Fetch test returned an unexpected response code of "+Integer.toString(statusCode); } } catch (InterruptedException e) { throw new ManifoldCFException("Interrupted: "+e.getMessage(),e,ManifoldCFException.INTERRUPTED); } catch (java.net.SocketTimeoutException e) { return "Fetch test timed out reading from the Livelink HTTP Server: "+e.getMessage(); } catch (java.net.SocketException e) { return "Fetch test received a socket error reading from Livelink HTTP Server: "+e.getMessage(); } catch (javax.net.ssl.SSLHandshakeException e) { return "Fetch test was unable to set up a SSL connection to Livelink HTTP Server: "+e.getMessage(); } catch (ConnectTimeoutException e) { return "Fetch test connection timed out reading from Livelink HTTP Server: "+e.getMessage(); } catch (InterruptedIOException e) { throw new ManifoldCFException("Interrupted: "+e.getMessage(),e,ManifoldCFException.INTERRUPTED); } catch (HttpException e) { return "Fetch test had an HTTP exception: "+e.getMessage(); } catch (IOException e) { return "Fetch test had an IO failure: "+e.getMessage(); } } else return super.check(); } catch (ServiceInterruption e) { return "Transient error: "+e.getMessage(); } catch (ManifoldCFException e) { if (e.getErrorCode() == ManifoldCFException.INTERRUPTED) throw e; return "Error: "+e.getMessage(); } } /** This method is periodically called for all connectors that are connected but not * in active use. */ @Override public void poll() throws ManifoldCFException { if (!hasConnected) return; long currentTime = System.currentTimeMillis(); if (currentTime >= expirationTime) { hasConnected = false; expirationTime = -1L; // Shutdown livelink connection if (llServer != null) { llServer.disconnect(); llServer = null; } // Shutdown pool if (connectionManager != null) { connectionManager.shutdown(); connectionManager = null; } } } /** This method is called to assess whether to count this connector instance should * actually be counted as being connected. *@return true if the connector instance is actually connected. */ @Override public boolean isConnected() { return hasConnected; } /** Close the connection. Call this before discarding the repository connector. */ @Override public void disconnect() throws ManifoldCFException { hasSessionParameters = false; hasConnected = false; expirationTime = -1L; if (llServer != null) { llServer.disconnect(); llServer = null; } LLDocs = null; LLAttributes = null; ingestKeystoreManager = null; ingestPortNumber = -1; serverProtocol = null; serverName = null; serverPort = -1; serverUsername = null; serverPassword = null; serverHTTPCgi = null; serverHTTPNTLMDomain = null; serverHTTPNTLMUsername = null; serverHTTPNTLMPassword = null; serverHTTPSKeystore = null; ingestPort = null; ingestProtocol = null; ingestCgiPath = null; viewPort = null; viewServerName = null; viewProtocol = null; viewCgiPath = null; viewBasePath = null; ingestNtlmDomain = null; ingestNtlmUsername = null; ingestNtlmPassword = null; if (connectionManager != null) { connectionManager.shutdown(); connectionManager = null; } super.disconnect(); } /** List the activities we might report on. */ @Override public String[] getActivitiesList() { return activitiesList; } /** Convert a document identifier to a relative URI to read data from. This is not the search URI; that's constructed * by a different method. *@param documentIdentifier is the document identifier. *@return the relative document uri. */ protected String convertToIngestURI(String documentIdentifier) throws ManifoldCFException { // The document identifier is the string form of the object ID for this connector. if (!documentIdentifier.startsWith("D")) return null; int colonPosition = documentIdentifier.indexOf(":",1); if (colonPosition == -1) return ingestCgiPath+"?func=ll&objID="+documentIdentifier.substring(1)+"&objAction=download"; else return ingestCgiPath+"?func=ll&objID="+documentIdentifier.substring(colonPosition+1)+"&objAction=download"; } /** Convert a document identifier to a URI to view. The URI is the URI that will be the unique key from * the search index, and will be presented to the user as part of the search results. It must therefore * be a unique way of describing the document. *@param documentIdentifier is the document identifier. *@return the document uri. */ protected String convertToViewURI(String documentIdentifier) throws ManifoldCFException { // The document identifier is the string form of the object ID for this connector. if (!documentIdentifier.startsWith("D")) return null; int colonPosition = documentIdentifier.indexOf(":",1); if (colonPosition == -1) return viewBasePath+"?func=ll&objID="+documentIdentifier.substring(1)+"&objAction=download"; else return viewBasePath+"?func=ll&objID="+documentIdentifier.substring(colonPosition+1)+"&objAction=download"; } /** Request arbitrary connector information. * This method is called directly from the API in order to allow API users to perform any one of several connector-specific * queries. *@param output is the response object, to be filled in by this method. *@param command is the command, which is taken directly from the API request. *@return true if the resource is found, false if not. In either case, output may be filled in. */ @Override public boolean requestInfo(Configuration output, String command) throws ManifoldCFException { if (command.equals("workspaces")) { try { String[] workspaces = getWorkspaceNames(); int i = 0; while (i < workspaces.length) { String workspace = workspaces[i++]; ConfigurationNode node = new ConfigurationNode("workspace"); node.setValue(workspace); output.addChild(output.getChildCount(),node); } } catch (ServiceInterruption e) { ManifoldCF.createServiceInterruptionNode(output,e); } catch (ManifoldCFException e) { ManifoldCF.createErrorNode(output,e); } } else if (command.startsWith("folders/")) { String path = command.substring("folders/".length()); try { String[] folders = getChildFolderNames(path); int i = 0; while (i < folders.length) { String folder = folders[i++]; ConfigurationNode node = new ConfigurationNode("folder"); node.setValue(folder); output.addChild(output.getChildCount(),node); } } catch (ServiceInterruption e) { ManifoldCF.createServiceInterruptionNode(output,e); } catch (ManifoldCFException e) { ManifoldCF.createErrorNode(output,e); } } else if (command.startsWith("categories/")) { String path = command.substring("categories/".length()); try { String[] categories = getChildCategoryNames(path); int i = 0; while (i < categories.length) { String category = categories[i++]; ConfigurationNode node = new ConfigurationNode("category"); node.setValue(category); output.addChild(output.getChildCount(),node); } } catch (ServiceInterruption e) { ManifoldCF.createServiceInterruptionNode(output,e); } catch (ManifoldCFException e) { ManifoldCF.createErrorNode(output,e); } } else if (command.startsWith("categoryattributes/")) { String path = command.substring("categoryattributes/".length()); try { String[] attributes = getCategoryAttributes(path); int i = 0; while (i < attributes.length) { String attribute = attributes[i++]; ConfigurationNode node = new ConfigurationNode("attribute"); node.setValue(attribute); output.addChild(output.getChildCount(),node); } } catch (ServiceInterruption e) { ManifoldCF.createServiceInterruptionNode(output,e); } catch (ManifoldCFException e) { ManifoldCF.createErrorNode(output,e); } } else return super.requestInfo(output,command); return true; } /** Queue "seed" documents. Seed documents are the starting places for crawling activity. Documents * are seeded when this method calls appropriate methods in the passed in ISeedingActivity object. * * This method can choose to find repository changes that happen only during the specified time interval. * The seeds recorded by this method will be viewed by the framework based on what the * getConnectorModel() method returns. * * It is not a big problem if the connector chooses to create more seeds than are * strictly necessary; it is merely a question of overall work required. * * The end time and seeding version string passed to this method may be interpreted for greatest efficiency. * For continuous crawling jobs, this method will * be called once, when the job starts, and at various periodic intervals as the job executes. * * When a job's specification is changed, the framework automatically resets the seeding version string to null. The * seeding version string may also be set to null on each job run, depending on the connector model returned by * getConnectorModel(). * * Note that it is always ok to send MORE documents rather than less to this method. * The connector will be connected before this method can be called. *@param activities is the interface this method should use to perform whatever framework actions are desired. *@param spec is a document specification (that comes from the job). *@param seedTime is the end of the time range of documents to consider, exclusive. *@param lastSeedVersionString is the last seeding version string for this job, or null if the job has no previous seeding version string. *@param jobMode is an integer describing how the job is being run, whether continuous or once-only. *@return an updated seeding version string, to be stored with the job. */ @Override public String addSeedDocuments(ISeedingActivity activities, Specification spec, String lastSeedVersion, long seedTime, int jobMode) throws ManifoldCFException, ServiceInterruption { getSession(); LivelinkContext llc = new LivelinkContext(); // First, grab the root LLValue ObjectInformation rootValue = llc.getObjectInformation(LLENTWK_VOL,LLENTWK_ID); if (!rootValue.exists()) { // If we get here, it HAS to be a bad network/transient problem. Logging.connectors.warn("Livelink: Could not look up root workspace object during seeding! Retrying -"); throw new ServiceInterruption("Service interruption during seeding",new ManifoldCFException("Could not looking root workspace object during seeding"),System.currentTimeMillis()+60000L, System.currentTimeMillis()+600000L,-1,true); } // Walk the specification for the "startpoint" types. Amalgamate these into a list of strings. // Presume that all roots are startpoint nodes boolean doUserWorkspaces = false; for (int i = 0; i < spec.getChildCount(); i++) { SpecificationNode n = spec.getChild(i); if (n.getType().equals("startpoint")) { // The id returned is simply the node path, which can't be messed up long beginTime = System.currentTimeMillis(); String path = n.getAttributeValue("path"); VolumeAndId vaf = rootValue.getPathId(path); if (vaf != null) { activities.recordActivity(new Long(beginTime),ACTIVITY_SEED,null, path,"OK",null,null); String newID = "F" + new Integer(vaf.getVolumeID()).toString()+":"+ new Integer(vaf.getPathId()).toString(); activities.addSeedDocument(newID); if (Logging.connectors.isDebugEnabled()) Logging.connectors.debug("Livelink: Seed = '"+newID+"'"); } else { activities.recordActivity(new Long(beginTime),ACTIVITY_SEED,null, path,"NOT FOUND",null,null); } } else if (n.getType().equals("userworkspace")) { String value = n.getAttributeValue("value"); if (value != null && value.equals("true")) doUserWorkspaces = true; else if (value != null && value.equals("false")) doUserWorkspaces = false; } if (doUserWorkspaces) { // Do ListUsers and enumerate the values. int sanityRetryCount = FAILURE_RETRY_COUNT; while (true) { ListUsersThread t = new ListUsersThread(); try { t.start(); LLValue childrenDocs; try { childrenDocs = t.finishUp(); } catch (ManifoldCFException e) { sanityRetryCount = assessRetry(sanityRetryCount,e); continue; } int size = 0; if (childrenDocs.isRecord()) size = 1; if (childrenDocs.isTable()) size = childrenDocs.size(); // Do the scan for (int j = 0; j < size; j++) { int childID = childrenDocs.toInteger(j, "ID"); // Skip admin user if (childID == 1000 || childID == 1001) continue; if (Logging.connectors.isDebugEnabled()) Logging.connectors.debug("Livelink: Found a user: ID="+Integer.toString(childID)); activities.addSeedDocument("F0:"+Integer.toString(childID)); } break; } catch (InterruptedException e) { t.interrupt(); throw new ManifoldCFException("Interrupted: "+e.getMessage(),e,ManifoldCFException.INTERRUPTED); } catch (RuntimeException e) { sanityRetryCount = handleLivelinkRuntimeException(e,sanityRetryCount,true); continue; } } } } return ""; } /** Process a set of documents. * This is the method that should cause each document to be fetched, processed, and the results either added * to the queue of documents for the current job, and/or entered into the incremental ingestion manager. * The document specification allows this class to filter what is done based on the job. * The connector will be connected before this method can be called. *@param documentIdentifiers is the set of document identifiers to process. *@param statuses are the currently-stored document versions for each document in the set of document identifiers * passed in above. *@param activities is the interface this method should use to queue up new document references * and ingest documents. *@param jobMode is an integer describing how the job is being run, whether continuous or once-only. *@param usesDefaultAuthority will be true only if the authority in use for these documents is the default one. */ @Override public void processDocuments(String[] documentIdentifiers, IExistingVersions statuses, Specification spec, IProcessActivity activities, int jobMode, boolean usesDefaultAuthority) throws ManifoldCFException, ServiceInterruption { // Initialize a "livelink context", to minimize the number of objects we have to fetch LivelinkContext llc = new LivelinkContext(); // Initialize the table of catid's. // Keeping this around will allow us to benefit from batching of documents. MetadataDescription desc = new MetadataDescription(llc); // First, process the spec to get the string we tack on SystemMetadataDescription sDesc = new SystemMetadataDescription(llc,spec); // Read the forced acls. A null return indicates that security is disabled!!! // A zero-length return indicates that the native acls should be used. // All of this is germane to how we ingest the document, so we need to note it in // the version string completely. String[] acls = sDesc.getAcls(); // Sort it, in case it is needed. if (acls != null) java.util.Arrays.sort(acls); // Prepare the specified metadata String metadataString = null; String[] specifiedMetadataAttributes = null; CategoryPathAccumulator catAccum = null; if (!sDesc.includeAllMetadata()) { StringBuilder sb = new StringBuilder(); specifiedMetadataAttributes = sDesc.getMetadataAttributes(); // Sort! java.util.Arrays.sort(specifiedMetadataAttributes); // Build the metadata string piece now packList(sb,specifiedMetadataAttributes,'+'); metadataString = sb.toString(); } else catAccum = new CategoryPathAccumulator(llc); // Calculate the part of the version string that comes from path name and mapping. // This starts with = since ; is used by another optional component (the forced acls) String pathNameAttributeVersion; StringBuilder sb2 = new StringBuilder(); if (sDesc.getPathAttributeName() != null) sb2.append("=").append(sDesc.getPathAttributeName()).append(":").append(sDesc.getPathSeparator()).append(":").append(sDesc.getMatchMapString()); pathNameAttributeVersion = sb2.toString(); // Since the identifier indicates it is a directory, then queue up all the current children which pass the filter. String filterString = sDesc.getFilterString(); for (String documentIdentifier : documentIdentifiers) { // Since each livelink access is time-consuming, be sure that we abort if the job has gone inactive activities.checkJobStillActive(); // Read the document or folder metadata, which includes the ModifyDate String docID = documentIdentifier; boolean isFolder = docID.startsWith("F"); int colonPos = docID.indexOf(":",1); int objID; int vol; if (colonPos == -1) { objID = new Integer(docID.substring(1)).intValue(); vol = LLENTWK_VOL; } else { objID = new Integer(docID.substring(colonPos+1)).intValue(); vol = new Integer(docID.substring(1,colonPos)).intValue(); } getSession(); ObjectInformation value = llc.getObjectInformation(vol,objID); if (value.exists()) { // Make sure we have permission to see the object's contents int permissions = value.getPermissions().intValue(); if ((permissions & LAPI_DOCUMENTS.PERM_SEECONTENTS) != 0) { Date dt = value.getModifyDate(); // The rights don't change when the object changes, so we have to include those too. int[] rights = getObjectRights(vol,objID); if (rights != null) { // We were able to get rights, so object still exists. // Changed folder versioning for MCF 2.0 if (isFolder) { // === Livelink folder === // I'm still not sure if Livelink folder modified dates are one-level or hierarchical. // The code below assumes one-level only, so we always scan folders and there's no versioning if (Logging.connectors.isDebugEnabled()) Logging.connectors.debug("Livelink: Processing folder "+Integer.toString(vol)+":"+Integer.toString(objID)); int sanityRetryCount = FAILURE_RETRY_COUNT; while (true) { ListObjectsThread t = new ListObjectsThread(vol,objID,filterString); try { t.start(); LLValue childrenDocs; try { childrenDocs = t.finishUp(); } catch (ManifoldCFException e) { sanityRetryCount = assessRetry(sanityRetryCount,e); continue; } int size = 0; if (childrenDocs.isRecord()) size = 1; if (childrenDocs.isTable()) size = childrenDocs.size(); // System.out.println("Total child count = "+Integer.toString(size)); // Do the scan for (int j = 0; j < size; j++) { int childID = childrenDocs.toInteger(j, "ID"); if (Logging.connectors.isDebugEnabled()) Logging.connectors.debug("Livelink: Found a child of folder "+Integer.toString(vol)+":"+Integer.toString(objID)+" : ID="+Integer.toString(childID)); int subtype = childrenDocs.toInteger(j, "SubType"); boolean childIsFolder = (subtype == LAPI_DOCUMENTS.FOLDERSUBTYPE || subtype == LAPI_DOCUMENTS.PROJECTSUBTYPE || subtype == LAPI_DOCUMENTS.COMPOUNDDOCUMENTSUBTYPE); // If it's a folder, we just let it through for now if (!childIsFolder && checkInclude(childrenDocs.toString(j,"Name") + "." + childrenDocs.toString(j,"FileType"), spec) == false) { if (Logging.connectors.isDebugEnabled()) Logging.connectors.debug("Livelink: Child identifier "+Integer.toString(childID)+" was excluded by inclusion criteria"); continue; } if (childIsFolder) { if (Logging.connectors.isDebugEnabled()) Logging.connectors.debug("Livelink: Child identifier "+Integer.toString(childID)+" is a folder, project, or compound document; adding a reference"); if (subtype == LAPI_DOCUMENTS.PROJECTSUBTYPE) { // If we pick up a project object, we need to describe the volume object (which // will be the root of all documents beneath) activities.addDocumentReference("F"+new Integer(childID).toString()+":"+new Integer(-childID).toString()); } else activities.addDocumentReference("F"+new Integer(vol).toString()+":"+new Integer(childID).toString()); } else { if (Logging.connectors.isDebugEnabled()) Logging.connectors.debug("Livelink: Child identifier "+Integer.toString(childID)+" is a simple document; adding a reference"); activities.addDocumentReference("D"+new Integer(vol).toString()+":"+new Integer(childID).toString()); } } break; } catch (InterruptedException e) { t.interrupt(); throw new ManifoldCFException("Interrupted: "+e.getMessage(),e,ManifoldCFException.INTERRUPTED); } catch (RuntimeException e) { sanityRetryCount = handleLivelinkRuntimeException(e,sanityRetryCount,true); continue; } } if (Logging.connectors.isDebugEnabled()) Logging.connectors.debug("Livelink: Done processing folder "+Integer.toString(vol)+":"+Integer.toString(objID)); } else { // === Livelink document === // The version string includes the following: // 1) The modify date for the document // 2) The rights for the document, ordered (which can change without changing the ModifyDate field) // 3) The requested metadata fields (category and attribute, ordered) for the document // // The document identifiers are object id's. StringBuilder sb = new StringBuilder(); String[] categoryPaths; if (sDesc.includeAllMetadata()) { // Find all the metadata associated with this object, and then // find the set of category pathnames that correspond to it. int[] catIDs = getObjectCategoryIDs(vol,objID); categoryPaths = catAccum.getCategoryPathsAttributeNames(catIDs); // Sort! java.util.Arrays.sort(categoryPaths); // Build the metadata string piece now packList(sb,categoryPaths,'+'); } else { categoryPaths = specifiedMetadataAttributes; sb.append(metadataString); } String[] actualAcls; String[] denyAcls; String denyAcl; if (acls != null && acls.length == 0) { // No forced acls. Read the actual acls from livelink, as a set of rights. // We need also to add in support for the special rights objects. These are: // -1: RIGHT_WORLD // -2: RIGHT_SYSTEM // -3: RIGHT_OWNER // -4: RIGHT_GROUP // // RIGHT_WORLD means guest access. // RIGHT_SYSTEM is "Public Access". // RIGHT_OWNER is access by the owner of the object. // RIGHT_GROUP is access by a member of the base group containing the owner // // These objects are returned by the GetObjectRights() call made above, and NOT // returned by LLUser.ListObjects(). We have to figure out how to map these to // things that are // the equivalent of acls. actualAcls = lookupTokens(rights, value); java.util.Arrays.sort(actualAcls); // If security is on, no deny acl is needed for the local authority, since the repository does not support "deny". But this was added // to be really really really sure. denyAcl = defaultAuthorityDenyToken; } else if (acls != null && acls.length > 0) { // Forced acls actualAcls = acls; denyAcl = defaultAuthorityDenyToken; } else { // Security is OFF actualAcls = acls; denyAcl = null; } // Now encode the acls. If null, we write a special value. if (actualAcls == null) { sb.append('-'); denyAcls = null; } else { sb.append('+'); packList(sb,actualAcls,'+'); // This was added on 4/21/2008 to support forced acls working with the global default authority. pack(sb,denyAcl,'+'); denyAcls = new String[]{denyAcl}; } // The date does not need to be parseable sb.append(new Long(dt.getTime()).toString()); // PathNameAttributeVersion comes completely from the spec, so we don't // have to worry about it changing. No need, therefore, to parse it during // processDocuments. sb.append("=").append(pathNameAttributeVersion); // Tack on ingestCgiPath, to insulate us against changes to the repository connection setup. Added 9/7/07. sb.append("_").append(viewBasePath); String versionString = sb.toString(); if (Logging.connectors.isDebugEnabled()) Logging.connectors.debug("Livelink: Successfully calculated version string for document "+Integer.toString(vol)+":"+Integer.toString(objID)+" : '"+versionString+"'"); if (activities.checkDocumentNeedsReindexing(documentIdentifier,versionString)) { // Index the document if (Logging.connectors.isDebugEnabled()) Logging.connectors.debug("Livelink: Processing document "+Integer.toString(vol)+":"+Integer.toString(objID)); if (checkIngest(llc,objID,spec)) { if (Logging.connectors.isDebugEnabled()) Logging.connectors.debug("Livelink: Decided to ingest document "+Integer.toString(vol)+":"+Integer.toString(objID)); // Grab the access tokens for this file from the version string, inside ingest method. ingestFromLiveLink(llc,documentIdentifier,versionString,actualAcls,denyAcls,categoryPaths,activities,desc,sDesc); } else { if (Logging.connectors.isDebugEnabled()) Logging.connectors.debug("Livelink: Decided not to ingest document "+Integer.toString(vol)+":"+Integer.toString(objID)+" - Did not match ingestion criteria"); activities.noDocument(documentIdentifier,versionString); } if (Logging.connectors.isDebugEnabled()) Logging.connectors.debug("Livelink: Done processing document "+Integer.toString(vol)+":"+Integer.toString(objID)); } } } else { if (Logging.connectors.isDebugEnabled()) Logging.connectors.debug("Livelink: Could not get rights for object "+Integer.toString(vol)+":"+Integer.toString(objID)+" - deleting"); activities.deleteDocument(documentIdentifier); continue; } } else { if (Logging.connectors.isDebugEnabled()) Logging.connectors.debug("Livelink: Crawl user cannot see contents of object "+Integer.toString(vol)+":"+Integer.toString(objID)+" - deleting"); activities.deleteDocument(documentIdentifier); continue; } } else { if (Logging.connectors.isDebugEnabled()) Logging.connectors.debug("Livelink: Object "+Integer.toString(vol)+":"+Integer.toString(objID)+" has no information - deleting"); activities.deleteDocument(documentIdentifier); continue; } } } protected class ListObjectsThread extends Thread { protected final int vol; protected final int objID; protected final String filterString; protected Throwable exception = null; protected LLValue rval = null; public ListObjectsThread(int vol, int objID, String filterString) { super(); setDaemon(true); this.vol = vol; this.objID = objID; this.filterString = filterString; } public void run() { try { LLValue childrenDocs = new LLValue(); int status = LLDocs.ListObjects(vol, objID, null, filterString, LAPI_DOCUMENTS.PERM_SEECONTENTS, childrenDocs); if (status != 0) { throw new ManifoldCFException("Error retrieving contents of folder "+Integer.toString(vol)+":"+Integer.toString(objID)+" : Status="+Integer.toString(status)+" ("+llServer.getErrors()+")"); } rval = childrenDocs; } catch (Throwable e) { this.exception = e; } } public LLValue finishUp() throws ManifoldCFException, InterruptedException { join(); Throwable thr = exception; if (thr != null) { if (thr instanceof RuntimeException) throw (RuntimeException)thr; else if (thr instanceof ManifoldCFException) throw (ManifoldCFException)thr; else if (thr instanceof Error) throw (Error)thr; else throw new RuntimeException("Unrecognized exception type: "+thr.getClass().getName()+": "+thr.getMessage(),thr); } return rval; } } /** Get the maximum number of documents to amalgamate together into one batch, for this connector. *@return the maximum number. 0 indicates "unlimited". */ @Override public int getMaxDocumentRequest() { // Intrinsically, Livelink doesn't batch well. Multiple chunks have no advantage over one-at-a-time requests, // since apparently the Livelink API does not support multiples. HOWEVER - when metadata is considered, // it becomes worthwhile, because we will be able to do what is needed to look up the correct CATID node // only once per n requests! So it's a tradeoff between the advantage gained by threading, and the // savings gained by CATID lookup. // Note that at Shell, the fact that the network hiccups a lot makes it better to choose a smaller value. return 6; } // UI support methods. // // These support methods come in two varieties. The first bunch is involved in setting up connection configuration information. The second bunch // is involved in presenting and editing document specification information for a job. The two kinds of methods are accordingly treated differently, // in that the first bunch cannot assume that the current connector object is connected, while the second bunch can. That is why the first bunch // receives a thread context argument for all UI methods, while the second bunch does not need one (since it has already been applied via the connect() // method, above). /** Output the configuration header section. * This method is called in the head section of the connector's configuration page. Its purpose is to add the required tabs to the list, and to output any * javascript methods that might be needed by the configuration editing HTML. *@param threadContext is the local thread context. *@param out is the output to which any HTML should be sent. *@param parameters are the configuration parameters, as they currently exist, for this connection being configured. *@param tabsArray is an array of tab names. Add to this array any tab names that are specific to the connector. */ @Override public void outputConfigurationHeader(IThreadContext threadContext, IHTTPOutput out, Locale locale, ConfigParams parameters, List<String> tabsArray) throws ManifoldCFException, IOException { tabsArray.add(Messages.getString(locale,"LivelinkConnector.Server")); tabsArray.add(Messages.getString(locale,"LivelinkConnector.DocumentAccess")); tabsArray.add(Messages.getString(locale,"LivelinkConnector.DocumentView")); out.print( "<script type=\"text/javascript\">\n"+ "<!--\n"+ "function ServerDeleteCertificate(aliasName)\n"+ "{\n"+ " editconnection.serverkeystorealias.value = aliasName;\n"+ " editconnection.serverconfigop.value = \"Delete\";\n"+ " postForm();\n"+ "}\n"+ "\n"+ "function ServerAddCertificate()\n"+ "{\n"+ " if (editconnection.servercertificate.value == \"\")\n"+ " {\n"+ " alert(\""+Messages.getBodyJavascriptString(locale,"LivelinkConnector.ChooseACertificateFile")+"\");\n"+ " editconnection.servercertificate.focus();\n"+ " }\n"+ " else\n"+ " {\n"+ " editconnection.serverconfigop.value = \"Add\";\n"+ " postForm();\n"+ " }\n"+ "}\n"+ "\n"+ "function IngestDeleteCertificate(aliasName)\n"+ "{\n"+ " editconnection.ingestkeystorealias.value = aliasName;\n"+ " editconnection.ingestconfigop.value = \"Delete\";\n"+ " postForm();\n"+ "}\n"+ "\n"+ "function IngestAddCertificate()\n"+ "{\n"+ " if (editconnection.ingestcertificate.value == \"\")\n"+ " {\n"+ " alert(\""+Messages.getBodyJavascriptString(locale,"LivelinkConnector.ChooseACertificateFile")+"\");\n"+ " editconnection.ingestcertificate.focus();\n"+ " }\n"+ " else\n"+ " {\n"+ " editconnection.ingestconfigop.value = \"Add\";\n"+ " postForm();\n"+ " }\n"+ "}\n"+ "\n"+ "function checkConfig()\n"+ "{\n"+ " if (editconnection.serverport.value != \"\" && !isInteger(editconnection.serverport.value))\n"+ " {\n"+ " alert(\""+Messages.getBodyJavascriptString(locale,"LivelinkConnector.AValidNumberIsRequired")+"\");\n"+ " editconnection.serverport.focus();\n"+ " return false;\n"+ " }\n"+ " if (editconnection.ingestport.value != \"\" && !isInteger(editconnection.ingestport.value))\n"+ " {\n"+ " alert(\""+Messages.getBodyJavascriptString(locale,"LivelinkConnector.AValidNumberOrBlankIsRequired")+"\");\n"+ " editconnection.ingestport.focus();\n"+ " return false;\n"+ " }\n"+ " if (editconnection.viewport.value != \"\" && !isInteger(editconnection.viewport.value))\n"+ " {\n"+ " alert(\""+Messages.getBodyJavascriptString(locale,"LivelinkConnector.AValidNumberOrBlankIsRequired")+"\");\n"+ " editconnection.viewport.focus();\n"+ " return false;\n"+ " }\n"+ " return true;\n"+ "}\n"+ "\n"+ "function checkConfigForSave()\n"+ "{\n"+ " if (editconnection.servername.value == \"\")\n"+ " {\n"+ " alert(\""+Messages.getBodyJavascriptString(locale,"LivelinkConnector.EnterALivelinkServerName")+"\");\n"+ " SelectTab(\"" + Messages.getBodyJavascriptString(locale,"LivelinkConnector.Server") + "\");\n"+ " editconnection.servername.focus();\n"+ " return false;\n"+ " }\n"+ " if (editconnection.serverport.value == \"\")\n"+ " {\n"+ " alert(\""+Messages.getBodyJavascriptString(locale,"LivelinkConnector.AServerPortNumberIsRequired")+"\");\n"+ " SelectTab(\"" + Messages.getBodyJavascriptString(locale,"LivelinkConnector.Server") + "\");\n"+ " editconnection.serverport.focus();\n"+ " return false;\n"+ " }\n"+ " if (editconnection.serverhttpcgipath.value == \"\")\n"+ " {\n"+ " alert(\""+Messages.getBodyJavascriptString(locale,"LivelinkConnector.EnterTheServerCgiPathToLivelink")+"\");\n"+ " SelectTab(\"" + Messages.getBodyJavascriptString(locale,"LivelinkConnector.Server") + "\");\n"+ " editconnection.serverhttpcgipath.focus();\n"+ " return false;\n"+ " }\n"+ " if (editconnection.serverhttpcgipath.value.substring(0,1) != \"/\")\n"+ " {\n"+ " alert(\""+Messages.getBodyJavascriptString(locale,"LivelinkConnector.TheServerCgiPathMustBeginWithACharacter")+"\");\n"+ " SelectTab(\"" + Messages.getBodyJavascriptString(locale,"LivelinkConnector.Server") + "\");\n"+ " editconnection.serverhttpcgipath.focus();\n"+ " return false;\n"+ " }\n"+ " if (editconnection.viewprotocol.value == \"\" && editconnection.ingestprotocol.value == \"\")\n"+ " {\n"+ " alert(\""+Messages.getBodyJavascriptString(locale,"LivelinkConnector.SelectAViewProtocol")+"\");\n"+ " SelectTab(\"" + Messages.getBodyJavascriptString(locale,"LivelinkConnector.DocumentView") + "\");\n"+ " editconnection.viewprotocol.focus();\n"+ " return false;\n"+ " }\n"+ " if (editconnection.viewcgipath.value == \"\" && editconnection.ingestcgipath.value == \"\")\n"+ " {\n"+ " alert(\""+Messages.getBodyJavascriptString(locale,"LivelinkConnector.EnterTheViewCgiPathToLivelink")+"\");\n"+ " SelectTab(\"" + Messages.getBodyJavascriptString(locale,"LivelinkConnector.DocumentView") + "\");\n"+ " editconnection.viewcgipath.focus();\n"+ " return false;\n"+ " }\n"+ " if (editconnection.ingestcgipath.value != \"\" && editconnection.ingestcgipath.value.substring(0,1) != \"/\")\n"+ " {\n"+ " alert(\""+Messages.getBodyJavascriptString(locale,"LivelinkConnector.TheIngestCgiPathMustBeBlankOrBeginWithACharacter")+"\");\n"+ " SelectTab(\"" + Messages.getBodyJavascriptString(locale,"LivelinkConnector.DocumentAccess") + "\");\n"+ " editconnection.ingestcgipath.focus();\n"+ " return false;\n"+ " }\n"+ " if (editconnection.viewcgipath.value != \"\" && editconnection.viewcgipath.value.substring(0,1) != \"/\")\n"+ " {\n"+ " alert(\""+Messages.getBodyJavascriptString(locale,"LivelinkConnector.TheViewCgiPathMustBeBlankOrBeginWithACharacter")+"\");\n"+ " SelectTab(\"" + Messages.getBodyJavascriptString(locale,"LivelinkConnector.DocumentView") + "\");\n"+ " editconnection.viewcgipath.focus();\n"+ " return false;\n"+ " }\n"+ " return true;\n"+ "}\n"+ "\n"+ "//-->\n"+ "</script>\n" ); } /** Output the configuration body section. * This method is called in the body section of the connector's configuration page. Its purpose is to present the required form elements for editing. * The coder can presume that the HTML that is output from this configuration will be within appropriate <html>, <body>, and <form> tags. The name of the * form is "editconnection". *@param threadContext is the local thread context. *@param out is the output to which any HTML should be sent. *@param parameters are the configuration parameters, as they currently exist, for this connection being configured. *@param tabName is the current tab name. */ @Override public void outputConfigurationBody(IThreadContext threadContext, IHTTPOutput out, Locale locale, ConfigParams parameters, String tabName) throws ManifoldCFException, IOException { // LAPI parameters String serverProtocol = parameters.getParameter(LiveLinkParameters.serverProtocol); if (serverProtocol == null) serverProtocol = "internal"; String serverName = parameters.getParameter(LiveLinkParameters.serverName); if (serverName == null) serverName = "localhost"; String serverPort = parameters.getParameter(LiveLinkParameters.serverPort); if (serverPort == null) serverPort = "2099"; String serverUserName = parameters.getParameter(LiveLinkParameters.serverUsername); if (serverUserName == null) serverUserName = ""; String serverPassword = parameters.getObfuscatedParameter(LiveLinkParameters.serverPassword); if (serverPassword == null) serverPassword = ""; else serverPassword = out.mapPasswordToKey(serverPassword); String serverHTTPCgiPath = parameters.getParameter(LiveLinkParameters.serverHTTPCgiPath); if (serverHTTPCgiPath == null) serverHTTPCgiPath = "/livelink/livelink.exe"; String serverHTTPNTLMDomain = parameters.getParameter(LiveLinkParameters.serverHTTPNTLMDomain); if (serverHTTPNTLMDomain == null) serverHTTPNTLMDomain = ""; String serverHTTPNTLMUserName = parameters.getParameter(LiveLinkParameters.serverHTTPNTLMUsername); if (serverHTTPNTLMUserName == null) serverHTTPNTLMUserName = ""; String serverHTTPNTLMPassword = parameters.getObfuscatedParameter(LiveLinkParameters.serverHTTPNTLMPassword); if (serverHTTPNTLMPassword == null) serverHTTPNTLMPassword = ""; else serverHTTPNTLMPassword = out.mapPasswordToKey(serverHTTPNTLMPassword); String serverHTTPSKeystore = parameters.getParameter(LiveLinkParameters.serverHTTPSKeystore); IKeystoreManager localServerHTTPSKeystore; if (serverHTTPSKeystore == null) localServerHTTPSKeystore = KeystoreManagerFactory.make(""); else localServerHTTPSKeystore = KeystoreManagerFactory.make("",serverHTTPSKeystore); // Document access parameters String ingestProtocol = parameters.getParameter(LiveLinkParameters.ingestProtocol); if (ingestProtocol == null) ingestProtocol = ""; String ingestPort = parameters.getParameter(LiveLinkParameters.ingestPort); if (ingestPort == null) ingestPort = ""; String ingestCgiPath = parameters.getParameter(LiveLinkParameters.ingestCgiPath); if (ingestCgiPath == null) ingestCgiPath = ""; String ingestNtlmUsername = parameters.getParameter(LiveLinkParameters.ingestNtlmUsername); if (ingestNtlmUsername == null) ingestNtlmUsername = ""; String ingestNtlmPassword = parameters.getObfuscatedParameter(LiveLinkParameters.ingestNtlmPassword); if (ingestNtlmPassword == null) ingestNtlmPassword = ""; else ingestNtlmPassword = out.mapPasswordToKey(ingestNtlmPassword); String ingestNtlmDomain = parameters.getParameter(LiveLinkParameters.ingestNtlmDomain); if (ingestNtlmDomain == null) ingestNtlmDomain = ""; String ingestKeystore = parameters.getParameter(LiveLinkParameters.ingestKeystore); IKeystoreManager localIngestKeystore; if (ingestKeystore == null) localIngestKeystore = KeystoreManagerFactory.make(""); else localIngestKeystore = KeystoreManagerFactory.make("",ingestKeystore); // Document view parameters String viewProtocol = parameters.getParameter(LiveLinkParameters.viewProtocol); if (viewProtocol == null) viewProtocol = "http"; String viewServerName = parameters.getParameter(LiveLinkParameters.viewServerName); if (viewServerName == null) viewServerName = ""; String viewPort = parameters.getParameter(LiveLinkParameters.viewPort); if (viewPort == null) viewPort = ""; String viewCgiPath = parameters.getParameter(LiveLinkParameters.viewCgiPath); if (viewCgiPath == null) viewCgiPath = "/livelink/livelink.exe"; // The "Server" tab // Always pass the whole keystore as a hidden. out.print( "<input name=\"serverconfigop\" type=\"hidden\" value=\"Continue\"/>\n" ); if (serverHTTPSKeystore != null) { out.print( "<input type=\"hidden\" name=\"serverhttpskeystoredata\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(serverHTTPSKeystore)+"\"/>\n" ); } if (tabName.equals(Messages.getString(locale,"LivelinkConnector.Server"))) { out.print( "<table class=\"displaytable\">\n"+ " <tr><td class=\"separator\" colspan=\"2\"><hr/></td></tr>\n"+ " <tr>\n"+ " <td class=\"description\">"+Messages.getBodyString(locale,"LivelinkConnector.ServerProtocol")+"</td>\n"+ " <td class=\"value\">\n"+ " <select name=\"serverprotocol\" size=\"2\">\n"+ " <option value=\"internal\" "+((serverProtocol.equals("internal"))?"selected=\"selected\"":"")+">"+Messages.getBodyString(locale,"LivelinkConnector.internal")+"</option>\n"+ " <option value=\"http\" "+((serverProtocol.equals("http"))?"selected=\"selected\"":"")+">http</option>\n"+ " <option value=\"https\" "+((serverProtocol.equals("https"))?"selected=\"selected\"":"")+">https</option>\n"+ " </select>\n"+ " </td>\n"+ " </tr>\n"+ " <tr>\n"+ " <td class=\"description\"><nobr>"+Messages.getBodyString(locale,"LivelinkConnector.ServerName")+"</nobr></td>\n"+ " <td class=\"value\"><input type=\"text\" size=\"64\" name=\"servername\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(serverName)+"\"/></td>\n"+ " </tr>\n"+ " <tr>\n"+ " <td class=\"description\"><nobr>"+Messages.getBodyString(locale,"LivelinkConnector.ServerPort")+"</nobr></td>\n"+ " <td class=\"value\"><input type=\"text\" size=\"5\" name=\"serverport\" value=\""+serverPort+"\"/></td>\n"+ " </tr>\n"+ " <tr>\n"+ " <td class=\"description\"><nobr>"+Messages.getBodyString(locale,"LivelinkConnector.ServerUserName")+"</nobr></td>\n"+ " <td class=\"value\"><input type=\"text\" size=\"32\" name=\"serverusername\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(serverUserName)+"\"/></td>\n"+ " </tr>\n"+ " <tr>\n"+ " <td class=\"description\"><nobr>"+Messages.getBodyString(locale,"LivelinkConnector.ServerPassword")+"</nobr></td>\n"+ " <td class=\"value\"><input type=\"password\" size=\"32\" name=\"serverpassword\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(serverPassword)+"\"/></td>\n"+ " </tr>\n"+ " <tr><td class=\"separator\" colspan=\"2\"><hr/></td></tr>\n"+ " <tr>\n"+ " <td class=\"description\"><nobr>"+Messages.getBodyString(locale,"LivelinkConnector.ServerHTTPCGIPath")+"</nobr></td>\n"+ " <td class=\"value\"><input type=\"text\" size=\"32\" name=\"serverhttpcgipath\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(serverHTTPCgiPath)+"\"/></td>\n"+ " </tr>\n"+ " <tr>\n"+ " <td class=\"description\"><nobr>"+Messages.getBodyString(locale,"LivelinkConnector.ServerHTTPNTLMDomain")+"</nobr><br/><nobr>"+Messages.getBodyString(locale,"LivelinkConnector.SetIfNTLMAuthDesired")+"</nobr></td>\n"+ " <td class=\"value\">\n"+ " <input type=\"text\" size=\"32\" name=\"serverhttpntlmdomain\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(serverHTTPNTLMDomain)+"\"/>\n"+ " </td>\n"+ " </tr>\n"+ " <tr>\n"+ " <td class=\"description\"><nobr>"+Messages.getBodyString(locale,"LivelinkConnector.ServerHTTPNTLMUserName")+"</nobr></td>\n"+ " <td class=\"value\">\n"+ " <input type=\"text\" size=\"32\" name=\"serverhttpntlmusername\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(serverHTTPNTLMUserName)+"\"/>\n"+ " </td>\n"+ " </tr>\n"+ " <tr>\n"+ " <td class=\"description\"><nobr>"+Messages.getBodyString(locale,"LivelinkConnector.ServerHTTPNTLMPassword")+"</nobr></td>\n"+ " <td class=\"value\">\n"+ " <input type=\"password\" size=\"32\" name=\"serverhttpntlmpassword\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(serverHTTPNTLMPassword)+"\"/>\n"+ " </td>\n"+ " </tr>\n"+ " <tr><td class=\"separator\" colspan=\"2\"><hr/></td></tr>\n" ); out.print( " <tr>\n"+ " <td class=\"description\"><nobr>"+Messages.getBodyString(locale,"LivelinkConnector.ServerSSLCertificateList")+"</nobr></td>\n"+ " <td class=\"value\">\n"+ " <input type=\"hidden\" name=\"serverkeystorealias\" value=\"\"/>\n"+ " <table class=\"displaytable\">\n" ); // List the individual certificates in the store, with a delete button for each String[] contents = localServerHTTPSKeystore.getContents(); if (contents.length == 0) { out.print( " <tr><td class=\"message\" colspan=\"2\"><nobr>"+Messages.getBodyString(locale,"LivelinkConnector.NoCertificatesPresent")+"</nobr></td></tr>\n" ); } else { int i = 0; while (i < contents.length) { String alias = contents[i]; String description = localServerHTTPSKeystore.getDescription(alias); if (description.length() > 128) description = description.substring(0,125) + "..."; out.print( " <tr>\n"+ " <td class=\"value\"><input type=\"button\" onclick='Javascript:ServerDeleteCertificate(\""+org.apache.manifoldcf.ui.util.Encoder.attributeJavascriptEscape(alias)+"\")' alt=\""+Messages.getAttributeString(locale,"LivelinkConnector.DeleteCert")+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(alias)+"\" value=\""+Messages.getAttributeString(locale,"LivelinkConnector.Delete")+"\"/></td>\n"+ " <td>"+org.apache.manifoldcf.ui.util.Encoder.bodyEscape(description)+"</td>\n"+ " </tr>\n" ); i++; } } out.print( " </table>\n"+ " <input type=\"button\" onclick='Javascript:ServerAddCertificate()' alt=\""+Messages.getAttributeString(locale,"LivelinkConnector.AddCert")+"\" value=\""+Messages.getAttributeString(locale,"LivelinkConnector.Add")+"\"/>&nbsp;\n"+ " "+Messages.getBodyString(locale,"LivelinkConnector.Certificate")+"<input name=\"servercertificate\" size=\"50\" type=\"file\"/>\n"+ " </td>\n"+ " </tr>\n" ); out.print( "</table>\n" ); } else { // Hiddens for Server tab out.print( "<input type=\"hidden\" name=\"serverprotocol\" value=\""+serverProtocol+"\"/>\n"+ "<input type=\"hidden\" name=\"servername\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(serverName)+"\"/>\n"+ "<input type=\"hidden\" name=\"serverport\" value=\""+serverPort+"\"/>\n"+ "<input type=\"hidden\" name=\"serverusername\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(serverUserName)+"\"/>\n"+ "<input type=\"hidden\" name=\"serverpassword\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(serverPassword)+"\"/>\n"+ "<input type=\"hidden\" name=\"serverhttpcgipath\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(serverHTTPCgiPath)+"\"/>\n"+ "<input type=\"hidden\" name=\"serverhttpntlmdomain\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(serverHTTPNTLMDomain)+"\"/>\n"+ "<input type=\"hidden\" name=\"serverhttpntlmusername\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(serverHTTPNTLMUserName)+"\"/>\n"+ "<input type=\"hidden\" name=\"serverhttpntlmpassword\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(serverHTTPNTLMPassword)+"\"/>\n" ); } // The "Document Access" tab // Always pass the whole keystore as a hidden. out.print( "<input name=\"ingestconfigop\" type=\"hidden\" value=\"Continue\"/>\n" ); if (ingestKeystore != null) { out.print( "<input type=\"hidden\" name=\"ingestkeystoredata\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(ingestKeystore)+"\"/>\n" ); } if (tabName.equals(Messages.getString(locale,"LivelinkConnector.DocumentAccess"))) { out.print( "<table class=\"displaytable\">\n"+ " <tr><td class=\"separator\" colspan=\"2\"><hr/></td></tr>\n"+ " <tr>\n"+ " <td class=\"description\">"+Messages.getBodyString(locale,"LivelinkConnector.DocumentFetchProtocol")+"</td>\n"+ " <td class=\"value\">\n"+ " <select name=\"ingestprotocol\" size=\"3\">\n"+ " <option value=\"\" "+((ingestProtocol.equals(""))?"selected=\"selected\"":"")+">"+Messages.getBodyString(locale,"LivelinkConnector.UseLAPI")+"</option>\n"+ " <option value=\"http\" "+((ingestProtocol.equals("http"))?"selected=\"selected\"":"")+">http</option>\n"+ " <option value=\"https\" "+((ingestProtocol.equals("https"))?"selected=\"selected\"":"")+">https</option>\n"+ " </select>\n"+ " </td>\n"+ " </tr>\n"+ " <tr>\n"+ " <td class=\"description\"><nobr>"+Messages.getBodyString(locale,"LivelinkConnector.DocumentFetchPort")+"</nobr></td>\n"+ " <td class=\"value\"><input type=\"text\" size=\"5\" name=\"ingestport\" value=\""+ingestPort+"\"/></td>\n"+ " </tr>\n"+ " <tr><td class=\"separator\" colspan=\"2\"><hr/></td></tr>\n"+ " <tr>\n"+ " <td class=\"description\"><nobr>"+Messages.getBodyString(locale,"LivelinkConnector.DocumentFetchCGIPath")+"</nobr></td>\n"+ " <td class=\"value\"><input type=\"text\" size=\"32\" name=\"ingestcgipath\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(ingestCgiPath)+"\"/></td>\n"+ " </tr>\n"+ " <tr>\n"+ " <td class=\"description\"><nobr>"+Messages.getBodyString(locale,"LivelinkConnector.DocumentFetchNTLMDomain")+"</nobr><br/><nobr>"+Messages.getBodyString(locale,"LivelinkConnector.SetIfNTLMAuthDesired")+"</nobr></td>\n"+ " <td class=\"value\">\n"+ " <input type=\"text\" size=\"32\" name=\"ingestntlmdomain\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(ingestNtlmDomain)+"\"/>\n"+ " </td>\n"+ " </tr>\n"+ " <tr>\n"+ " <td class=\"description\"><nobr>"+Messages.getBodyString(locale,"LivelinkConnector.DocumentFetchNTLMUserName")+"</nobr><br/><nobr>"+Messages.getBodyString(locale,"LivelinkConnector.SetIfDifferentFromServerUserName")+"</nobr></td>\n"+ " <td class=\"value\">\n"+ " <input type=\"text\" size=\"32\" name=\"ingestntlmusername\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(ingestNtlmUsername)+"\"/>\n"+ " </td>\n"+ " </tr>\n"+ " <tr>\n"+ " <td class=\"description\"><nobr>"+Messages.getBodyString(locale,"LivelinkConnector.DocumentFetchNTLMPassword")+"</nobr><br/><nobr>"+Messages.getBodyString(locale,"LivelinkConnector.SetIfDifferentFromServerPassword")+"</nobr></td>\n"+ " <td class=\"value\">\n"+ " <input type=\"password\" size=\"32\" name=\"ingestntlmpassword\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(ingestNtlmPassword)+"\"/>\n"+ " </td>\n"+ " </tr>\n"+ " <tr><td class=\"separator\" colspan=\"2\"><hr/></td></tr>\n" ); out.print( " <tr>\n"+ " <td class=\"description\"><nobr>"+Messages.getBodyString(locale,"LivelinkConnector.DocumentFetchSSLCertificateList")+"</nobr></td>\n"+ " <td class=\"value\">\n"+ " <input type=\"hidden\" name=\"ingestkeystorealias\" value=\"\"/>\n"+ " <table class=\"displaytable\">\n" ); // List the individual certificates in the store, with a delete button for each String[] contents = localIngestKeystore.getContents(); if (contents.length == 0) { out.print( " <tr><td class=\"message\" colspan=\"2\"><nobr>"+Messages.getBodyString(locale,"LivelinkConnector.NoCertificatesPresent")+"</nobr></td></tr>\n" ); } else { int i = 0; while (i < contents.length) { String alias = contents[i]; String description = localIngestKeystore.getDescription(alias); if (description.length() > 128) description = description.substring(0,125) + "..."; out.print( " <tr>\n"+ " <td class=\"value\"><input type=\"button\" onclick='Javascript:IngestDeleteCertificate(\""+org.apache.manifoldcf.ui.util.Encoder.attributeJavascriptEscape(alias)+"\")' alt=\""+Messages.getAttributeString(locale,"LivelinkConnector.DeleteCert")+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(alias)+"\" value=\""+Messages.getAttributeString(locale,"LivelinkConnector.Delete")+"\"/></td>\n"+ " <td>"+org.apache.manifoldcf.ui.util.Encoder.bodyEscape(description)+"</td>\n"+ " </tr>\n" ); i++; } } out.print( " </table>\n"+ " <input type=\"button\" onclick='Javascript:IngestAddCertificate()' alt=\""+Messages.getAttributeString(locale,"LivelinkConnector.AddCert")+"\" value=\""+Messages.getAttributeString(locale,"LivelinkConnector.Add")+"\"/>&nbsp;\n"+ " "+Messages.getBodyString(locale,"LivelinkConnector.Certificate")+"<input name=\"ingestcertificate\" size=\"50\" type=\"file\"/>\n"+ " </td>\n"+ " </tr>\n" ); out.print( "</table>\n" ); } else { // Hiddens for Document Access tab out.print( "<input type=\"hidden\" name=\"ingestprotocol\" value=\""+ingestProtocol+"\"/>\n"+ "<input type=\"hidden\" name=\"ingestport\" value=\""+ingestPort+"\"/>\n"+ "<input type=\"hidden\" name=\"ingestcgipath\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(ingestCgiPath)+"\"/>\n"+ "<input type=\"hidden\" name=\"ingestntlmusername\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(ingestNtlmUsername)+"\"/>\n"+ "<input type=\"hidden\" name=\"ingestntlmpassword\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(ingestNtlmPassword)+"\"/>\n"+ "<input type=\"hidden\" name=\"ingestntlmdomain\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(ingestNtlmDomain)+"\"/>\n" ); } // Document View tab if (tabName.equals(Messages.getString(locale,"LivelinkConnector.DocumentView"))) { out.print( "<table class=\"displaytable\">\n"+ " <tr><td class=\"separator\" colspan=\"2\"><hr/></td></tr>\n"+ " <tr>\n"+ " <td class=\"description\">"+Messages.getBodyString(locale,"LivelinkConnector.DocumentViewProtocol")+"</td>\n"+ " <td class=\"value\">\n"+ " <select name=\"viewprotocol\" size=\"3\">\n"+ " <option value=\"\" "+((viewProtocol.equals(""))?"selected=\"selected\"":"")+">"+Messages.getBodyString(locale,"LivelinkConnector.SameAsFetchProtocol")+"</option>\n"+ " <option value=\"http\" "+((viewProtocol.equals("http"))?"selected=\"selected\"":"")+">http</option>\n"+ " <option value=\"https\" "+((viewProtocol.equals("https"))?"selected=\"selected\"":"")+">https</option>\n"+ " </select>\n"+ " </td>\n"+ " </tr>\n"+ " <tr>\n"+ " <td class=\"description\"><nobr>"+Messages.getBodyString(locale,"LivelinkConnector.DocumentViewServerName")+"</nobr><br/><nobr>"+Messages.getBodyString(locale,"LivelinkConnector.BlankSameAsFetchServer")+"</nobr></td>\n"+ " <td class=\"value\"><input type=\"text\" size=\"64\" name=\"viewservername\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(viewServerName)+"\"/></td>\n"+ " </tr>\n"+ " <tr>\n"+ " <td class=\"description\"><nobr>"+Messages.getBodyString(locale,"LivelinkConnector.DocumentViewPort")+"</nobr><br/><nobr>(blank = same as fetch port)</nobr></td>\n"+ " <td class=\"value\"><input type=\"text\" size=\"5\" name=\"viewport\" value=\""+viewPort+"\"/></td>\n"+ " </tr>\n"+ " <tr>\n"+ " <td class=\"description\"><nobr>"+Messages.getBodyString(locale,"LivelinkConnector.DocumentViewCGIPath")+"</nobr><br/><nobr>"+Messages.getBodyString(locale,"LivelinkConnector.BlankSameAsFetchServer")+"</nobr></td>\n"+ " <td class=\"value\"><input type=\"text\" size=\"32\" name=\"viewcgipath\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(viewCgiPath)+"\"/></td>\n"+ " </tr>\n"+ "</table>\n" ); } else { // Hiddens for Document View tab out.print( "<input type=\"hidden\" name=\"viewprotocol\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(viewProtocol)+"\"/>\n"+ "<input type=\"hidden\" name=\"viewservername\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(viewServerName)+"\"/>\n"+ "<input type=\"hidden\" name=\"viewport\" value=\""+viewPort+"\"/>\n"+ "<input type=\"hidden\" name=\"viewcgipath\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(viewCgiPath)+"\"/>\n" ); } } /** Process a configuration post. * This method is called at the start of the connector's configuration page, whenever there is a possibility that form data for a connection has been * posted. Its purpose is to gather form information and modify the configuration parameters accordingly. * The name of the posted form is "editconnection". *@param threadContext is the local thread context. *@param variableContext is the set of variables available from the post, including binary file post information. *@param parameters are the configuration parameters, as they currently exist, for this connection being configured. *@return null if all is well, or a string error message if there is an error that should prevent saving of the connection (and cause a redirection to an error page). */ @Override public String processConfigurationPost(IThreadContext threadContext, IPostParameters variableContext, Locale locale, ConfigParams parameters) throws ManifoldCFException { // View parameters String viewProtocol = variableContext.getParameter("viewprotocol"); if (viewProtocol != null) parameters.setParameter(LiveLinkParameters.viewProtocol,viewProtocol); String viewServerName = variableContext.getParameter("viewservername"); if (viewServerName != null) parameters.setParameter(LiveLinkParameters.viewServerName,viewServerName); String viewPort = variableContext.getParameter("viewport"); if (viewPort != null) parameters.setParameter(LiveLinkParameters.viewPort,viewPort); String viewCgiPath = variableContext.getParameter("viewcgipath"); if (viewCgiPath != null) parameters.setParameter(LiveLinkParameters.viewCgiPath,viewCgiPath); // Server parameters String serverProtocol = variableContext.getParameter("serverprotocol"); if (serverProtocol != null) parameters.setParameter(LiveLinkParameters.serverProtocol,serverProtocol); String serverName = variableContext.getParameter("servername"); if (serverName != null) parameters.setParameter(LiveLinkParameters.serverName,serverName); String serverPort = variableContext.getParameter("serverport"); if (serverPort != null) parameters.setParameter(LiveLinkParameters.serverPort,serverPort); String serverUserName = variableContext.getParameter("serverusername"); if (serverUserName != null) parameters.setParameter(LiveLinkParameters.serverUsername,serverUserName); String serverPassword = variableContext.getParameter("serverpassword"); if (serverPassword != null) parameters.setObfuscatedParameter(LiveLinkParameters.serverPassword,variableContext.mapKeyToPassword(serverPassword)); String serverHTTPCgiPath = variableContext.getParameter("serverhttpcgipath"); if (serverHTTPCgiPath != null) parameters.setParameter(LiveLinkParameters.serverHTTPCgiPath,serverHTTPCgiPath); String serverHTTPNTLMDomain = variableContext.getParameter("serverhttpntlmdomain"); if (serverHTTPNTLMDomain != null) parameters.setParameter(LiveLinkParameters.serverHTTPNTLMDomain,serverHTTPNTLMDomain); String serverHTTPNTLMUserName = variableContext.getParameter("serverhttpntlmusername"); if (serverHTTPNTLMUserName != null) parameters.setParameter(LiveLinkParameters.serverHTTPNTLMUsername,serverHTTPNTLMUserName); String serverHTTPNTLMPassword = variableContext.getParameter("serverhttpntlmpassword"); if (serverHTTPNTLMPassword != null) parameters.setObfuscatedParameter(LiveLinkParameters.serverHTTPNTLMPassword,variableContext.mapKeyToPassword(serverHTTPNTLMPassword)); String serverHTTPSKeystoreValue = variableContext.getParameter("serverhttpskeystoredata"); if (serverHTTPSKeystoreValue != null) parameters.setParameter(LiveLinkParameters.serverHTTPSKeystore,serverHTTPSKeystoreValue); String serverConfigOp = variableContext.getParameter("serverconfigop"); if (serverConfigOp != null) { if (serverConfigOp.equals("Delete")) { String alias = variableContext.getParameter("serverkeystorealias"); serverHTTPSKeystoreValue = parameters.getParameter(LiveLinkParameters.serverHTTPSKeystore); IKeystoreManager mgr; if (serverHTTPSKeystoreValue != null) mgr = KeystoreManagerFactory.make("",serverHTTPSKeystoreValue); else mgr = KeystoreManagerFactory.make(""); mgr.remove(alias); parameters.setParameter(LiveLinkParameters.serverHTTPSKeystore,mgr.getString()); } else if (serverConfigOp.equals("Add")) { String alias = IDFactory.make(threadContext); byte[] certificateValue = variableContext.getBinaryBytes("servercertificate"); serverHTTPSKeystoreValue = parameters.getParameter(LiveLinkParameters.serverHTTPSKeystore); IKeystoreManager mgr; if (serverHTTPSKeystoreValue != null) mgr = KeystoreManagerFactory.make("",serverHTTPSKeystoreValue); else mgr = KeystoreManagerFactory.make(""); java.io.InputStream is = new java.io.ByteArrayInputStream(certificateValue); String certError = null; try { mgr.importCertificate(alias,is); } catch (Throwable e) { certError = e.getMessage(); } finally { try { is.close(); } catch (IOException e) { // Eat this exception } } if (certError != null) { return "Illegal certificate: "+certError; } parameters.setParameter(LiveLinkParameters.serverHTTPSKeystore,mgr.getString()); } } // Ingest parameters String ingestProtocol = variableContext.getParameter("ingestprotocol"); if (ingestProtocol != null) parameters.setParameter(LiveLinkParameters.ingestProtocol,ingestProtocol); String ingestPort = variableContext.getParameter("ingestport"); if (ingestPort != null) parameters.setParameter(LiveLinkParameters.ingestPort,ingestPort); String ingestCgiPath = variableContext.getParameter("ingestcgipath"); if (ingestCgiPath != null) parameters.setParameter(LiveLinkParameters.ingestCgiPath,ingestCgiPath); String ingestNtlmDomain = variableContext.getParameter("ingestntlmdomain"); if (ingestNtlmDomain != null) parameters.setParameter(LiveLinkParameters.ingestNtlmDomain,ingestNtlmDomain); String ingestNtlmUsername = variableContext.getParameter("ingestntlmusername"); if (ingestNtlmUsername != null) parameters.setParameter(LiveLinkParameters.ingestNtlmUsername,ingestNtlmUsername); String ingestNtlmPassword = variableContext.getParameter("ingestntlmpassword"); if (ingestNtlmPassword != null) parameters.setObfuscatedParameter(LiveLinkParameters.ingestNtlmPassword,variableContext.mapKeyToPassword(ingestNtlmPassword)); String ingestKeystoreValue = variableContext.getParameter("ingestkeystoredata"); if (ingestKeystoreValue != null) parameters.setParameter(LiveLinkParameters.ingestKeystore,ingestKeystoreValue); String ingestConfigOp = variableContext.getParameter("ingestconfigop"); if (ingestConfigOp != null) { if (ingestConfigOp.equals("Delete")) { String alias = variableContext.getParameter("ingestkeystorealias"); ingestKeystoreValue = parameters.getParameter(LiveLinkParameters.ingestKeystore); IKeystoreManager mgr; if (ingestKeystoreValue != null) mgr = KeystoreManagerFactory.make("",ingestKeystoreValue); else mgr = KeystoreManagerFactory.make(""); mgr.remove(alias); parameters.setParameter(LiveLinkParameters.ingestKeystore,mgr.getString()); } else if (ingestConfigOp.equals("Add")) { String alias = IDFactory.make(threadContext); byte[] certificateValue = variableContext.getBinaryBytes("ingestcertificate"); ingestKeystoreValue = parameters.getParameter(LiveLinkParameters.ingestKeystore); IKeystoreManager mgr; if (ingestKeystoreValue != null) mgr = KeystoreManagerFactory.make("",ingestKeystoreValue); else mgr = KeystoreManagerFactory.make(""); java.io.InputStream is = new java.io.ByteArrayInputStream(certificateValue); String certError = null; try { mgr.importCertificate(alias,is); } catch (Throwable e) { certError = e.getMessage(); } finally { try { is.close(); } catch (IOException e) { // Eat this exception } } if (certError != null) { return "Illegal certificate: "+certError; } parameters.setParameter(LiveLinkParameters.ingestKeystore,mgr.getString()); } } return null; } /** View configuration. * This method is called in the body section of the connector's view configuration page. Its purpose is to present the connection information to the user. * The coder can presume that the HTML that is output from this configuration will be within appropriate <html> and <body> tags. *@param threadContext is the local thread context. *@param out is the output to which any HTML should be sent. *@param parameters are the configuration parameters, as they currently exist, for this connection being configured. */ @Override public void viewConfiguration(IThreadContext threadContext, IHTTPOutput out, Locale locale, ConfigParams parameters) throws ManifoldCFException, IOException { out.print( "<table class=\"displaytable\">\n"+ " <tr>\n"+ " <td class=\"description\" colspan=\"1\"><nobr>"+Messages.getBodyString(locale,"LivelinkConnector.Parameters")+"</nobr></td>\n"+ " <td class=\"value\" colspan=\"3\">\n" ); Iterator iter = parameters.listParameters(); while (iter.hasNext()) { String param = (String)iter.next(); String value = parameters.getParameter(param); if (param.length() >= "password".length() && param.substring(param.length()-"password".length()).equalsIgnoreCase("password")) { out.print( " <nobr>"+org.apache.manifoldcf.ui.util.Encoder.bodyEscape(param)+"=********</nobr><br/>\n" ); } else if (param.length() >="keystore".length() && param.substring(param.length()-"keystore".length()).equalsIgnoreCase("keystore") || param.length() > "truststore".length() && param.substring(param.length()-"truststore".length()).equalsIgnoreCase("truststore")) { IKeystoreManager kmanager = KeystoreManagerFactory.make("",value); out.print( " <nobr>"+org.apache.manifoldcf.ui.util.Encoder.bodyEscape(param)+"=&lt;"+Integer.toString(kmanager.getContents().length)+Messages.getBodyString(locale,"LivelinkConnector.certificates")+"&gt;</nobr><br/>\n" ); } else { out.print( " <nobr>"+org.apache.manifoldcf.ui.util.Encoder.bodyEscape(param)+"="+org.apache.manifoldcf.ui.util.Encoder.bodyEscape(value)+"</nobr><br/>\n" ); } } out.print( " </td>\n"+ " </tr>\n"+ "</table>\n" ); } /** Output the specification header section. * This method is called in the head section of a job page which has selected a repository connection of the * current type. Its purpose is to add the required tabs to the list, and to output any javascript methods * that might be needed by the job editing HTML. * The connector will be connected before this method can be called. *@param out is the output to which any HTML should be sent. *@param locale is the locale the output is preferred to be in. *@param ds is the current document specification for this job. *@param connectionSequenceNumber is the unique number of this connection within the job. *@param tabsArray is an array of tab names. Add to this array any tab names that are specific to the connector. */ @Override public void outputSpecificationHeader(IHTTPOutput out, Locale locale, Specification ds, int connectionSequenceNumber, List<String> tabsArray) throws ManifoldCFException, IOException { tabsArray.add(Messages.getString(locale,"LivelinkConnector.Paths")); tabsArray.add(Messages.getString(locale,"LivelinkConnector.Filters")); tabsArray.add(Messages.getString(locale,"LivelinkConnector.Security")); tabsArray.add(Messages.getString(locale,"LivelinkConnector.Metadata")); String seqPrefix = "s"+connectionSequenceNumber+"_"; out.print( "<script type=\"text/javascript\">\n"+ "<!--\n"+ "\n"+ "function "+seqPrefix+"SpecOp(n, opValue, anchorvalue)\n"+ "{\n"+ " eval(\"editjob.\"+n+\".value = \\\"\"+opValue+\"\\\"\");\n"+ " postFormSetAnchor(anchorvalue);\n"+ "}\n"+ "\n"+ "function "+seqPrefix+"SpecAddToPath(anchorvalue)\n"+ "{\n"+ " if (editjob."+seqPrefix+"pathaddon.value == \"\")\n"+ " {\n"+ " alert(\""+Messages.getBodyJavascriptString(locale,"LivelinkConnector.SelectAFolderFirst")+"\");\n"+ " editjob."+seqPrefix+"pathaddon.focus();\n"+ " return;\n"+ " }\n"+ "\n"+ " "+seqPrefix+"SpecOp(\""+seqPrefix+"pathop\",\"AddToPath\",anchorvalue);\n"+ "}\n"+ "\n"+ "function "+seqPrefix+"SpecAddFilespec(anchorvalue)\n"+ "{\n"+ " if (editjob."+seqPrefix+"specfile.value == \"\")\n"+ " {\n"+ " alert(\""+Messages.getBodyJavascriptString(locale,"LivelinkConnector.TypeInAFileSpecification")+"\");\n"+ " editjob."+seqPrefix+"specfile.focus();\n"+ " return;\n"+ " }\n"+ " "+seqPrefix+"SpecOp(\""+seqPrefix+"fileop\",\"Add\",anchorvalue);\n"+ "}\n"+ "\n"+ "function "+seqPrefix+"SpecAddToken(anchorvalue)\n"+ "{\n"+ " if (editjob."+seqPrefix+"spectoken.value == \"\")\n"+ " {\n"+ " alert(\""+Messages.getBodyJavascriptString(locale,"LivelinkConnector.TypeInAnAccessToken")+"\");\n"+ " editjob."+seqPrefix+"spectoken.focus();\n"+ " return;\n"+ " }\n"+ " "+seqPrefix+"SpecOp(\""+seqPrefix+"accessop\",\"Add\",anchorvalue);\n"+ "}\n"+ "\n"+ "function "+seqPrefix+"SpecAddToMetadata(anchorvalue)\n"+ "{\n"+ " if (editjob."+seqPrefix+"metadataaddon.value == \"\")\n"+ " {\n"+ " alert(\""+Messages.getBodyJavascriptString(locale,"LivelinkConnector.SelectAFolderFirst")+"\");\n"+ " editjob."+seqPrefix+"metadataaddon.focus();\n"+ " return;\n"+ " }\n"+ " "+seqPrefix+"SpecOp(\""+seqPrefix+"metadataop\",\"AddToPath\",anchorvalue);\n"+ "}\n"+ "\n"+ "function "+seqPrefix+"SpecSetWorkspace(anchorvalue)\n"+ "{\n"+ " if (editjob."+seqPrefix+"metadataaddon.value == \"\")\n"+ " {\n"+ " alert(\""+Messages.getBodyJavascriptString(locale,"LivelinkConnector.SelectAWorkspaceFirst")+"\");\n"+ " editjob."+seqPrefix+"metadataaddon.focus();\n"+ " return;\n"+ " }\n"+ " "+seqPrefix+"SpecOp(\""+seqPrefix+"metadataop\",\"SetWorkspace\",anchorvalue);\n"+ "}\n"+ "\n"+ "function "+seqPrefix+"SpecAddCategory(anchorvalue)\n"+ "{\n"+ " if (editjob."+seqPrefix+"categoryaddon.value == \"\")\n"+ " {\n"+ " alert(\""+Messages.getBodyJavascriptString(locale,"LivelinkConnector.SelectACategoryFirst")+"\");\n"+ " editjob."+seqPrefix+"categoryaddon.focus();\n"+ " return;\n"+ " }\n"+ " "+seqPrefix+"SpecOp(\""+seqPrefix+"metadataop\",\"AddCategory\",anchorvalue);\n"+ "}\n"+ "\n"+ "function "+seqPrefix+"SpecAddMetadata(anchorvalue)\n"+ "{\n"+ " if (editjob."+seqPrefix+"attributeselect.value == \"\" && editjob."+seqPrefix+"attributeall.value == \"\")\n"+ " {\n"+ " alert(\""+Messages.getBodyJavascriptString(locale,"LivelinkConnector.SelectAtLeastOneAttributeFirst")+"\");\n"+ " editjob."+seqPrefix+"attributeselect.focus();\n"+ " return;\n"+ " }\n"+ " "+seqPrefix+"SpecOp(\""+seqPrefix+"metadataop\",\"Add\",anchorvalue);\n"+ "}\n"+ "\n"+ "function "+seqPrefix+"SpecAddMapping(anchorvalue)\n"+ "{\n"+ " if (editjob."+seqPrefix+"specmatch.value == \"\")\n"+ " {\n"+ " alert(\""+Messages.getBodyJavascriptString(locale,"LivelinkConnector.MatchStringCannotBeEmpty")+"\");\n"+ " editjob."+seqPrefix+"specmatch.focus();\n"+ " return;\n"+ " }\n"+ " if (!isRegularExpression(editjob."+seqPrefix+"specmatch.value))\n"+ " {\n"+ " alert(\""+Messages.getBodyJavascriptString(locale,"LivelinkConnector.MatchStringMustBeValidRegularExpression")+"\");\n"+ " editjob."+seqPrefix+"specmatch.focus();\n"+ " return;\n"+ " }\n"+ " "+seqPrefix+"SpecOp(\""+seqPrefix+"specmappingop\",\"Add\",anchorvalue);\n"+ "}\n"+ "//-->\n"+ "</script>\n" ); } /** Output the specification body section. * This method is called in the body section of a job page which has selected a repository connection of the * current type. Its purpose is to present the required form elements for editing. * The coder can presume that the HTML that is output from this configuration will be within appropriate * <html>, <body>, and <form> tags. The name of the form is always "editjob". * The connector will be connected before this method can be called. *@param out is the output to which any HTML should be sent. *@param locale is the locale the output is preferred to be in. *@param ds is the current document specification for this job. *@param connectionSequenceNumber is the unique number of this connection within the job. *@param actualSequenceNumber is the connection within the job that has currently been selected. *@param tabName is the current tab name. (actualSequenceNumber, tabName) form a unique tuple within * the job. */ @Override public void outputSpecificationBody(IHTTPOutput out, Locale locale, Specification ds, int connectionSequenceNumber, int actualSequenceNumber, String tabName) throws ManifoldCFException, IOException { String seqPrefix = "s"+connectionSequenceNumber+"_"; int i; int k; // Paths tab boolean userWorkspaces = false; i = 0; while (i < ds.getChildCount()) { SpecificationNode sn = ds.getChild(i++); if (sn.getType().equals("userworkspace")) { String value = sn.getAttributeValue("value"); if (value != null && value.equals("true")) userWorkspaces = true; } } if (tabName.equals(Messages.getString(locale,"LivelinkConnector.Paths")) && connectionSequenceNumber == actualSequenceNumber) { out.print( "<table class=\"displaytable\">\n"+ " <tr><td class=\"separator\" colspan=\"2\"><hr/></td></tr>\n"+ " <tr>\n"+ " <td class=\"description\">\n"+ " <nobr>"+Messages.getBodyString(locale,"LivelinkConnector.CrawlUserWorkspaces")+"</nobr>\n"+ " </td>\n"+ " <td class=\"value\">\n"+ " <input type=\"checkbox\" name=\""+seqPrefix+"userworkspace\" value=\"true\""+(userWorkspaces?" checked=\"true\"":"")+"/>\n"+ " <input type=\"hidden\" name=\""+seqPrefix+"userworkspace_present\" value=\"true\"/>\n"+ " </td>\n"+ " </tr>\n"+ " <tr><td class=\"separator\" colspan=\"2\"><hr/></td></tr>\n" ); // Now, loop through paths i = 0; k = 0; while (i < ds.getChildCount()) { SpecificationNode sn = ds.getChild(i++); if (sn.getType().equals("startpoint")) { String pathDescription = "_"+Integer.toString(k); String pathOpName = seqPrefix+"pathop"+pathDescription; out.print( " <tr>\n"+ " <td class=\"description\">\n"+ " <input type=\"hidden\" name=\""+seqPrefix+"specpath"+pathDescription+"\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(sn.getAttributeValue("path"))+"\"/>\n"+ " <input type=\"hidden\" name=\""+pathOpName+"\" value=\"\"/>\n"+ " <a name=\""+seqPrefix+"path_"+Integer.toString(k)+"\">\n"+ " <input type=\"button\" value=\"Delete\" onClick='Javascript:"+seqPrefix+"SpecOp(\""+pathOpName+"\",\"Delete\",\""+seqPrefix+"path_"+Integer.toString(k)+"\")' alt=\""+Messages.getAttributeString(locale,"LivelinkConnector.DeletePath")+Integer.toString(k)+"\"/>\n"+ " </a>\n"+ " </td>\n"+ " <td class=\"value\">\n"+ " "+((sn.getAttributeValue("path").length() == 0)?"(root)":org.apache.manifoldcf.ui.util.Encoder.bodyEscape(sn.getAttributeValue("path")))+"\n"+ " </td>\n"+ " </tr>\n" ); k++; } } if (k == 0) { out.print( " <tr>\n"+ " <td class=\"message\" colspan=\"2\">"+Messages.getBodyString(locale,"LivelinkConnector.NoStartingPointsDefined")+"</td>\n"+ " </tr>\n" ); } out.print( " <tr><td class=\"lightseparator\" colspan=\"2\"><hr/></td></tr>\n"+ " <tr>\n"+ " <td class=\"description\">\n"+ " <input type=\"hidden\" name=\""+seqPrefix+"pathcount\" value=\""+Integer.toString(k)+"\"/>\n" ); String pathSoFar = (String)currentContext.get(seqPrefix+"specpath"); if (pathSoFar == null) pathSoFar = ""; // Grab next folder/project list try { String[] childList; childList = getChildFolderNames(pathSoFar); if (childList == null) { // Illegal path - set it back pathSoFar = ""; childList = getChildFolderNames(""); if (childList == null) throw new ManifoldCFException("Can't find any children for root folder"); } out.print( " <input type=\"hidden\" name=\""+seqPrefix+"specpath\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(pathSoFar)+"\"/>\n"+ " <input type=\"hidden\" name=\""+seqPrefix+"pathop\" value=\"\"/>\n"+ " <a name=\""+seqPrefix+"path_"+Integer.toString(k)+"\">\n"+ " <input type=\"button\" value=\"Add\" onClick='Javascript:"+seqPrefix+"SpecOp(\""+seqPrefix+"pathop\",\"Add\",\""+seqPrefix+"path_"+Integer.toString(k+1)+"\")' alt=\""+Messages.getAttributeString(locale,"LivelinkConnector.AddPath")+"\"/>\n"+ " </a>&nbsp;\n"+ " </td>\n"+ " <td class=\"value\">\n"+ " "+((pathSoFar.length()==0)?"(root)":org.apache.manifoldcf.ui.util.Encoder.bodyEscape(pathSoFar))+"\n" ); if (pathSoFar.length() > 0) { out.print( " <input type=\"button\" value=\"-\" onClick='Javascript:"+seqPrefix+"SpecOp(\""+seqPrefix+"pathop\",\"Up\",\""+seqPrefix+"path_"+Integer.toString(k)+"\")' alt=\"Back up path\"/>\n" ); } if (childList.length > 0) { out.print( " <input type=\"button\" value=\"+\" onClick='Javascript:"+seqPrefix+"SpecAddToPath(\""+seqPrefix+"path_"+Integer.toString(k)+"\")' alt=\""+Messages.getAttributeString(locale,"LivelinkConnector.AddToPath")+"\"/>&nbsp;\n"+ " <select multiple=\"false\" name=\""+seqPrefix+"pathaddon\" size=\"2\">\n"+ " <option value=\"\" selected=\"selected\">"+Messages.getBodyString(locale,"LivelinkConnector.PickAFolder")+"</option>\n" ); int j = 0; while (j < childList.length) { out.print( " <option value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(childList[j])+"\">"+org.apache.manifoldcf.ui.util.Encoder.bodyEscape(childList[j])+"</option>\n" ); j++; } out.print( " </select>\n" ); } } catch (ServiceInterruption e) { //e.printStackTrace(); out.println(org.apache.manifoldcf.ui.util.Encoder.bodyEscape(e.getMessage())); } catch (ManifoldCFException e) { //e.printStackTrace(); out.println(org.apache.manifoldcf.ui.util.Encoder.bodyEscape(e.getMessage())); } out.print( " </td>\n"+ " </tr>\n"+ "</table>\n" ); } else { // Now, loop through paths i = 0; k = 0; while (i < ds.getChildCount()) { SpecificationNode sn = ds.getChild(i++); if (sn.getType().equals("startpoint")) { String pathDescription = "_"+Integer.toString(k); out.print( "<input type=\"hidden\" name=\""+seqPrefix+"specpath"+pathDescription+"\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(sn.getAttributeValue("path"))+"\"/>\n" ); k++; } } out.print( "<input type=\"hidden\" name=\""+seqPrefix+"pathcount\" value=\""+Integer.toString(k)+"\"/>\n"+ "<input type=\"hidden\" name=\""+seqPrefix+"userworkspace\" value=\""+(userWorkspaces?"true":"false")+"\"/>\n"+ "<input type=\"hidden\" name=\""+seqPrefix+"userworkspace_present\" value=\"true\"/>\n" ); } // Filter tab if (tabName.equals(Messages.getString(locale,"LivelinkConnector.Filters")) && connectionSequenceNumber == actualSequenceNumber) { out.print( "<table class=\"displaytable\">\n"+ " <tr><td class=\"separator\" colspan=\"2\"><hr/></td></tr>\n" ); // Next, go through include/exclude filespecs i = 0; k = 0; while (i < ds.getChildCount()) { SpecificationNode sn = ds.getChild(i++); if (sn.getType().equals("include") || sn.getType().equals("exclude")) { String fileSpecDescription = "_"+Integer.toString(k); String fileOpName = seqPrefix+"fileop"+fileSpecDescription; String filespec = sn.getAttributeValue("filespec"); out.print( " <tr>\n"+ " <td class=\"description\">\n"+ " <input type=\"hidden\" name=\""+seqPrefix+"specfiletype"+fileSpecDescription+"\" value=\""+sn.getType()+"\"/>\n"+ " <input type=\"hidden\" name=\""+fileOpName+"\" value=\"\"/>\n"+ " <a name=\""+seqPrefix+"filespec_"+Integer.toString(k)+"\">\n"+ " <input type=\"button\" value=\"Delete\" onClick='Javascript:"+seqPrefix+"SpecOp(\""+fileOpName+"\",\"Delete\",\""+seqPrefix+"filespec_"+Integer.toString(k)+"\")' alt=\""+Messages.getAttributeString(locale,"LivelinkConnector.DeleteFilespec")+Integer.toString(k)+"\"/>\n"+ " </a>\n"+ " </td>\n"+ " <td class=\"value\">\n"+ " "+(sn.getType().equals("include")?"Include:":"")+"\n"+ " "+(sn.getType().equals("exclude")?"Exclude:":"")+"\n"+ " &nbsp;<input type=\"hidden\" name=\""+seqPrefix+"specfile"+fileSpecDescription+"\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(filespec)+"\"/>\n"+ " "+org.apache.manifoldcf.ui.util.Encoder.bodyEscape(filespec)+"\n"+ " </td>\n"+ " </tr>\n" ); k++; } } if (k == 0) { out.print( " <tr>\n"+ " <td class=\"message\" colspan=\"2\">"+Messages.getBodyString(locale,"LivelinkConnector.NoIncludeExcludeFilesDefined")+"</td>\n"+ " </tr>\n" ); } out.print( " <tr><td class=\"lightseparator\" colspan=\"2\"><hr/></td></tr>\n"+ " <tr>\n"+ " <td class=\"description\">\n"+ " <input type=\"hidden\" name=\""+seqPrefix+"filecount\" value=\""+Integer.toString(k)+"\"/>\n"+ " <input type=\"hidden\" name=\""+seqPrefix+"fileop\" value=\"\"/>\n"+ " <a name=\""+seqPrefix+"filespec_"+Integer.toString(k)+"\">\n"+ " <input type=\"button\" value=\"Add\" onClick='Javascript:"+seqPrefix+"SpecAddFilespec(\""+seqPrefix+"filespec_"+Integer.toString(k+1)+"\")' alt=\""+Messages.getAttributeString(locale,"LivelinkConnector.AddFileSpecification")+"\"/>\n"+ " </a>&nbsp;\n"+ " </td>\n"+ " <td class=\"value\">\n"+ " <select name=\""+seqPrefix+"specfiletype\" size=\"1\">\n"+ " <option value=\"include\" selected=\"selected\">"+Messages.getBodyString(locale,"LivelinkConnector.Include")+"</option>\n"+ " <option value=\"exclude\">"+Messages.getBodyString(locale,"LivelinkConnector.Exclude")+"</option>\n"+ " </select>&nbsp;\n"+ " <input type=\"text\" size=\"30\" name=\""+seqPrefix+"specfile\" value=\"\"/>\n"+ " </td>\n"+ " </tr>\n"+ "</table>\n" ); } else { // Next, go through include/exclude filespecs i = 0; k = 0; while (i < ds.getChildCount()) { SpecificationNode sn = ds.getChild(i++); if (sn.getType().equals("include") || sn.getType().equals("exclude")) { String fileSpecDescription = "_"+Integer.toString(k); String filespec = sn.getAttributeValue("filespec"); out.print( "<input type=\"hidden\" name=\""+seqPrefix+"specfiletype"+fileSpecDescription+"\" value=\""+sn.getType()+"\"/>\n"+ "<input type=\"hidden\" name=\""+seqPrefix+"specfile"+fileSpecDescription+"\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(filespec)+"\"/>\n" ); k++; } } out.print( "<input type=\"hidden\" name=\""+seqPrefix+"filecount\" value=\""+Integer.toString(k)+"\"/>\n" ); } // Security tab // Find whether security is on or off i = 0; boolean securityOn = true; while (i < ds.getChildCount()) { SpecificationNode sn = ds.getChild(i++); if (sn.getType().equals("security")) { String securityValue = sn.getAttributeValue("value"); if (securityValue.equals("off")) securityOn = false; else if (securityValue.equals("on")) securityOn = true; } } if (tabName.equals(Messages.getString(locale,"LivelinkConnector.Security")) && connectionSequenceNumber == actualSequenceNumber) { out.print( "<table class=\"displaytable\">\n"+ " <tr><td class=\"separator\" colspan=\"2\"><hr/></td></tr>\n"+ " <tr>\n"+ " <td class=\"description\"><nobr>"+Messages.getBodyString(locale,"LivelinkConnector.SecurityColon")+"</nobr></td>\n"+ " <td class=\"value\">\n"+ " <input type=\"radio\" name=\""+seqPrefix+"specsecurity\" value=\"on\" "+(securityOn?"checked=\"true\"":"")+" />"+Messages.getBodyString(locale,"LivelinkConnector.Enabled")+"\n"+ " <input type=\"radio\" name=\""+seqPrefix+"specsecurity\" value=\"off\" "+((securityOn==false)?"checked=\"true\"":"")+" />"+Messages.getBodyString(locale,"LivelinkConnector.Disabled")+"\n"+ " </td>\n"+ " </tr>\n"+ " <tr><td class=\"separator\" colspan=\"2\"><hr/></td></tr>\n" ); // Go through forced ACL i = 0; k = 0; while (i < ds.getChildCount()) { SpecificationNode sn = ds.getChild(i++); if (sn.getType().equals("access")) { String accessDescription = "_"+Integer.toString(k); String accessOpName = seqPrefix+"accessop"+accessDescription; String token = sn.getAttributeValue("token"); out.print( " <tr>\n"+ " <td class=\"description\">\n"+ " <input type=\"hidden\" name=\""+accessOpName+"\" value=\"\"/>\n"+ " <input type=\"hidden\" name=\""+seqPrefix+"spectoken"+accessDescription+"\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(token)+"\"/>\n"+ " <a name=\""+seqPrefix+"token_"+Integer.toString(k)+"\">\n"+ " <input type=\"button\" value=\"Delete\" onClick='Javascript:"+seqPrefix+"SpecOp(\""+accessOpName+"\",\"Delete\",\""+seqPrefix+"token_"+Integer.toString(k)+"\")' alt=\""+Messages.getAttributeString(locale,"LivelinkConnector.DeleteToken")+Integer.toString(k)+"\"/>\n"+ " </a>&nbsp;\n"+ " </td>\n"+ " <td class=\"value\">\n"+ " "+org.apache.manifoldcf.ui.util.Encoder.bodyEscape(token)+"\n"+ " </td>\n"+ " </tr>\n" ); k++; } } if (k == 0) { out.print( " <tr>\n"+ " <td class=\"message\" colspan=\"2\">" + Messages.getBodyString(locale,"LivelinkConnector.NoAccessTokensPresent") + "</td>\n"+ " </tr>\n" ); } out.print( " <tr><td class=\"lightseparator\" colspan=\"2\"><hr/></td></tr>\n"+ " <tr>\n"+ " <td class=\"description\">\n"+ " <input type=\"hidden\" name=\""+seqPrefix+"tokencount\" value=\""+Integer.toString(k)+"\"/>\n"+ " <input type=\"hidden\" name=\""+seqPrefix+"accessop\" value=\"\"/>\n"+ " <a name=\""+seqPrefix+"token_"+Integer.toString(k)+"\">\n"+ " <input type=\"button\" value=\"Add\" onClick='Javascript:"+seqPrefix+"SpecAddToken(\""+seqPrefix+"token_"+Integer.toString(k+1)+"\")' alt=\""+Messages.getAttributeString(locale,"LivelinkConnector.AddAccessToken")+"\"/>\n"+ " </a>&nbsp;\n"+ " </td>\n"+ " <td class=\"value\">\n"+ " <input type=\"text\" size=\"30\" name=\""+seqPrefix+"spectoken\" value=\"\"/>\n"+ " </td>\n"+ " </tr>\n"+ "</table>\n" ); } else { out.print( "<input type=\"hidden\" name=\""+seqPrefix+"specsecurity\" value=\""+(securityOn?"on":"off")+"\"/>\n" ); // Finally, go through forced ACL i = 0; k = 0; while (i < ds.getChildCount()) { SpecificationNode sn = ds.getChild(i++); if (sn.getType().equals("access")) { String accessDescription = "_"+Integer.toString(k); String token = sn.getAttributeValue("token"); out.print( "<input type=\"hidden\" name=\""+seqPrefix+"spectoken"+accessDescription+"\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(token)+"\"/>\n" ); k++; } } out.print( "<input type=\"hidden\" name=\""+seqPrefix+"tokencount\" value=\""+Integer.toString(k)+"\"/>\n" ); } // Metadata tab // Find the path-value metadata attribute name i = 0; String pathNameAttribute = ""; String pathNameSeparator = "/"; while (i < ds.getChildCount()) { SpecificationNode sn = ds.getChild(i++); if (sn.getType().equals("pathnameattribute")) { pathNameAttribute = sn.getAttributeValue("value"); if (sn.getAttributeValue("separator") != null) pathNameSeparator = sn.getAttributeValue("separator"); } } // Find the path-value mapping data i = 0; MatchMap matchMap = new MatchMap(); while (i < ds.getChildCount()) { SpecificationNode sn = ds.getChild(i++); if (sn.getType().equals("pathmap")) { String pathMatch = sn.getAttributeValue("match"); String pathReplace = sn.getAttributeValue("replace"); matchMap.appendMatchPair(pathMatch,pathReplace); } } i = 0; String ingestAllMetadata = "false"; while (i < ds.getChildCount()) { SpecificationNode sn = ds.getChild(i++); if (sn.getType().equals("allmetadata")) { ingestAllMetadata = sn.getAttributeValue("all"); if (ingestAllMetadata == null) ingestAllMetadata = "false"; } } if (tabName.equals(Messages.getString(locale,"LivelinkConnector.Metadata")) && connectionSequenceNumber == actualSequenceNumber) { out.print( "<input type=\"hidden\" name=\""+seqPrefix+"specmappingcount\" value=\""+Integer.toString(matchMap.getMatchCount())+"\"/>\n"+ "<input type=\"hidden\" name=\""+seqPrefix+"specmappingop\" value=\"\"/>\n"+ "\n"+ "<table class=\"displaytable\">\n"+ " <tr><td class=\"separator\" colspan=\"4\"><hr/></td></tr>\n"+ " <tr>\n"+ " <td class=\"description\" colspan=\"1\"><nobr>"+Messages.getBodyString(locale,"LivelinkConnector.IngestALLMetadata")+"</nobr></td>\n"+ " <td class=\"value\" colspan=\"3\">\n"+ " <nobr><input type=\"radio\" name=\""+seqPrefix+"specallmetadata\" value=\"true\" "+(ingestAllMetadata.equals("true")?"checked=\"true\"":"")+"/>"+Messages.getBodyString(locale,"LivelinkConnector.Yes")+"</nobr>&nbsp;\n"+ " <nobr><input type=\"radio\" name=\""+seqPrefix+"specallmetadata\" value=\"false\" "+(ingestAllMetadata.equals("false")?"checked=\"true\"":"")+"/>"+Messages.getBodyString(locale,"LivelinkConnector.No")+"</nobr>\n"+ " </td>\n"+ " </tr>\n"+ " <tr><td class=\"separator\" colspan=\"4\"><hr/></td></tr>\n" ); // Go through the selected metadata attributes i = 0; k = 0; while (i < ds.getChildCount()) { SpecificationNode sn = ds.getChild(i++); if (sn.getType().equals("metadata")) { String accessDescription = "_"+Integer.toString(k); String accessOpName = seqPrefix+"metadataop"+accessDescription; String categoryPath = sn.getAttributeValue("category"); String isAll = sn.getAttributeValue("all"); if (isAll == null) isAll = "false"; String attributeName = sn.getAttributeValue("attribute"); if (attributeName == null) attributeName = ""; out.print( " <tr>\n"+ " <td class=\"description\" colspan=\"1\">\n"+ " <input type=\"hidden\" name=\""+accessOpName+"\" value=\"\"/>\n"+ " <input type=\"hidden\" name=\""+seqPrefix+"speccategory"+accessDescription+"\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(categoryPath)+"\"/>\n"+ " <input type=\"hidden\" name=\""+seqPrefix+"specattributeall"+accessDescription+"\" value=\""+isAll+"\"/>\n"+ " <input type=\"hidden\" name=\""+seqPrefix+"specattribute"+accessDescription+"\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(attributeName)+"\"/>\n"+ " <a name=\""+seqPrefix+"metadata_"+Integer.toString(k)+"\">\n"+ " <input type=\"button\" value=\"Delete\" onClick='Javascript:"+seqPrefix+"SpecOp(\""+accessOpName+"\",\"Delete\",\""+seqPrefix+"metadata_"+Integer.toString(k)+"\")' alt=\""+Messages.getAttributeString(locale,"LivelinkConnector.DeleteMetadata")+Integer.toString(k)+"\"/>\n"+ " </a>&nbsp;\n"+ " </td>\n"+ " <td class=\"value\" colspan=\"3\">\n"+ " "+org.apache.manifoldcf.ui.util.Encoder.bodyEscape(categoryPath)+":"+((isAll!=null&&isAll.equals("true"))?"(All metadata attributes)":org.apache.manifoldcf.ui.util.Encoder.bodyEscape(attributeName))+"\n"+ " </td>\n"+ " </tr>\n" ); k++; } } if (k == 0) { out.print( " <tr>\n"+ " <td class=\"message\" colspan=\"4\">"+Messages.getBodyString(locale,"LivelinkConnector.NoMetadataSpecified")+"</td>\n"+ " </tr>\n" ); } out.print( " <tr><td class=\"lightseparator\" colspan=\"4\"><hr/></td></tr>\n"+ " <tr>\n"+ " <td class=\"description\" colspan=\"1\">\n"+ " <a name=\""+seqPrefix+"metadata_"+Integer.toString(k)+"\"></a>\n"+ " <input type=\"hidden\" name=\""+seqPrefix+"metadatacount\" value=\""+Integer.toString(k)+"\"/>\n" ); String categorySoFar = (String)currentContext.get(seqPrefix+"speccategory"); if (categorySoFar == null) categorySoFar = ""; // Grab next folder/project list, and the appropriate category list try { String[] childList = null; String[] workspaceList = null; String[] categoryList = null; String[] attributeList = null; if (categorySoFar.length() == 0) { workspaceList = getWorkspaceNames(); } else { attributeList = getCategoryAttributes(categorySoFar); if (attributeList == null) { childList = getChildFolderNames(categorySoFar); if (childList == null) { // Illegal path - set it back categorySoFar = ""; childList = getChildFolderNames(""); if (childList == null) throw new ManifoldCFException("Can't find any children for root folder"); } categoryList = getChildCategoryNames(categorySoFar); if (categoryList == null) throw new ManifoldCFException("Can't find any categories for root folder folder"); } } out.print( " <input type=\"hidden\" name=\""+seqPrefix+"speccategory\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(categorySoFar)+"\"/>\n"+ " <input type=\"hidden\" name=\""+seqPrefix+"metadataop\" value=\"\"/>\n" ); if (attributeList != null) { // We have a valid category! out.print( " <input type=\"button\" value=\"Add\" onClick='Javascript:"+seqPrefix+"SpecAddMetadata(\""+seqPrefix+"metadata_"+Integer.toString(k+1)+"\")' alt=\""+Messages.getAttributeString(locale,"LivelinkConnector.AddMetadataItem")+"\"/>&nbsp;\n"+ " </td>\n"+ " <td class=\"value\" colspan=\"3\">\n"+ " "+org.apache.manifoldcf.ui.util.Encoder.bodyEscape(categorySoFar)+":<input type=\"button\" value=\"-\" onClick='Javascript:"+seqPrefix+"SpecOp(\""+seqPrefix+"metadataop\",\"Up\",\""+seqPrefix+"metadata_"+Integer.toString(k)+"\")' alt=\""+Messages.getAttributeString(locale,"LivelinkConnector.BackUpMetadataPath")+"\"/>&nbsp;\n"+ " <table class=\"displaytable\">\n"+ " <tr>\n"+ " <td class=\"value\">\n"+ " <input type=\"checkbox\" name=\""+seqPrefix+"attributeall\" value=\"true\"/>"+Messages.getBodyString(locale,"LivelinkConnector.AllAttributesInThisCategory")+"<br/>\n"+ " <select multiple=\"true\" name=\""+seqPrefix+"attributeselect\" size=\"2\">\n"+ " <option value=\"\" selected=\"selected\">"+Messages.getBodyString(locale,"LivelinkConnector.PickAttributes")+"</option>\n" ); int l = 0; while (l < attributeList.length) { String attributeName = attributeList[l++]; out.print( " <option value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(attributeName)+"\">"+org.apache.manifoldcf.ui.util.Encoder.bodyEscape(attributeName)+"</option>\n" ); } out.print( " </select>\n"+ " </td>\n"+ " </tr>\n"+ " </table>\n" ); } else if (workspaceList != null) { out.print( " </td>\n"+ " <td class=\"value\" colspan=\"3\">\n"+ " <input type=\"button\" value=\"+\" onClick='Javascript:"+seqPrefix+"SpecSetWorkspace(\""+seqPrefix+"metadata_"+Integer.toString(k)+"\")' alt=\""+Messages.getAttributeString(locale,"LivelinkConnector.AddToMetadataPath")+"\"/>&nbsp;\n"+ " <select multiple=\"false\" name=\""+seqPrefix+"metadataaddon\" size=\"2\">\n"+ " <option value=\"\" selected=\"selected\">"+Messages.getBodyString(locale,"LivelinkConnector.PickWorkspace")+"</option>\n" ); int j = 0; while (j < workspaceList.length) { out.print( " <option value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(workspaceList[j])+"\">"+org.apache.manifoldcf.ui.util.Encoder.bodyEscape(workspaceList[j])+"</option>\n" ); j++; } out.print( " </select>\n" ); } else { out.print( " </td>\n"+ " <td class=\"value\" colspan=\"3\">\n"+ " "+((categorySoFar.length()==0)?"(root)":org.apache.manifoldcf.ui.util.Encoder.bodyEscape(categorySoFar))+"&nbsp;\n" ); if (categorySoFar.length() > 0) { out.print( " <input type=\"button\" value=\"-\" onClick='Javascript:"+seqPrefix+"SpecOp(\""+seqPrefix+"metadataop\",\"Up\",\""+seqPrefix+"metadata_"+Integer.toString(k)+"\")' alt=\""+Messages.getAttributeString(locale,"LivelinkConnector.BackUpMetadataPath")+"\"/>&nbsp;\n" ); } if (childList.length > 0) { out.print( " <input type=\"button\" value=\"+\" onClick='Javascript:"+seqPrefix+"SpecAddToMetadata(\""+seqPrefix+"metadata_"+Integer.toString(k)+"\")' alt=\""+Messages.getAttributeString(locale,"LivelinkConnector.AddToMetadataPath")+"\"/>&nbsp;\n"+ " <select multiple=\"false\" name=\""+seqPrefix+"metadataaddon\" size=\"2\">\n"+ " <option value=\"\" selected=\"selected\">"+Messages.getBodyString(locale,"LivelinkConnector.PickAFolder")+"</option>\n" ); int j = 0; while (j < childList.length) { out.print( " <option value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(childList[j])+"\">"+org.apache.manifoldcf.ui.util.Encoder.bodyEscape(childList[j])+"</option>\n" ); j++; } out.print( " </select>\n" ); } if (categoryList.length > 0) { out.print( " <input type=\"button\" value=\"+\" onClick='Javascript:"+seqPrefix+"SpecAddCategory(\""+seqPrefix+"metadata_"+Integer.toString(k)+"\")' alt=\""+Messages.getAttributeString(locale,"LivelinkConnector.AddCategory")+"\"/>&nbsp;\n"+ " <select multiple=\"false\" name=\""+seqPrefix+"categoryaddon\" size=\"2\">\n"+ " <option value=\"\" selected=\"selected\">"+Messages.getBodyString(locale,"LivelinkConnector.PickACategory")+"</option>\n" ); int j = 0; while (j < categoryList.length) { out.print( " <option value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(categoryList[j])+"\">"+org.apache.manifoldcf.ui.util.Encoder.bodyEscape(categoryList[j])+"</option>\n" ); j++; } out.print( " </select>\n" ); } } } catch (ServiceInterruption e) { //e.printStackTrace(); out.println(org.apache.manifoldcf.ui.util.Encoder.bodyEscape(e.getMessage())); } catch (ManifoldCFException e) { //e.printStackTrace(); out.println(org.apache.manifoldcf.ui.util.Encoder.bodyEscape(e.getMessage())); } out.print( " </td>\n"+ " </tr>\n"+ " <tr><td class=\"separator\" colspan=\"4\"><hr/></td></tr>\n"+ " <tr>\n"+ " <td class=\"description\" colspan=\"1\"><nobr>"+Messages.getBodyString(locale,"LivelinkConnector.PathAttributeName")+"</nobr></td>\n"+ " <td class=\"value\" colspan=\"1\">\n"+ " <input type=\"text\" name=\""+seqPrefix+"specpathnameattribute\" size=\"20\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(pathNameAttribute)+"\"/>\n"+ " </td>\n"+ " <td class=\"description\" colspan=\"1\"><nobr>"+Messages.getBodyString(locale,"LivelinkConnector.PathSeparatorString")+"</nobr></td>\n"+ " <td class=\"value\" colspan=\"1\">\n"+ " <input type=\"text\" name=\""+seqPrefix+"specpathnameseparator\" size=\"20\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(pathNameSeparator)+"\"/>\n"+ " </td>\n"+ " </tr>\n"+ " <tr><td class=\"separator\" colspan=\"4\"><hr/></td></tr>\n" ); i = 0; while (i < matchMap.getMatchCount()) { String matchString = matchMap.getMatchString(i); String replaceString = matchMap.getReplaceString(i); out.print( " <tr>\n"+ " <td class=\"description\">\n"+ " <input type=\"hidden\" name=\""+seqPrefix+"specmappingop_"+Integer.toString(i)+"\" value=\"\"/>\n"+ " <a name=\""+seqPrefix+"mapping_"+Integer.toString(i)+"\">\n"+ " <input type=\"button\" onClick='Javascript:"+seqPrefix+"SpecOp(\""+seqPrefix+"specmappingop_"+Integer.toString(i)+"\",\"Delete\",\""+seqPrefix+"mapping_"+Integer.toString(i)+"\")' alt=\""+Messages.getAttributeString(locale,"LivelinkConnector.DeleteMapping")+Integer.toString(i)+"\" value=\"Delete\"/>\n"+ " </a>\n"+ " </td>\n"+ " <td class=\"value\">\n"+ " <input type=\"hidden\" name=\""+seqPrefix+"specmatch_"+Integer.toString(i)+"\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(matchString)+"\"/>"+org.apache.manifoldcf.ui.util.Encoder.bodyEscape(matchString)+"\n"+ " </td>\n"+ " <td class=\"value\">==></td>\n"+ " <td class=\"value\">\n"+ " <input type=\"hidden\" name=\""+seqPrefix+"specreplace_"+Integer.toString(i)+"\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(replaceString)+"\"/>"+org.apache.manifoldcf.ui.util.Encoder.bodyEscape(replaceString)+"\n"+ " </td>\n"+ " </tr>\n" ); i++; } if (i == 0) { out.print( " <tr><td colspan=\"4\" class=\"message\">"+Messages.getBodyString(locale,"LivelinkConnector.NoMappingsSpecified")+"</td></tr>\n" ); } out.print( " <tr><td class=\"lightseparator\" colspan=\"4\"><hr/></td></tr>\n"+ " <tr>\n"+ " <td class=\"description\">\n"+ " <a name=\""+seqPrefix+"mapping_"+Integer.toString(i)+"\">\n"+ " <input type=\"button\" onClick='Javascript:"+seqPrefix+"SpecAddMapping(\""+seqPrefix+"mapping_"+Integer.toString(i+1)+"\")' alt=\""+Messages.getAttributeString(locale,"LivelinkConnector.AddToMappings")+"\" value=\"Add\"/>\n"+ " </a>\n"+ " </td>\n"+ " <td class=\"value\">Match regexp:&nbsp;<input type=\"text\" name=\""+seqPrefix+"specmatch\" size=\"32\" value=\"\"/></td>\n"+ " <td class=\"value\">==></td>\n"+ " <td class=\"value\">Replace string:&nbsp;<input type=\"text\" name=\""+seqPrefix+"specreplace\" size=\"32\" value=\"\"/></td>\n"+ " </tr>\n"+ "</table>\n" ); } else { out.print( "<input type=\"hidden\" name=\""+seqPrefix+"specallmetadata\" value=\""+ingestAllMetadata+"\"/>\n" ); // Go through the selected metadata attributes i = 0; k = 0; while (i < ds.getChildCount()) { SpecificationNode sn = ds.getChild(i++); if (sn.getType().equals("metadata")) { String accessDescription = "_"+Integer.toString(k); String categoryPath = sn.getAttributeValue("category"); String isAll = sn.getAttributeValue("all"); if (isAll == null) isAll = "false"; String attributeName = sn.getAttributeValue("attribute"); if (attributeName == null) attributeName = ""; out.print( "<input type=\"hidden\" name=\""+seqPrefix+"speccategory"+accessDescription+"\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(categoryPath)+"\"/>\n"+ "<input type=\"hidden\" name=\""+seqPrefix+"specattributeall"+accessDescription+"\" value=\""+isAll+"\"/>\n"+ "<input type=\"hidden\" name=\""+seqPrefix+"specattribute"+accessDescription+"\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(attributeName)+"\"/>\n" ); k++; } } out.print( "<input type=\"hidden\" name=\""+seqPrefix+"metadatacount\" value=\""+Integer.toString(k)+"\"/>\n"+ "<input type=\"hidden\" name=\""+seqPrefix+"specpathnameattribute\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(pathNameAttribute)+"\"/>\n"+ "<input type=\"hidden\" name=\""+seqPrefix+"specpathnameseparator\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(pathNameSeparator)+"\"/>\n"+ "<input type=\"hidden\" name=\""+seqPrefix+"specmappingcount\" value=\""+Integer.toString(matchMap.getMatchCount())+"\"/>\n" ); i = 0; while (i < matchMap.getMatchCount()) { String matchString = matchMap.getMatchString(i); String replaceString = matchMap.getReplaceString(i); out.print( "<input type=\"hidden\" name=\""+seqPrefix+"specmatch_"+Integer.toString(i)+"\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(matchString)+"\"/>\n"+ "<input type=\"hidden\" name=\""+seqPrefix+"specreplace_"+Integer.toString(i)+"\" value=\""+org.apache.manifoldcf.ui.util.Encoder.attributeEscape(replaceString)+"\"/>\n" ); i++; } } } /** Process a specification post. * This method is called at the start of job's edit or view page, whenever there is a possibility that form * data for a connection has been posted. Its purpose is to gather form information and modify the * document specification accordingly. The name of the posted form is always "editjob". * The connector will be connected before this method can be called. *@param variableContext contains the post data, including binary file-upload information. *@param locale is the locale the output is preferred to be in. *@param ds is the current document specification for this job. *@param connectionSequenceNumber is the unique number of this connection within the job. *@return null if all is well, or a string error message if there is an error that should prevent saving of * the job (and cause a redirection to an error page). */ @Override public String processSpecificationPost(IPostParameters variableContext, Locale locale, Specification ds, int connectionSequenceNumber) throws ManifoldCFException { String seqPrefix = "s"+connectionSequenceNumber+"_"; String userWorkspacesPresent = variableContext.getParameter(seqPrefix+"userworkspace_present"); if (userWorkspacesPresent != null) { String value = variableContext.getParameter(seqPrefix+"userworkspace"); int i = 0; while (i < ds.getChildCount()) { SpecificationNode sn = ds.getChild(i); if (sn.getType().equals("userworkspace")) ds.removeChild(i); else i++; } SpecificationNode sn = new SpecificationNode("userworkspace"); sn.setAttribute("value",value); ds.addChild(ds.getChildCount(),sn); } String xc = variableContext.getParameter(seqPrefix+"pathcount"); if (xc != null) { // Delete all path specs first int i = 0; while (i < ds.getChildCount()) { SpecificationNode sn = ds.getChild(i); if (sn.getType().equals("startpoint")) ds.removeChild(i); else i++; } // Find out how many children were sent int pathCount = Integer.parseInt(xc); // Gather up these i = 0; while (i < pathCount) { String pathDescription = "_"+Integer.toString(i); String pathOpName = seqPrefix+"pathop"+pathDescription; xc = variableContext.getParameter(pathOpName); if (xc != null && xc.equals("Delete")) { // Skip to the next i++; continue; } // Path inserts won't happen until the very end String path = variableContext.getParameter(seqPrefix+"specpath"+pathDescription); SpecificationNode node = new SpecificationNode("startpoint"); node.setAttribute("path",path); ds.addChild(ds.getChildCount(),node); i++; } // See if there's a global add operation String op = variableContext.getParameter(seqPrefix+"pathop"); if (op != null && op.equals("Add")) { String path = variableContext.getParameter("specpath"); SpecificationNode node = new SpecificationNode("startpoint"); node.setAttribute("path",path); ds.addChild(ds.getChildCount(),node); } else if (op != null && op.equals("Up")) { // Strip off end String path = variableContext.getParameter(seqPrefix+"specpath"); int lastSlash = -1; int k = 0; while (k < path.length()) { char x = path.charAt(k++); if (x == '/') { lastSlash = k-1; continue; } if (x == '\\') k++; } if (lastSlash == -1) path = ""; else path = path.substring(0,lastSlash); currentContext.save(seqPrefix+"specpath",path); } else if (op != null && op.equals("AddToPath")) { String path = variableContext.getParameter(seqPrefix+"specpath"); String addon = variableContext.getParameter(seqPrefix+"pathaddon"); if (addon != null && addon.length() > 0) { StringBuilder sb = new StringBuilder(); int k = 0; while (k < addon.length()) { char x = addon.charAt(k++); if (x == '/' || x == '\\' || x == ':') sb.append('\\'); sb.append(x); } if (path.length() == 0) path = sb.toString(); else path += "/" + sb.toString(); } currentContext.save(seqPrefix+"specpath",path); } } xc = variableContext.getParameter(seqPrefix+"filecount"); if (xc != null) { // Delete all file specs first int i = 0; while (i < ds.getChildCount()) { SpecificationNode sn = ds.getChild(i); if (sn.getType().equals("include") || sn.getType().equals("exclude")) ds.removeChild(i); else i++; } int fileCount = Integer.parseInt(xc); i = 0; while (i < fileCount) { String fileSpecDescription = "_"+Integer.toString(i); String fileOpName = seqPrefix+"fileop"+fileSpecDescription; xc = variableContext.getParameter(fileOpName); if (xc != null && xc.equals("Delete")) { // Next row i++; continue; } // Get the stuff we need String filespecType = variableContext.getParameter(seqPrefix+"specfiletype"+fileSpecDescription); String filespec = variableContext.getParameter(seqPrefix+"specfile"+fileSpecDescription); SpecificationNode node = new SpecificationNode(filespecType); node.setAttribute("filespec",filespec); ds.addChild(ds.getChildCount(),node); i++; } String op = variableContext.getParameter(seqPrefix+"fileop"); if (op != null && op.equals("Add")) { String filespec = variableContext.getParameter(seqPrefix+"specfile"); String filespectype = variableContext.getParameter(seqPrefix+"specfiletype"); SpecificationNode node = new SpecificationNode(filespectype); node.setAttribute("filespec",filespec); ds.addChild(ds.getChildCount(),node); } } xc = variableContext.getParameter(seqPrefix+"specsecurity"); if (xc != null) { // Delete all security entries first int i = 0; while (i < ds.getChildCount()) { SpecificationNode sn = ds.getChild(i); if (sn.getType().equals("security")) ds.removeChild(i); else i++; } SpecificationNode node = new SpecificationNode("security"); node.setAttribute("value",xc); ds.addChild(ds.getChildCount(),node); } xc = variableContext.getParameter(seqPrefix+"tokencount"); if (xc != null) { // Delete all file specs first int i = 0; while (i < ds.getChildCount()) { SpecificationNode sn = ds.getChild(i); if (sn.getType().equals("access")) ds.removeChild(i); else i++; } int accessCount = Integer.parseInt(xc); i = 0; while (i < accessCount) { String accessDescription = "_"+Integer.toString(i); String accessOpName = seqPrefix+"accessop"+accessDescription; xc = variableContext.getParameter(accessOpName); if (xc != null && xc.equals("Delete")) { // Next row i++; continue; } // Get the stuff we need String accessSpec = variableContext.getParameter(seqPrefix+"spectoken"+accessDescription); SpecificationNode node = new SpecificationNode("access"); node.setAttribute("token",accessSpec); ds.addChild(ds.getChildCount(),node); i++; } String op = variableContext.getParameter(seqPrefix+"accessop"); if (op != null && op.equals("Add")) { String accessspec = variableContext.getParameter(seqPrefix+"spectoken"); SpecificationNode node = new SpecificationNode("access"); node.setAttribute("token",accessspec); ds.addChild(ds.getChildCount(),node); } } xc = variableContext.getParameter(seqPrefix+"specallmetadata"); if (xc != null) { // Look for the 'all metadata' checkbox int i = 0; while (i < ds.getChildCount()) { SpecificationNode sn = ds.getChild(i); if (sn.getType().equals("allmetadata")) ds.removeChild(i); else i++; } if (xc.equals("true")) { SpecificationNode newNode = new SpecificationNode("allmetadata"); newNode.setAttribute("all",xc); ds.addChild(ds.getChildCount(),newNode); } } xc = variableContext.getParameter(seqPrefix+"metadatacount"); if (xc != null) { // Delete all metadata specs first int i = 0; while (i < ds.getChildCount()) { SpecificationNode sn = ds.getChild(i); if (sn.getType().equals("metadata")) ds.removeChild(i); else i++; } // Find out how many children were sent int metadataCount = Integer.parseInt(xc); // Gather up these i = 0; while (i < metadataCount) { String pathDescription = "_"+Integer.toString(i); String pathOpName = seqPrefix+"metadataop"+pathDescription; xc = variableContext.getParameter(pathOpName); if (xc != null && xc.equals("Delete")) { // Skip to the next i++; continue; } // Metadata inserts won't happen until the very end String category = variableContext.getParameter(seqPrefix+"speccategory"+pathDescription); String attributeName = variableContext.getParameter(seqPrefix+"specattribute"+pathDescription); String isAll = variableContext.getParameter(seqPrefix+"specattributeall"+pathDescription); SpecificationNode node = new SpecificationNode("metadata"); node.setAttribute("category",category); if (isAll != null && isAll.equals("true")) node.setAttribute("all","true"); else node.setAttribute("attribute",attributeName); ds.addChild(ds.getChildCount(),node); i++; } // See if there's a global add operation String op = variableContext.getParameter(seqPrefix+"metadataop"); if (op != null && op.equals("Add")) { String category = variableContext.getParameter(seqPrefix+"speccategory"); String isAll = variableContext.getParameter(seqPrefix+"attributeall"); if (isAll != null && isAll.equals("true")) { SpecificationNode node = new SpecificationNode("metadata"); node.setAttribute("category",category); node.setAttribute("all","true"); ds.addChild(ds.getChildCount(),node); } else { String[] attributes = variableContext.getParameterValues(seqPrefix+"attributeselect"); if (attributes != null && attributes.length > 0) { int k = 0; while (k < attributes.length) { String attribute = attributes[k++]; SpecificationNode node = new SpecificationNode("metadata"); node.setAttribute("category",category); node.setAttribute("attribute",attribute); ds.addChild(ds.getChildCount(),node); } } } } else if (op != null && op.equals("Up")) { // Strip off end String category = variableContext.getParameter(seqPrefix+"speccategory"); int lastSlash = -1; int firstColon = -1; int k = 0; while (k < category.length()) { char x = category.charAt(k++); if (x == '/') { lastSlash = k-1; continue; } if (x == ':') { firstColon = k; continue; } if (x == '\\') k++; } if (lastSlash == -1) { if (firstColon == -1 || firstColon == category.length()) category = ""; else category = category.substring(0,firstColon); } else category = category.substring(0,lastSlash); currentContext.save(seqPrefix+"speccategory",category); } else if (op != null && op.equals("AddToPath")) { String category = variableContext.getParameter(seqPrefix+"speccategory"); String addon = variableContext.getParameter(seqPrefix+"metadataaddon"); if (addon != null && addon.length() > 0) { StringBuilder sb = new StringBuilder(); int k = 0; while (k < addon.length()) { char x = addon.charAt(k++); if (x == '/' || x == '\\' || x == ':') sb.append('\\'); sb.append(x); } if (category.length() == 0 || category.endsWith(":")) category += sb.toString(); else category += "/" + sb.toString(); } currentContext.save(seqPrefix+"speccategory",category); } else if (op != null && op.equals("SetWorkspace")) { String addon = variableContext.getParameter(seqPrefix+"metadataaddon"); if (addon != null && addon.length() > 0) { StringBuilder sb = new StringBuilder(); int k = 0; while (k < addon.length()) { char x = addon.charAt(k++); if (x == '/' || x == '\\' || x == ':') sb.append('\\'); sb.append(x); } String category = sb.toString() + ":"; currentContext.save(seqPrefix+"speccategory",category); } } else if (op != null && op.equals("AddCategory")) { String category = variableContext.getParameter(seqPrefix+"speccategory"); String addon = variableContext.getParameter(seqPrefix+"categoryaddon"); if (addon != null && addon.length() > 0) { StringBuilder sb = new StringBuilder(); int k = 0; while (k < addon.length()) { char x = addon.charAt(k++); if (x == '/' || x == '\\' || x == ':') sb.append('\\'); sb.append(x); } if (category.length() == 0 || category.endsWith(":")) category += sb.toString(); else category += "/" + sb.toString(); } currentContext.save(seqPrefix+"speccategory",category); } } xc = variableContext.getParameter(seqPrefix+"specpathnameattribute"); if (xc != null) { String separator = variableContext.getParameter(seqPrefix+"specpathnameseparator"); if (separator == null) separator = "/"; // Delete old one int i = 0; while (i < ds.getChildCount()) { SpecificationNode sn = ds.getChild(i); if (sn.getType().equals("pathnameattribute")) ds.removeChild(i); else i++; } if (xc.length() > 0) { SpecificationNode node = new SpecificationNode("pathnameattribute"); node.setAttribute("value",xc); node.setAttribute("separator",separator); ds.addChild(ds.getChildCount(),node); } } xc = variableContext.getParameter(seqPrefix+"specmappingcount"); if (xc != null) { // Delete old spec int i = 0; while (i < ds.getChildCount()) { SpecificationNode sn = ds.getChild(i); if (sn.getType().equals("pathmap")) ds.removeChild(i); else i++; } // Now, go through the data and assemble a new list. int mappingCount = Integer.parseInt(xc); // Gather up these i = 0; while (i < mappingCount) { String pathDescription = "_"+Integer.toString(i); String pathOpName = seqPrefix+"specmappingop"+pathDescription; xc = variableContext.getParameter(pathOpName); if (xc != null && xc.equals("Delete")) { // Skip to the next i++; continue; } // Inserts won't happen until the very end String match = variableContext.getParameter(seqPrefix+"specmatch"+pathDescription); String replace = variableContext.getParameter(seqPrefix+"specreplace"+pathDescription); SpecificationNode node = new SpecificationNode("pathmap"); node.setAttribute("match",match); node.setAttribute("replace",replace); ds.addChild(ds.getChildCount(),node); i++; } // Check for add xc = variableContext.getParameter(seqPrefix+"specmappingop"); if (xc != null && xc.equals("Add")) { String match = variableContext.getParameter(seqPrefix+"specmatch"); String replace = variableContext.getParameter(seqPrefix+"specreplace"); SpecificationNode node = new SpecificationNode("pathmap"); node.setAttribute("match",match); node.setAttribute("replace",replace); ds.addChild(ds.getChildCount(),node); } } return null; } /** View specification. * This method is called in the body section of a job's view page. Its purpose is to present the document * specification information to the user. The coder can presume that the HTML that is output from * this configuration will be within appropriate <html> and <body> tags. * The connector will be connected before this method can be called. *@param out is the output to which any HTML should be sent. *@param locale is the locale the output is preferred to be in. *@param ds is the current document specification for this job. *@param connectionSequenceNumber is the unique number of this connection within the job. */ @Override public void viewSpecification(IHTTPOutput out, Locale locale, Specification ds, int connectionSequenceNumber) throws ManifoldCFException, IOException { out.print( "<table class=\"displaytable\">\n"+ " <tr>\n" ); int i = 0; boolean userWorkspaces = false; while (i < ds.getChildCount()) { SpecificationNode sn = ds.getChild(i++); if (sn.getType().equals("userworkspace")) { String value = sn.getAttributeValue("value"); if (value != null && value.equals("true")) userWorkspaces = true; } } out.print( " <td class=\"description\"/>\n"+ " <nobr>"+Messages.getBodyString(locale,"LivelinkConnector.CrawlUserWorkspaces")+"</nobr>\n"+ " </td>\n"+ " <td class=\"value\"/>\n"+ " "+(userWorkspaces?Messages.getBodyString(locale,"LivelinkConnector.Yes"):Messages.getBodyString(locale,"LivelinkConnector.No"))+"\n"+ " </td>\n"+ " </tr>" ); out.print( " <tr><td class=\"separator\" colspan=\"2\"><hr/></td></tr>\n" ); out.print( " <tr>" ); i = 0; boolean seenAny = false; while (i < ds.getChildCount()) { SpecificationNode sn = ds.getChild(i++); if (sn.getType().equals("startpoint")) { if (seenAny == false) { out.print( " <td class=\"description\">"+Messages.getBodyString(locale,"LivelinkConnector.Roots")+"</td>\n"+ " <td class=\"value\">\n" ); seenAny = true; } out.print( " "+org.apache.manifoldcf.ui.util.Encoder.bodyEscape(sn.getAttributeValue("path"))+"<br/>\n" ); } } if (seenAny) { out.print( " </td>\n"+ " </tr>\n" ); } else { out.print( " <tr><td class=\"message\" colspan=\"2\">"+Messages.getBodyString(locale,"LivelinkConnector.NoStartPointsSpecified")+"</td></tr>\n" ); } out.print( " <tr><td class=\"separator\" colspan=\"2\"><hr/></td></tr>\n" ); seenAny = false; // Go through looking for include or exclude file specs i = 0; while (i < ds.getChildCount()) { SpecificationNode sn = ds.getChild(i++); if (sn.getType().equals("include") || sn.getType().equals("exclude")) { if (seenAny == false) { out.print( " <tr><td class=\"description\">"+Messages.getBodyString(locale,"LivelinkConnector.FileSpecs")+"</td>\n"+ " <td class=\"value\">\n" ); seenAny = true; } String filespec = sn.getAttributeValue("filespec"); out.print( " "+(sn.getType().equals("include")?"Include file:":"")+"\n"+ " "+(sn.getType().equals("exclude")?"Exclude file:":"")+"\n"+ " "+org.apache.manifoldcf.ui.util.Encoder.bodyEscape(filespec)+"<br/>\n" ); } } if (seenAny) { out.print( " </td>\n"+ " </tr>\n" ); } else { out.print( " <tr><td class=\"message\" colspan=\"2\">"+Messages.getBodyString(locale,"LivelinkConnector.NoFileSpecsSpecified")+"</td></tr>\n" ); } out.print( " <tr><td class=\"separator\" colspan=\"2\"><hr/></td></tr>\n" ); // Find whether security is on or off i = 0; boolean securityOn = true; while (i < ds.getChildCount()) { SpecificationNode sn = ds.getChild(i++); if (sn.getType().equals("security")) { String securityValue = sn.getAttributeValue("value"); if (securityValue.equals("off")) securityOn = false; else if (securityValue.equals("on")) securityOn = true; } } out.print( " <tr>\n"+ " <td class=\"description\">"+Messages.getBodyString(locale,"LivelinkConnector.SecurityColon")+"</td>\n"+ " <td class=\"value\">"+(securityOn?Messages.getBodyString(locale,"LivelinkConnector.Enabled2"):Messages.getBodyString(locale,"LivelinkConnector.Disabled"))+"</td>\n"+ " </tr>\n"+ "\n"+ " <tr><td class=\"separator\" colspan=\"2\"><hr/></td></tr>\n" ); // Go through looking for access tokens seenAny = false; i = 0; while (i < ds.getChildCount()) { SpecificationNode sn = ds.getChild(i++); if (sn.getType().equals("access")) { if (seenAny == false) { out.print( " <tr><td class=\"description\">"+Messages.getBodyString(locale,"LivelinkConnector.AccessTokens")+"</td>\n"+ " <td class=\"value\">\n" ); seenAny = true; } String token = sn.getAttributeValue("token"); out.print( " "+org.apache.manifoldcf.ui.util.Encoder.bodyEscape(token)+"<br/>\n" ); } } if (seenAny) { out.print( " </td>\n"+ " </tr>\n" ); } else { out.print( " <tr><td class=\"message\" colspan=\"2\">" + Messages.getBodyString(locale,"LivelinkConnector.NoAccessTokensSpecified") + "</td></tr>\n" ); } out.print( " <tr><td class=\"separator\" colspan=\"2\"><hr/></td></tr>\n" ); i = 0; String allMetadata = Messages.getBodyString(locale,"LivelinkConnector.OnlySpecifiedMetadataWillBeIngested"); while (i < ds.getChildCount()) { SpecificationNode sn = ds.getChild(i++); if (sn.getType().equals("allmetadata")) { String value = sn.getAttributeValue("all"); if (value != null && value.equals("true")) { allMetadata=Messages.getBodyString(locale,"LivelinkConnector.AllDocumentMetadataWillBeIngested"); } } } out.print( " <tr>\n"+ " <td class=\"description\"><nobr>"+Messages.getBodyString(locale,"LivelinkConnector.MetadataSpecification")+"</nobr></td>\n"+ " <td class=\"value\"><nobr>"+allMetadata+"</nobr></td>\n"+ " </tr>\n"+ " <tr><td class=\"separator\" colspan=\"2\"><hr/></td></tr>\n" ); // Go through looking for metadata spec seenAny = false; i = 0; while (i < ds.getChildCount()) { SpecificationNode sn = ds.getChild(i++); if (sn.getType().equals("metadata")) { if (seenAny == false) { out.print( " <tr><td class=\"description\"><nobr>"+Messages.getBodyString(locale,"LivelinkConnector.SpecificMetadata")+"</nobr></td>\n"+ " <td class=\"value\">\n" ); seenAny = true; } String category = sn.getAttributeValue("category"); String attribute = sn.getAttributeValue("attribute"); String isAll = sn.getAttributeValue("all"); out.print( " "+org.apache.manifoldcf.ui.util.Encoder.bodyEscape(category)+":"+((isAll!=null&&isAll.equals("true"))?"(All metadata attributes)":org.apache.manifoldcf.ui.util.Encoder.bodyEscape(attribute))+"<br/>\n" ); } } if (seenAny) { out.print( " </td>\n"+ " </tr>\n" ); } else { out.print( " <tr><td class=\"message\" colspan=\"2\">"+Messages.getBodyString(locale,"LivelinkConnector.NoMetadataSpecified")+"</td></tr>\n" ); } out.print( " <tr><td class=\"separator\" colspan=\"2\"><hr/></td></tr>\n" ); // Find the path-name metadata attribute name i = 0; String pathNameAttribute = ""; String pathSeparator = "/"; while (i < ds.getChildCount()) { SpecificationNode sn = ds.getChild(i++); if (sn.getType().equals("pathnameattribute")) { pathNameAttribute = sn.getAttributeValue("value"); if (sn.getAttributeValue("separator") != null) pathSeparator = sn.getAttributeValue("separator"); } } if (pathNameAttribute.length() > 0) { out.print( " <tr>\n"+ " <td class=\"description\">"+Messages.getBodyString(locale,"LivelinkConnector.PathNameMetadataAttribute")+"</td>\n"+ " <td class=\"value\">"+org.apache.manifoldcf.ui.util.Encoder.bodyEscape(pathNameAttribute)+"</td>\n"+ " </tr>\n"+ " <tr>\n"+ " <td class=\"description\">"+Messages.getBodyString(locale,"LivelinkConnector.PathSeparatorString")+"</td>\n"+ " <td class=\"value\">"+org.apache.manifoldcf.ui.util.Encoder.bodyEscape(pathSeparator)+"</td>\n"+ " </tr>\n" ); } else { out.print( " <tr>\n"+ " <td class=\"message\" colspan=\"2\">"+Messages.getBodyString(locale,"LivelinkConnector.NoPathNameMetadataAttributeSpecified")+"</td>\n"+ " </tr>\n" ); } out.print( "\n"+ " <tr><td class=\"separator\" colspan=\"2\"><hr/></td></tr>\n"+ "\n"+ " <tr>\n" ); // Find the path-value mapping data i = 0; MatchMap matchMap = new MatchMap(); while (i < ds.getChildCount()) { SpecificationNode sn = ds.getChild(i++); if (sn.getType().equals("pathmap")) { String pathMatch = sn.getAttributeValue("match"); String pathReplace = sn.getAttributeValue("replace"); matchMap.appendMatchPair(pathMatch,pathReplace); } } if (matchMap.getMatchCount() > 0) { out.print( " <td class=\"description\">"+Messages.getBodyString(locale,"LivelinkConnector.PathValueMapping")+"</td>\n"+ " <td class=\"value\">\n"+ " <table class=\"displaytable\">\n" ); i = 0; while (i < matchMap.getMatchCount()) { String matchString = matchMap.getMatchString(i); String replaceString = matchMap.getReplaceString(i); out.print( " <tr>\n"+ " <td class=\"value\">"+org.apache.manifoldcf.ui.util.Encoder.bodyEscape(matchString)+"</td>\n"+ " <td class=\"value\">--></td>\n"+ " <td class=\"value\">"+org.apache.manifoldcf.ui.util.Encoder.bodyEscape(replaceString)+"</td>\n"+ " </tr>\n" ); i++; } out.print( " </table>\n"+ " </td>\n" ); } else { out.print( " <td class=\"message\" colspan=\"2\">"+Messages.getBodyString(locale,"LivelinkConnector.NoMappingsSpecified")+"</td>\n" ); } out.print( " </tr>\n"+ "</table>\n" ); } // The following public methods are NOT part of the interface. They are here so that the UI can present information // that will allow users to select what they need. protected final static String CATEGORY_NAME = "CATEGORY"; protected final static String ENTWKSPACE_NAME = "ENTERPRISE"; /** Get the allowed workspace names. *@return a list of workspace names. */ public String[] getWorkspaceNames() throws ManifoldCFException, ServiceInterruption { return new String[]{CATEGORY_NAME,ENTWKSPACE_NAME}; } /** Given a path string, get a list of folders and projects under that node. *@param pathString is the current path (folder names and project names, separated by dots (.)). *@return a list of folder and project names, in sorted order, or null if the path was invalid. */ public String[] getChildFolderNames(String pathString) throws ManifoldCFException, ServiceInterruption { getSession(); return getChildFolders(new LivelinkContext(),pathString); } /** Given a path string, get a list of categories under that node. *@param pathString is the current path (folder names and project names, separated by dots (.)). *@return a list of category names, in sorted order, or null if the path was invalid. */ public String[] getChildCategoryNames(String pathString) throws ManifoldCFException, ServiceInterruption { getSession(); return getChildCategories(new LivelinkContext(),pathString); } /** Given a category path, get a list of legal attribute names. *@param pathString is the current path of a category (with path components separated by dots). *@return a list of attribute names, in sorted order, or null of the path was invalid. */ public String[] getCategoryAttributes(String pathString) throws ManifoldCFException, ServiceInterruption { getSession(); return getCategoryAttributes(new LivelinkContext(), pathString); } protected String[] getCategoryAttributes(LivelinkContext llc, String pathString) throws ManifoldCFException, ServiceInterruption { // Start at root RootValue rv = new RootValue(llc,pathString); // Get the object id of the category the path describes int catObjectID = getCategoryId(rv); if (catObjectID == -1) return null; String[] rval = getCategoryAttributes(catObjectID); if (rval == null) return new String[0]; return rval; } // Protected methods and classes /** Create the login URI. This must be a relative URI. */ protected String createLivelinkLoginURI() throws ManifoldCFException { StringBuilder llURI = new StringBuilder(); llURI.append(ingestCgiPath); llURI.append("?func=ll.login&CurrentClientTime=D%2F2005%2F3%2F9%3A13%3A16%3A30&NextURL="); llURI.append(org.apache.manifoldcf.core.util.URLEncoder.encode(ingestCgiPath)); llURI.append("%3FRedirect%3D1&Username="); llURI.append(org.apache.manifoldcf.core.util.URLEncoder.encode(llServer.getLLUser())); llURI.append("&Password="); llURI.append(org.apache.manifoldcf.core.util.URLEncoder.encode(llServer.getLLPwd())); return llURI.toString(); } /** * Connects to the specified Livelink document using HTTP protocol * @param documentIdentifier is the document identifier (as far as the crawler knows). * @param activities is the process activity structure, so we can ingest */ protected void ingestFromLiveLink(LivelinkContext llc, String documentIdentifier, String version, String[] actualAcls, String[] denyAcls, String[] categoryPaths, IProcessActivity activities, MetadataDescription desc, SystemMetadataDescription sDesc) throws ManifoldCFException, ServiceInterruption { String contextMsg = "for '"+documentIdentifier+"'"; String viewHttpAddress = convertToViewURI(documentIdentifier); if (viewHttpAddress == null) { if (Logging.connectors.isDebugEnabled()) Logging.connectors.debug("Livelink: No view URI "+contextMsg+" - not ingesting"); return; } // Fetch logging long startTime = System.currentTimeMillis(); String resultCode = "FAILED"; String resultDescription = null; Long readSize = null; boolean wasInterrupted = false; int objID; int vol; int colonPos = documentIdentifier.indexOf(":",1); if (colonPos == -1) { objID = new Integer(documentIdentifier.substring(1)).intValue(); vol = LLENTWK_VOL; } else { objID = new Integer(documentIdentifier.substring(colonPos+1)).intValue(); vol = new Integer(documentIdentifier.substring(1,colonPos)).intValue(); } // Try/finally for fetch logging try { // Check URL first if (!activities.checkURLIndexable(viewHttpAddress)) { // Document not ingestable due to URL resultDescription = "URL ("+viewHttpAddress+") was rejected by output connector"; if (Logging.connectors.isDebugEnabled()) Logging.connectors.debug("Livelink: Excluding document "+documentIdentifier+" because its URL ("+viewHttpAddress+") was rejected by output connector"); resultCode = "URLEXCLUSION"; activities.noDocument(documentIdentifier,version); return; } // Add general metadata ObjectInformation objInfo = llc.getObjectInformation(vol,objID); VersionInformation versInfo = llc.getVersionInformation(vol,objID,0); if (!objInfo.exists()) { resultCode = "OBJECTNOTFOUND"; Logging.connectors.debug("Livelink: No object "+contextMsg+": not ingesting"); return; } if (!versInfo.exists()) { resultCode = "VERSIONNOTFOUND"; Logging.connectors.debug("Livelink: No version data "+contextMsg+": not ingesting"); return; } String mimeType = versInfo.getMimeType(); if (!activities.checkMimeTypeIndexable(mimeType)) { // Document not indexable because of its mime type resultDescription = "Mime type ("+mimeType+") was rejected by output connector"; if (Logging.connectors.isDebugEnabled()) Logging.connectors.debug("Livelink: Excluding document "+documentIdentifier+" because its mime type ("+mimeType+") was rejected by output connector"); resultCode = "MIMETYPEEXCLUSION"; activities.noDocument(documentIdentifier,version); return; } Long dataSize = versInfo.getDataSize(); if (dataSize == null) { // Document had no length resultDescription = "Document had no length"; if (Logging.connectors.isDebugEnabled()) Logging.connectors.debug("Livelink: Excluding document "+documentIdentifier+" because it had no length"); resultCode = "DOCUMENTNOLENGTH"; activities.noDocument(documentIdentifier,version); return; } if (!activities.checkLengthIndexable(dataSize.longValue())) { // Document not indexable because of its length resultDescription = "Document length ("+dataSize+") was rejected by output connector"; if (Logging.connectors.isDebugEnabled()) Logging.connectors.debug("Livelink: Excluding document "+documentIdentifier+" because its length ("+dataSize+") was rejected by output connector"); resultCode = "DOCUMENTTOOLONG"; activities.noDocument(documentIdentifier,version); return; } Date modifyDate = versInfo.getModifyDate(); if (!activities.checkDateIndexable(modifyDate)) { // Document not indexable because of its date resultDescription = "Document date ("+modifyDate+") was rejected by output connector"; if (Logging.connectors.isDebugEnabled()) Logging.connectors.debug("Livelink: Excluding document "+documentIdentifier+" because its date ("+modifyDate+") was rejected by output connector"); resultCode = "DOCUMENTBADDATE"; activities.noDocument(documentIdentifier,version); return; } String fileName = versInfo.getFileName(); Date creationDate = objInfo.getCreationDate(); Integer parentID = objInfo.getParentId(); RepositoryDocument rd = new RepositoryDocument(); // Add general data we need for the output connector if (mimeType != null) rd.setMimeType(mimeType); if (fileName != null) rd.setFileName(fileName); if (creationDate != null) rd.setCreatedDate(creationDate); if (modifyDate != null) rd.setModifiedDate(modifyDate); rd.addField(GENERAL_NAME_FIELD,objInfo.getName()); rd.addField(GENERAL_DESCRIPTION_FIELD,objInfo.getComments()); if (creationDate != null) rd.addField(GENERAL_CREATIONDATE_FIELD,DateParser.formatISO8601Date(creationDate)); if (modifyDate != null) rd.addField(GENERAL_MODIFYDATE_FIELD,DateParser.formatISO8601Date(modifyDate)); if (parentID != null) rd.addField(GENERAL_PARENTID,parentID.toString()); UserInformation owner = llc.getUserInformation(objInfo.getOwnerId().intValue()); UserInformation creator = llc.getUserInformation(objInfo.getCreatorId().intValue()); UserInformation modifier = llc.getUserInformation(versInfo.getOwnerId().intValue()); if (owner != null) rd.addField(GENERAL_OWNER,owner.getName()); if (creator != null) rd.addField(GENERAL_CREATOR,creator.getName()); if (modifier != null) rd.addField(GENERAL_MODIFIER,modifier.getName()); // Iterate over the metadata items. These are organized by category // for speed of lookup. Iterator<MetadataItem> catIter = desc.getItems(categoryPaths); while (catIter.hasNext()) { MetadataItem item = catIter.next(); MetadataPathItem pathItem = item.getPathItem(); if (pathItem != null) { int catID = pathItem.getCatID(); // grab the associated catversion LLValue catVersion = getCatVersion(objID,catID); if (catVersion != null) { // Go through attributes now Iterator<String> attrIter = item.getAttributeNames(); while (attrIter.hasNext()) { String attrName = attrIter.next(); // Create a unique metadata name String metadataName = pathItem.getCatName()+":"+attrName; // Fetch the metadata and stuff it into the RepositoryData structure String[] metadataValue = getAttributeValue(catVersion,attrName); if (metadataValue != null) rd.addField(metadataName,metadataValue); else Logging.connectors.warn("Livelink: Metadata attribute '"+metadataName+"' does not seem to exist; please correct the job"); } } } } if (actualAcls != null && denyAcls != null) rd.setSecurity(RepositoryDocument.SECURITY_TYPE_DOCUMENT,actualAcls,denyAcls); // Add the path metadata item into the mix, if enabled String pathAttributeName = sDesc.getPathAttributeName(); if (pathAttributeName != null && pathAttributeName.length() > 0) { String pathString = sDesc.getPathAttributeValue(documentIdentifier); if (pathString != null) { if (Logging.connectors.isDebugEnabled()) Logging.connectors.debug("Livelink: Path attribute name is '"+pathAttributeName+"'"+contextMsg+", value is '"+pathString+"'"); rd.addField(pathAttributeName,pathString); } } if (ingestProtocol != null) { // Use HTTP to fetch document! String ingestHttpAddress = convertToIngestURI(documentIdentifier); if (ingestHttpAddress != null) { // Set up connection HttpClient client = getInitializedClient(contextMsg); long currentTime; if (Logging.connectors.isInfoEnabled()) Logging.connectors.info("Livelink: " + ingestHttpAddress); HttpGet method = new HttpGet(getHost().toURI() + ingestHttpAddress); method.setHeader(new BasicHeader("Accept","*/*")); ExecuteMethodThread methodThread = new ExecuteMethodThread(client,method); methodThread.start(); try { int statusCode = methodThread.getResponseCode(); switch (statusCode) { case 500: case 502: Logging.connectors.warn("Livelink: Service interruption during fetch "+contextMsg+" with Livelink HTTP Server, retrying..."); throw new ServiceInterruption("Service interruption during fetch",new ManifoldCFException(Integer.toString(statusCode)+" error while fetching"),System.currentTimeMillis()+60000L, System.currentTimeMillis()+600000L,-1,true); case HttpStatus.SC_UNAUTHORIZED: Logging.connectors.warn("Livelink: Document fetch unauthorized for "+ingestHttpAddress+" ("+contextMsg+")"); // Since we logged in, we should fail here if the ingestion user doesn't have access to the // the document, but if we do, don't fail hard. resultCode = "UNAUTHORIZED"; activities.noDocument(documentIdentifier,version); return; case HttpStatus.SC_OK: if (Logging.connectors.isDebugEnabled()) Logging.connectors.debug("Livelink: Created http document connection to Livelink "+contextMsg); // A non-existent content length will cause a value of -1 to be returned. This seems to indicate that the session login did not work right. if (methodThread.getResponseContentLength() >= 0) { try { InputStream is = methodThread.getSafeInputStream(); try { rd.setBinary(is,dataSize); activities.ingestDocumentWithException(documentIdentifier,version,viewHttpAddress,rd); if (Logging.connectors.isDebugEnabled()) Logging.connectors.debug("Livelink: Ingesting done "+contextMsg); } finally { // Close stream via thread, since otherwise this can hang is.close(); } } catch (java.net.SocketTimeoutException e) { resultCode = "DATATIMEOUT"; resultDescription = e.getMessage(); currentTime = System.currentTimeMillis(); Logging.connectors.warn("Livelink: Livelink socket timed out ingesting from the Livelink HTTP Server "+contextMsg+": "+e.getMessage(), e); throw new ServiceInterruption("Socket timed out: "+e.getMessage(),e,currentTime+300000L,currentTime+6*3600000L,-1,false); } catch (java.net.SocketException e) { resultCode = "DATASOCKETERROR"; resultDescription = e.getMessage(); currentTime = System.currentTimeMillis(); Logging.connectors.warn("Livelink: Livelink socket error ingesting from the Livelink HTTP Server "+contextMsg+": "+e.getMessage(), e); throw new ServiceInterruption("Socket error: "+e.getMessage(),e,currentTime+300000L,currentTime+6*3600000L,-1,false); } catch (javax.net.ssl.SSLHandshakeException e) { resultCode = "DATASSLHANDSHAKEERROR"; resultDescription = e.getMessage(); currentTime = System.currentTimeMillis(); Logging.connectors.warn("Livelink: SSL handshake failed authenticating "+contextMsg+": "+e.getMessage(),e); throw new ServiceInterruption("SSL handshake error: "+e.getMessage(),e,currentTime+60000L,currentTime+300000L,-1,true); } catch (ConnectTimeoutException e) { resultCode = "CONNECTTIMEOUT"; resultDescription = e.getMessage(); currentTime = System.currentTimeMillis(); Logging.connectors.warn("Livelink: Livelink socket timed out connecting to the Livelink HTTP Server "+contextMsg+": "+e.getMessage(), e); throw new ServiceInterruption("Connect timed out: "+e.getMessage(),e,currentTime+300000L,currentTime+6*3600000L,-1,false); } catch (InterruptedException e) { wasInterrupted = true; throw new ManifoldCFException("Interrupted: "+e.getMessage(),e,ManifoldCFException.INTERRUPTED); } catch (InterruptedIOException e) { wasInterrupted = true; throw new ManifoldCFException("Interrupted: "+e.getMessage(),e,ManifoldCFException.INTERRUPTED); } catch (HttpException e) { resultCode = "HTTPEXCEPTION"; resultDescription = e.getMessage(); // Treat unknown error ingesting data as a transient condition currentTime = System.currentTimeMillis(); Logging.connectors.warn("Livelink: HTTP exception ingesting "+contextMsg+": "+e.getMessage(),e); throw new ServiceInterruption("HTTP exception ingesting "+contextMsg+": "+e.getMessage(),e,currentTime+300000L,currentTime+6*3600000L,-1,false); } catch (IOException e) { resultCode = "DATAEXCEPTION"; resultDescription = e.getMessage(); // Treat unknown error ingesting data as a transient condition currentTime = System.currentTimeMillis(); Logging.connectors.warn("Livelink: IO exception ingesting "+contextMsg+": "+e.getMessage(),e); throw new ServiceInterruption("IO exception ingesting "+contextMsg+": "+e.getMessage(),e,currentTime+300000L,currentTime+6*3600000L,-1,false); } readSize = dataSize; } else { resultCode = "SESSIONLOGINFAILED"; activities.noDocument(documentIdentifier,version); } break; case HttpStatus.SC_BAD_REQUEST: case HttpStatus.SC_USE_PROXY: case HttpStatus.SC_GONE: resultCode = "ERROR "+Integer.toString(statusCode); throw new ManifoldCFException("Unrecoverable request failure; error = "+Integer.toString(statusCode)); default: resultCode = "UNKNOWN"; Logging.connectors.warn("Livelink: Attempt to retrieve document from '"+ingestHttpAddress+"' received a response of "+Integer.toString(statusCode)+"; retrying in one minute"); currentTime = System.currentTimeMillis(); throw new ServiceInterruption("Fetch failed; retrying in 1 minute",new ManifoldCFException("Fetch failed with unknown code "+Integer.toString(statusCode)), currentTime+60000L,currentTime+600000L,-1,true); } } catch (InterruptedException e) { // Drop the connection on the floor methodThread.interrupt(); methodThread = null; throw new ManifoldCFException("Interrupted: "+e.getMessage(),e,ManifoldCFException.INTERRUPTED); } catch (java.net.SocketTimeoutException e) { Logging.connectors.warn("Livelink: Socket timed out reading from the Livelink HTTP Server "+contextMsg+": "+e.getMessage(), e); resultCode = "TIMEOUT"; resultDescription = e.getMessage(); currentTime = System.currentTimeMillis(); throw new ServiceInterruption("Socket timed out: "+e.getMessage(),e,currentTime+300000L,currentTime+6*3600000L,-1,true); } catch (java.net.SocketException e) { Logging.connectors.warn("Livelink: Socket error reading from Livelink HTTP Server "+contextMsg+": "+e.getMessage(), e); resultCode = "SOCKETERROR"; resultDescription = e.getMessage(); currentTime = System.currentTimeMillis(); throw new ServiceInterruption("Socket error: "+e.getMessage(),e,currentTime+300000L,currentTime+6*3600000L,-1,true); } catch (javax.net.ssl.SSLHandshakeException e) { currentTime = System.currentTimeMillis(); Logging.connectors.warn("Livelink: SSL handshake failed "+contextMsg+": "+e.getMessage(),e); resultCode = "SSLHANDSHAKEERROR"; resultDescription = e.getMessage(); throw new ServiceInterruption("SSL handshake error: "+e.getMessage(),e,currentTime+60000L,currentTime+300000L,-1,true); } catch (ConnectTimeoutException e) { Logging.connectors.warn("Livelink: Connect timed out reading from the Livelink HTTP Server "+contextMsg+": "+e.getMessage(), e); resultCode = "CONNECTTIMEOUT"; resultDescription = e.getMessage(); currentTime = System.currentTimeMillis(); throw new ServiceInterruption("Connect timed out: "+e.getMessage(),e,currentTime+300000L,currentTime+6*3600000L,-1,true); } catch (InterruptedIOException e) { methodThread.interrupt(); throw new ManifoldCFException("Interrupted: "+e.getMessage(),e,ManifoldCFException.INTERRUPTED); } catch (HttpException e) { resultCode = "EXCEPTION"; resultDescription = e.getMessage(); throw new ManifoldCFException("Exception getting response "+contextMsg+": "+e.getMessage(), e); } catch (IOException e) { resultCode = "EXCEPTION"; resultDescription = e.getMessage(); throw new ManifoldCFException("Exception getting response "+contextMsg+": "+e.getMessage(), e); } finally { if (methodThread != null) { methodThread.abort(); if (!wasInterrupted) { try { methodThread.finishUp(); } catch (InterruptedException e) { wasInterrupted = true; throw new ManifoldCFException(e.getMessage(),e,ManifoldCFException.INTERRUPTED); } } } } } else { if (Logging.connectors.isDebugEnabled()) Logging.connectors.debug("Livelink: No fetch URI "+contextMsg+" - not ingesting"); resultCode = "NOURI"; return; } } else { // Use FetchVersion instead long currentTime; // Fire up the document reading thread DocumentReadingThread t = new DocumentReadingThread(vol,objID,0); try { t.start(); try { InputStream is = t.getSafeInputStream(); try { // Can only index while background thread is running! rd.setBinary(is, dataSize); activities.ingestDocumentWithException(documentIdentifier, version, viewHttpAddress, rd); } finally { is.close(); } } catch (ManifoldCFException e) { if (e.getErrorCode() == ManifoldCFException.INTERRUPTED) wasInterrupted = true; throw e; } catch (java.net.SocketTimeoutException e) { throw e; } catch (InterruptedIOException e) { wasInterrupted = true; throw e; } finally { if (!wasInterrupted) t.finishUp(); } // No errors. Record the fact that we made it. resultCode = "OK"; readSize = dataSize; } catch (InterruptedException e) { t.interrupt(); throw new ManifoldCFException("Interrupted: " + e.getMessage(), e, ManifoldCFException.INTERRUPTED); } catch (ConnectTimeoutException e) { Logging.connectors.warn("Livelink: Connect timed out "+contextMsg+": "+e.getMessage(), e); resultCode = "CONNECTTIMEOUT"; resultDescription = e.getMessage(); currentTime = System.currentTimeMillis(); throw new ServiceInterruption("Connect timed out: "+e.getMessage(),e,currentTime+300000L,currentTime+6*3600000L,-1,true); } catch (InterruptedIOException e) { t.interrupt(); throw new ManifoldCFException("Interrupted: "+e.getMessage(),e,ManifoldCFException.INTERRUPTED); } catch (IOException e) { resultCode = "EXCEPTION"; resultDescription = e.getMessage(); throw new ManifoldCFException("Exception getting response "+contextMsg+": "+e.getMessage(), e); } catch (ManifoldCFException e) { if (e.getErrorCode() != ManifoldCFException.INTERRUPTED) { resultCode = "EXCEPTION"; resultDescription = e.getMessage(); } throw e; } catch (RuntimeException e) { resultCode = "EXCEPTION"; resultDescription = e.getMessage(); handleLivelinkRuntimeException(e,0,true); } } } finally { if (!wasInterrupted) activities.recordActivity(new Long(startTime),ACTIVITY_FETCH,readSize,vol+":"+objID,resultCode,resultDescription,null); } } /** Initialize a livelink client connection */ protected HttpClient getInitializedClient(String contextMsg) throws ServiceInterruption, ManifoldCFException { long currentTime; if (Logging.connectors.isDebugEnabled()) Logging.connectors.debug("Livelink: Session authenticating via http "+contextMsg+"..."); HttpGet authget = new HttpGet(getHost().toURI() + createLivelinkLoginURI()); authget.setHeader(new BasicHeader("Accept","*/*")); try { if (Logging.connectors.isDebugEnabled()) Logging.connectors.debug("Livelink: Created new HttpGet "+contextMsg+"; executing authentication method"); int statusCode = executeMethodViaThread(httpClient,authget); if (statusCode == 502 || statusCode == 500) { Logging.connectors.warn("Livelink: Service interruption during authentication "+contextMsg+" with Livelink HTTP Server, retrying..."); currentTime = System.currentTimeMillis(); throw new ServiceInterruption("502 error during authentication",new ManifoldCFException("502 error while authenticating"), currentTime+60000L,currentTime+600000L,-1,true); } if (statusCode != HttpStatus.SC_OK) { Logging.connectors.error("Livelink: Failed to authenticate "+contextMsg+" against Livelink HTTP Server; Status code: " + statusCode); // Ok, so we didn't get in - simply do not ingest if (statusCode == HttpStatus.SC_UNAUTHORIZED) throw new ManifoldCFException("Session authorization failed with a 401 code; are credentials correct?"); else throw new ManifoldCFException("Session authorization failed with code "+Integer.toString(statusCode)); } } catch (InterruptedException e) { throw new ManifoldCFException("Interrupted: "+e.getMessage(),e,ManifoldCFException.INTERRUPTED); } catch (java.net.SocketTimeoutException e) { currentTime = System.currentTimeMillis(); Logging.connectors.warn("Livelink: Socket timed out authenticating to the Livelink HTTP Server "+contextMsg+": "+e.getMessage(), e); throw new ServiceInterruption("Socket timed out: "+e.getMessage(),e,currentTime+300000L,currentTime+6*3600000L,-1,true); } catch (java.net.SocketException e) { currentTime = System.currentTimeMillis(); Logging.connectors.warn("Livelink: Socket error authenticating to the Livelink HTTP Server "+contextMsg+": "+e.getMessage(), e); throw new ServiceInterruption("Socket error: "+e.getMessage(),e,currentTime+300000L,currentTime+6*3600000L,-1,true); } catch (javax.net.ssl.SSLHandshakeException e) { currentTime = System.currentTimeMillis(); Logging.connectors.warn("Livelink: SSL handshake failed authenticating "+contextMsg+": "+e.getMessage(),e); throw new ServiceInterruption("SSL handshake error: "+e.getMessage(),e,currentTime+60000L,currentTime+300000L,-1,true); } catch (ConnectTimeoutException e) { currentTime = System.currentTimeMillis(); Logging.connectors.warn("Livelink: Connect timed out authenticating to the Livelink HTTP Server "+contextMsg+": "+e.getMessage(), e); throw new ServiceInterruption("Connect timed out: "+e.getMessage(),e,currentTime+300000L,currentTime+6*3600000L,-1,true); } catch (InterruptedIOException e) { throw new ManifoldCFException("Interrupted: "+e.getMessage(),e,ManifoldCFException.INTERRUPTED); } catch (HttpException e) { Logging.connectors.error("Livelink: HTTP exception when authenticating to the Livelink HTTP Server "+contextMsg+": "+e.getMessage(), e); throw new ManifoldCFException("Unable to communicate with the Livelink HTTP Server: "+e.getMessage(), e); } catch (IOException e) { Logging.connectors.error("Livelink: IO exception when authenticating to the Livelink HTTP Server "+contextMsg+": "+e.getMessage(), e); throw new ManifoldCFException("Unable to communicate with the Livelink HTTP Server: "+e.getMessage(), e); } return httpClient; } /** Pack category and attribute */ protected static String packCategoryAttribute(String category, String attribute) { StringBuilder sb = new StringBuilder(); pack(sb,category,':'); pack(sb,attribute,':'); return sb.toString(); } /** Unpack category and attribute */ protected static void unpackCategoryAttribute(StringBuilder category, StringBuilder attribute, String value) { int startPos = 0; startPos = unpack(category,value,startPos,':'); startPos = unpack(attribute,value,startPos,':'); } /** Given a path string, get a list of folders and projects under that node. *@param pathString is the current path (folder names and project names, separated by dots (.)). *@return a list of folder and project names, in sorted order, or null if the path was invalid. */ protected String[] getChildFolders(LivelinkContext llc, String pathString) throws ManifoldCFException, ServiceInterruption { RootValue rv = new RootValue(llc,pathString); // Get the volume, object id of the folder/project the path describes VolumeAndId vid = getPathId(rv); if (vid == null) return null; String filterString = "(SubType="+ LAPI_DOCUMENTS.FOLDERSUBTYPE + " or SubType=" + LAPI_DOCUMENTS.PROJECTSUBTYPE + " or SubType=" + LAPI_DOCUMENTS.COMPOUNDDOCUMENTSUBTYPE + ")"; int sanityRetryCount = FAILURE_RETRY_COUNT; while (true) { ListObjectsThread t = new ListObjectsThread(vid.getVolumeID(), vid.getPathId(), filterString); try { t.start(); LLValue children; try { children = t.finishUp(); } catch (ManifoldCFException e) { sanityRetryCount = assessRetry(sanityRetryCount,e); continue; } String[] rval = new String[children.size()]; int j = 0; while (j < children.size()) { rval[j] = children.toString(j,"Name"); j++; } return rval; } catch (InterruptedException e) { t.interrupt(); throw new ManifoldCFException("Interrupted: "+e.getMessage(),e,ManifoldCFException.INTERRUPTED); } catch (RuntimeException e) { sanityRetryCount = handleLivelinkRuntimeException(e,sanityRetryCount,true); continue; } } } /** Given a path string, get a list of categories under that node. *@param pathString is the current path (folder names and project names, separated by dots (.)). *@return a list of category names, in sorted order, or null if the path was invalid. */ protected String[] getChildCategories(LivelinkContext llc, String pathString) throws ManifoldCFException, ServiceInterruption { // Start at root RootValue rv = new RootValue(llc,pathString); // Get the volume, object id of the folder/project the path describes VolumeAndId vid = getPathId(rv); if (vid == null) return null; // We want only folders that are children of the current object and which match the specified subfolder String filterString = "SubType="+ LAPI_DOCUMENTS.CATEGORYSUBTYPE; int sanityRetryCount = FAILURE_RETRY_COUNT; while (true) { ListObjectsThread t = new ListObjectsThread(vid.getVolumeID(), vid.getPathId(), filterString); try { t.start(); LLValue children; try { children = t.finishUp(); } catch (ManifoldCFException e) { sanityRetryCount = assessRetry(sanityRetryCount,e); continue; } String[] rval = new String[children.size()]; int j = 0; while (j < children.size()) { rval[j] = children.toString(j,"Name"); j++; } return rval; } catch (InterruptedException e) { t.interrupt(); throw new ManifoldCFException("Interrupted: "+e.getMessage(),e,ManifoldCFException.INTERRUPTED); } catch (RuntimeException e) { sanityRetryCount = handleLivelinkRuntimeException(e,sanityRetryCount,true); continue; } } } protected class GetCategoryAttributesThread extends Thread { protected final int catObjectID; protected Throwable exception = null; protected LLValue rval = null; public GetCategoryAttributesThread(int catObjectID) { super(); setDaemon(true); this.catObjectID = catObjectID; } public void run() { try { LLValue catID = new LLValue(); catID.setAssoc(); catID.add("ID", catObjectID); catID.add("Type", LAPI_ATTRIBUTES.CATEGORY_TYPE_LIBRARY); LLValue catVersion = new LLValue(); int status = LLDocs.FetchCategoryVersion(catID,catVersion); if (status == 107105 || status == 107106) return; if (status != 0) { throw new ManifoldCFException("Error getting category version: "+Integer.toString(status)); } LLValue children = new LLValue(); status = LLAttributes.AttrListNames(catVersion,null,children); if (status != 0) { throw new ManifoldCFException("Error getting attribute names: "+Integer.toString(status)); } rval = children; } catch (Throwable e) { this.exception = e; } } public LLValue finishUp() throws ManifoldCFException, InterruptedException { join(); Throwable thr = exception; if (thr != null) { if (thr instanceof RuntimeException) throw (RuntimeException)thr; else if (thr instanceof ManifoldCFException) throw (ManifoldCFException)thr; else if (thr instanceof Error) throw (Error)thr; else throw new RuntimeException("Unrecognized exception type: "+thr.getClass().getName()+": "+thr.getMessage(),thr); } return rval; } } /** Given a category path, get a list of legal attribute names. *@param catObjectID is the object id of the category. *@return a list of attribute names, in sorted order, or null of the path was invalid. */ protected String[] getCategoryAttributes(int catObjectID) throws ManifoldCFException, ServiceInterruption { int sanityRetryCount = FAILURE_RETRY_COUNT; while (true) { GetCategoryAttributesThread t = new GetCategoryAttributesThread(catObjectID); try { t.start(); LLValue children; try { children = t.finishUp(); } catch (ManifoldCFException e) { sanityRetryCount = assessRetry(sanityRetryCount,e); continue; } if (children == null) return null; String[] rval = new String[children.size()]; LLValueEnumeration en = children.enumerateValues(); int j = 0; while (en.hasMoreElements()) { LLValue v = (LLValue)en.nextElement(); rval[j] = v.toString(); j++; } return rval; } catch (InterruptedException e) { t.interrupt(); throw new ManifoldCFException("Interrupted: "+e.getMessage(),e,ManifoldCFException.INTERRUPTED); } catch (RuntimeException e) { sanityRetryCount = handleLivelinkRuntimeException(e,sanityRetryCount,true); continue; } } } protected class GetCategoryVersionThread extends Thread { protected final int objID; protected final int catID; protected Throwable exception = null; protected LLValue rval = null; public GetCategoryVersionThread(int objID, int catID) { super(); setDaemon(true); this.objID = objID; this.catID = catID; } public void run() { try { // Set up the right llvalues // Object ID LLValue objIDValue = new LLValue().setAssoc(); objIDValue.add("ID", objID); // Current version, so don't set the "Version" field // CatID LLValue catIDValue = new LLValue().setAssoc(); catIDValue.add("ID", catID); catIDValue.add("Type", LAPI_ATTRIBUTES.CATEGORY_TYPE_LIBRARY); LLValue rvalue = new LLValue(); int status = LLDocs.GetObjectAttributesEx(objIDValue,catIDValue,rvalue); // If either the object is wrong, or the object does not have the specified category, return null. if (status == 103101 || status == 107205) return; if (status != 0) { throw new ManifoldCFException("Error retrieving category version: "+Integer.toString(status)+": "+llServer.getErrors()); } rval = rvalue; } catch (Throwable e) { this.exception = e; } } public LLValue finishUp() throws ManifoldCFException, InterruptedException { join(); Throwable thr = exception; if (thr != null) { if (thr instanceof RuntimeException) throw (RuntimeException)thr; else if (thr instanceof ManifoldCFException) throw (ManifoldCFException)thr; else if (thr instanceof Error) throw (Error)thr; else throw new RuntimeException("Unrecognized exception type: "+thr.getClass().getName()+": "+thr.getMessage(),thr); } return rval; } } /** Get a category version for document. */ protected LLValue getCatVersion(int objID, int catID) throws ManifoldCFException, ServiceInterruption { int sanityRetryCount = FAILURE_RETRY_COUNT; while (true) { GetCategoryVersionThread t = new GetCategoryVersionThread(objID,catID); try { t.start(); try { return t.finishUp(); } catch (ManifoldCFException e) { sanityRetryCount = assessRetry(sanityRetryCount,e); continue; } } catch (InterruptedException e) { t.interrupt(); throw new ManifoldCFException("Interrupted: "+e.getMessage(),e,ManifoldCFException.INTERRUPTED); } catch (NullPointerException npe) { // LAPI throws a null pointer exception under very rare conditions when the GetObjectAttributesEx is // called. The conditions are not clear at this time - it could even be due to Livelink corruption. // However, I'm going to have to treat this as // indicating that this category version does not exist for this document. Logging.connectors.warn("Livelink: Null pointer exception thrown trying to get cat version for category "+ Integer.toString(catID)+" for object "+Integer.toString(objID)); return null; } catch (RuntimeException e) { sanityRetryCount = handleLivelinkRuntimeException(e,sanityRetryCount,true); continue; } } } protected class GetAttributeValueThread extends Thread { protected final LLValue categoryVersion; protected final String attributeName; protected Throwable exception = null; protected LLValue rval = null; public GetAttributeValueThread(LLValue categoryVersion, String attributeName) { super(); setDaemon(true); this.categoryVersion = categoryVersion; this.attributeName = attributeName; } public void run() { try { // Set up the right llvalues LLValue children = new LLValue(); int status = LLAttributes.AttrGetValues(categoryVersion,attributeName, 0,null,children); // "Not found" status - I don't know if it possible to get this here, but if so, behave civilly if (status == 103101) return; // This seems to be the real error LAPI returns if you don't have an attribute of this name if (status == 8000604) return; if (status != 0) { throw new ManifoldCFException("Error retrieving attribute value: "+Integer.toString(status)+": "+llServer.getErrors()); } rval = children; } catch (Throwable e) { this.exception = e; } } public LLValue finishUp() throws ManifoldCFException, InterruptedException { join(); Throwable thr = exception; if (thr != null) { if (thr instanceof RuntimeException) throw (RuntimeException)thr; else if (thr instanceof ManifoldCFException) throw (ManifoldCFException)thr; else if (thr instanceof Error) throw (Error)thr; else throw new RuntimeException("Unrecognized exception type: "+thr.getClass().getName()+": "+thr.getMessage(),thr); } return rval; } } /** Get an attribute value from a category version. */ protected String[] getAttributeValue(LLValue categoryVersion, String attributeName) throws ManifoldCFException, ServiceInterruption { int sanityRetryCount = FAILURE_RETRY_COUNT; while (true) { GetAttributeValueThread t = new GetAttributeValueThread(categoryVersion, attributeName); try { t.start(); LLValue children; try { children = t.finishUp(); } catch (ManifoldCFException e) { sanityRetryCount = assessRetry(sanityRetryCount,e); continue; } if (children == null) return null; String[] rval = new String[children.size()]; LLValueEnumeration en = children.enumerateValues(); int j = 0; while (en.hasMoreElements()) { LLValue v = (LLValue)en.nextElement(); rval[j] = v.toString(); j++; } return rval; } catch (InterruptedException e) { t.interrupt(); throw new ManifoldCFException("Interrupted: "+e.getMessage(),e,ManifoldCFException.INTERRUPTED); } catch (RuntimeException e) { sanityRetryCount = handleLivelinkRuntimeException(e,sanityRetryCount,true); continue; } } } protected class GetObjectRightsThread extends Thread { protected final int vol; protected final int objID; protected Throwable exception = null; protected LLValue rval = null; public GetObjectRightsThread(int vol, int objID) { super(); setDaemon(true); this.vol = vol; this.objID = objID; } public void run() { try { LLValue childrenObjects = new LLValue(); int status = LLDocs.GetObjectRights(vol, objID, childrenObjects); // If the rights object doesn't exist, behave civilly if (status == 103101) return; if (status != 0) { throw new ManifoldCFException("Error retrieving document rights: "+Integer.toString(status)+": "+llServer.getErrors()); } rval = childrenObjects; } catch (Throwable e) { this.exception = e; } } public LLValue finishUp() throws ManifoldCFException, InterruptedException { join(); Throwable thr = exception; if (thr != null) { if (thr instanceof RuntimeException) throw (RuntimeException)thr; else if (thr instanceof ManifoldCFException) throw (ManifoldCFException)thr; else if (thr instanceof Error) throw (Error)thr; else throw new RuntimeException("Unrecognized exception type: "+thr.getClass().getName()+": "+thr.getMessage(),thr); } return rval; } } /** Get an object's rights. This will be an array of right id's, including the special * ones defined by Livelink, or null will be returned (if the object is not found). *@param vol is the volume id *@param objID is the object id *@return the array. */ protected int[] getObjectRights(int vol, int objID) throws ManifoldCFException, ServiceInterruption { int sanityRetryCount = FAILURE_RETRY_COUNT; while (true) { GetObjectRightsThread t = new GetObjectRightsThread(vol,objID); try { t.start(); LLValue childrenObjects; try { childrenObjects = t.finishUp(); } catch (ManifoldCFException e) { sanityRetryCount = assessRetry(sanityRetryCount,e); continue; } if (childrenObjects == null) return null; int size; if (childrenObjects.isRecord()) size = 1; else if (childrenObjects.isTable()) size = childrenObjects.size(); else size = 0; int minPermission = LAPI_DOCUMENTS.PERM_SEE + LAPI_DOCUMENTS.PERM_SEECONTENTS; int j = 0; int count = 0; while (j < size) { int permission = childrenObjects.toInteger(j, "Permissions"); // Only if the permission is "see contents" can we consider this // access token! if ((permission & minPermission) == minPermission) count++; j++; } int[] rval = new int[count]; j = 0; count = 0; while (j < size) { int token = childrenObjects.toInteger(j, "RightID"); int permission = childrenObjects.toInteger(j, "Permissions"); // Only if the permission is "see contents" can we consider this // access token! if ((permission & minPermission) == minPermission) rval[count++] = token; j++; } return rval; } catch (InterruptedException e) { t.interrupt(); throw new ManifoldCFException("Interrupted: "+e.getMessage(),e,ManifoldCFException.INTERRUPTED); } catch (RuntimeException e) { sanityRetryCount = handleLivelinkRuntimeException(e,sanityRetryCount,true); continue; } } } /** Local cache for various kinds of objects that may be useful more than once. */ protected class LivelinkContext { /** Cache of ObjectInformation objects. */ protected final Map<ObjectInformation,ObjectInformation> objectInfoMap = new HashMap<ObjectInformation,ObjectInformation>(); /** Cache of VersionInformation objects. */ protected final Map<VersionInformation,VersionInformation> versionInfoMap = new HashMap<VersionInformation,VersionInformation>(); /** Cache of UserInformation objects */ protected final Map<UserInformation,UserInformation> userInfoMap = new HashMap<UserInformation,UserInformation>(); public LivelinkContext() { } public ObjectInformation getObjectInformation(int volumeID, int objectID) { ObjectInformation oi = new ObjectInformation(volumeID,objectID); ObjectInformation lookupValue = objectInfoMap.get(oi); if (lookupValue == null) { objectInfoMap.put(oi,oi); return oi; } return lookupValue; } public VersionInformation getVersionInformation(int volumeID, int objectID, int revisionNumber) { VersionInformation vi = new VersionInformation(volumeID,objectID,revisionNumber); VersionInformation lookupValue = versionInfoMap.get(vi); if (lookupValue == null) { versionInfoMap.put(vi,vi); return vi; } return lookupValue; } public UserInformation getUserInformation(int userID) { UserInformation ui = new UserInformation(userID); UserInformation lookupValue = userInfoMap.get(ui); if (lookupValue == null) { userInfoMap.put(ui,ui); return ui; } return lookupValue; } } /** This object represents a cache of user information. * Initialize it with the user ID. Then, request desired fields from it. */ protected class UserInformation { protected final int userID; protected LLValue userValue = null; public UserInformation(int userID) { this.userID = userID; } public boolean exists() throws ServiceInterruption, ManifoldCFException { return getUserValue() != null; } public String getName() throws ServiceInterruption, ManifoldCFException { LLValue userValue = getUserValue(); if (userValue == null) return null; return userValue.toString("NAME"); } protected LLValue getUserValue() throws ServiceInterruption, ManifoldCFException { if (userValue == null) { int sanityRetryCount = FAILURE_RETRY_COUNT; while (true) { GetUserInfoThread t = new GetUserInfoThread(userID); try { t.start(); try { userValue = t.finishUp(); } catch (ManifoldCFException e) { sanityRetryCount = assessRetry(sanityRetryCount,e); continue; } break; } catch (InterruptedException e) { t.interrupt(); throw new ManifoldCFException("Interrupted: "+e.getMessage(),e,ManifoldCFException.INTERRUPTED); } catch (RuntimeException e) { sanityRetryCount = handleLivelinkRuntimeException(e,sanityRetryCount,true); continue; } } } return userValue; } @Override public String toString() { return "("+userID+")"; } @Override public int hashCode() { return (userID << 5) ^ (userID >> 3); } @Override public boolean equals(Object o) { if (!(o instanceof UserInformation)) return false; UserInformation other = (UserInformation)o; return userID == other.userID; } } /** This object represents a cache of version information. * Initialize it with the volume ID and object ID and revision number (usually zero). * Then, request the desired fields from it. */ protected class VersionInformation { protected final int volumeID; protected final int objectID; protected final int revisionNumber; protected LLValue versionValue = null; public VersionInformation(int volumeID, int objectID, int revisionNumber) { this.volumeID = volumeID; this.objectID = objectID; this.revisionNumber = revisionNumber; } public boolean exists() throws ServiceInterruption, ManifoldCFException { return getVersionValue() != null; } /** Get data size. */ public Long getDataSize() throws ServiceInterruption, ManifoldCFException { LLValue elem = getVersionValue(); if (elem == null) return null; return new Long(elem.toLong("FILEDATASIZE")); } /** Get file name. */ public String getFileName() throws ServiceInterruption, ManifoldCFException { LLValue elem = getVersionValue(); if (elem == null) return null; return elem.toString("FILENAME"); } /** Get mime type. */ public String getMimeType() throws ServiceInterruption, ManifoldCFException { LLValue elem = getVersionValue(); if (elem == null) return null; return elem.toString("MIMETYPE"); } /** Get modify date. */ public Date getModifyDate() throws ServiceInterruption, ManifoldCFException { LLValue elem = getVersionValue(); if (elem == null) return null; return elem.toDate("MODIFYDATE"); } /** Get modifier. */ public Integer getOwnerId() throws ServiceInterruption, ManifoldCFException { LLValue elem = getVersionValue(); if (elem == null) return null; return new Integer(elem.toInteger("OWNER")); } /** Get version LLValue */ protected LLValue getVersionValue() throws ServiceInterruption, ManifoldCFException { if (versionValue == null) { int sanityRetryCount = FAILURE_RETRY_COUNT; while (true) { GetVersionInfoThread t = new GetVersionInfoThread(volumeID,objectID,revisionNumber); try { t.start(); try { versionValue = t.finishUp(); } catch (ManifoldCFException e) { sanityRetryCount = assessRetry(sanityRetryCount,e); continue; } break; } catch (InterruptedException e) { t.interrupt(); throw new ManifoldCFException("Interrupted: "+e.getMessage(),e,ManifoldCFException.INTERRUPTED); } catch (RuntimeException e) { sanityRetryCount = handleLivelinkRuntimeException(e,sanityRetryCount,true); continue; } } } return versionValue; } @Override public int hashCode() { return (volumeID << 5) ^ (volumeID >> 3) ^ (objectID << 5) ^ (objectID >> 3) ^ (revisionNumber << 5) ^ (revisionNumber >> 3); } @Override public boolean equals(Object o) { if (!(o instanceof VersionInformation)) return false; VersionInformation other = (VersionInformation)o; return volumeID == other.volumeID && objectID == other.objectID && revisionNumber == other.revisionNumber; } } /** This object represents an object information cache. * Initialize it with the volume ID and object ID, and then request * the appropriate fields from it. Keep it around as long as needed; it functions as a cache * of sorts... */ protected class ObjectInformation { protected final int volumeID; protected final int objectID; protected LLValue objectValue = null; public ObjectInformation(int volumeID, int objectID) { this.volumeID = volumeID; this.objectID = objectID; } /** * Check whether object seems to exist or not. */ public boolean exists() throws ServiceInterruption, ManifoldCFException { return getObjectValue() != null; } /** Check if this object is the category workspace. */ public boolean isCategoryWorkspace() { return objectID == LLCATWK_ID; } /** Check if this object is the entity workspace. */ public boolean isEntityWorkspace() { return objectID == LLENTWK_ID; } /** toString override */ @Override public String toString() { return "(Volume: "+volumeID+", Object: "+objectID+")"; } /** * Returns the object ID specified by the path name. * @param startPath is the folder name (a string with dots as separators) */ public VolumeAndId getPathId(String startPath) throws ServiceInterruption, ManifoldCFException { LLValue objInfo = getObjectValue(); if (objInfo == null) return null; // Grab the volume ID and starting object int obj = objInfo.toInteger("ID"); int vol = objInfo.toInteger("VolumeID"); // Pick apart the start path. This is a string separated by slashes. int charindex = 0; while (charindex < startPath.length()) { StringBuilder currentTokenBuffer = new StringBuilder(); // Find the current token while (charindex < startPath.length()) { char x = startPath.charAt(charindex++); if (x == '/') break; if (x == '\\') { // Attempt to escape what follows x = startPath.charAt(charindex); charindex++; } currentTokenBuffer.append(x); } String subFolder = currentTokenBuffer.toString(); // We want only folders that are children of the current object and which match the specified subfolder String filterString = "(SubType="+ LAPI_DOCUMENTS.FOLDERSUBTYPE + " or SubType=" + LAPI_DOCUMENTS.PROJECTSUBTYPE + " or SubType=" + LAPI_DOCUMENTS.COMPOUNDDOCUMENTSUBTYPE + ") and Name='" + subFolder + "'"; int sanityRetryCount = FAILURE_RETRY_COUNT; while (true) { ListObjectsThread t = new ListObjectsThread(vol,obj,filterString); try { t.start(); LLValue children; try { children = t.finishUp(); } catch (ManifoldCFException e) { sanityRetryCount = assessRetry(sanityRetryCount,e); continue; } if (children == null) return null; // If there is one child, then we are okay. if (children.size() == 1) { // New starting point is the one we found. obj = children.toInteger(0, "ID"); int subtype = children.toInteger(0, "SubType"); if (subtype == LAPI_DOCUMENTS.PROJECTSUBTYPE) { vol = obj; obj = -obj; } } else { // Couldn't find the path. Instead of throwing up, return null to indicate // illegal node. return null; } break; } catch (InterruptedException e) { t.interrupt(); throw new ManifoldCFException("Interrupted: "+e.getMessage(),e,ManifoldCFException.INTERRUPTED); } catch (RuntimeException e) { sanityRetryCount = handleLivelinkRuntimeException(e,sanityRetryCount,true); continue; } } } return new VolumeAndId(vol,obj); } /** * Returns the category ID specified by the path name. * @param startPath is the folder name, ending in a category name (a string with slashes as separators) */ public int getCategoryId(String startPath) throws ManifoldCFException, ServiceInterruption { LLValue objInfo = getObjectValue(); if (objInfo == null) return -1; // Grab the volume ID and starting object int obj = objInfo.toInteger("ID"); int vol = objInfo.toInteger("VolumeID"); // Pick apart the start path. This is a string separated by slashes. if (startPath.length() == 0) return -1; int charindex = 0; while (charindex < startPath.length()) { StringBuilder currentTokenBuffer = new StringBuilder(); // Find the current token while (charindex < startPath.length()) { char x = startPath.charAt(charindex++); if (x == '/') break; if (x == '\\') { // Attempt to escape what follows x = startPath.charAt(charindex); charindex++; } currentTokenBuffer.append(x); } String subFolder = currentTokenBuffer.toString(); String filterString; // We want only folders that are children of the current object and which match the specified subfolder if (charindex < startPath.length()) filterString = "(SubType="+ LAPI_DOCUMENTS.FOLDERSUBTYPE + " or SubType=" + LAPI_DOCUMENTS.PROJECTSUBTYPE + " or SubType=" + LAPI_DOCUMENTS.COMPOUNDDOCUMENTSUBTYPE + ")"; else filterString = "SubType="+LAPI_DOCUMENTS.CATEGORYSUBTYPE; filterString += " and Name='" + subFolder + "'"; int sanityRetryCount = FAILURE_RETRY_COUNT; while (true) { ListObjectsThread t = new ListObjectsThread(vol,obj,filterString); try { t.start(); LLValue children; try { children = t.finishUp(); } catch (ManifoldCFException e) { sanityRetryCount = assessRetry(sanityRetryCount,e); continue; } if (children == null) return -1; // If there is one child, then we are okay. if (children.size() == 1) { // New starting point is the one we found. obj = children.toInteger(0, "ID"); int subtype = children.toInteger(0, "SubType"); if (subtype == LAPI_DOCUMENTS.PROJECTSUBTYPE) { vol = obj; obj = -obj; } } else { // Couldn't find the path. Instead of throwing up, return null to indicate // illegal node. return -1; } break; } catch (InterruptedException e) { t.interrupt(); throw new ManifoldCFException("Interrupted: "+e.getMessage(),e,ManifoldCFException.INTERRUPTED); } catch (RuntimeException e) { sanityRetryCount = handleLivelinkRuntimeException(e,sanityRetryCount,true); continue; } } } return obj; } /** Get permissions. */ public Integer getPermissions() throws ServiceInterruption, ManifoldCFException { LLValue elem = getObjectValue(); if (elem == null) return null; return new Integer(objectValue.toInteger("Permissions")); } /** Get OpenText document name. */ public String getName() throws ServiceInterruption, ManifoldCFException { LLValue elem = getObjectValue(); if (elem == null) return null; return elem.toString("NAME"); } /** Get OpenText comments/description. */ public String getComments() throws ServiceInterruption, ManifoldCFException { LLValue elem = getObjectValue(); if (elem == null) return null; return elem.toString("COMMENT"); } /** Get parent ID. */ public Integer getParentId() throws ServiceInterruption, ManifoldCFException { LLValue elem = getObjectValue(); if (elem == null) return null; return new Integer(elem.toInteger("ParentId")); } /** Get owner ID. */ public Integer getOwnerId() throws ServiceInterruption, ManifoldCFException { LLValue elem = getObjectValue(); if (elem == null) return null; return new Integer(elem.toInteger("UserId")); } /** Get group ID. */ public Integer getGroupId() throws ServiceInterruption, ManifoldCFException { LLValue elem = getObjectValue(); if (elem == null) return null; return new Integer(elem.toInteger("GroupId")); } /** Get creation date. */ public Date getCreationDate() throws ServiceInterruption, ManifoldCFException { LLValue elem = getObjectValue(); if (elem == null) return null; return elem.toDate("CREATEDATE"); } /** Get creator ID. */ public Integer getCreatorId() throws ServiceInterruption, ManifoldCFException { LLValue elem = getObjectValue(); if (elem == null) return null; return new Integer(elem.toInteger("CREATEDBY")); } /* Get modify date. */ public Date getModifyDate() throws ServiceInterruption, ManifoldCFException { LLValue elem = getObjectValue(); if (elem == null) return null; return elem.toDate("ModifyDate"); } /** Get the objInfo object. */ protected LLValue getObjectValue() throws ServiceInterruption, ManifoldCFException { if (objectValue == null) { int sanityRetryCount = FAILURE_RETRY_COUNT; while (true) { GetObjectInfoThread t = new GetObjectInfoThread(volumeID,objectID); try { t.start(); try { objectValue = t.finishUp(); } catch (ManifoldCFException e) { sanityRetryCount = assessRetry(sanityRetryCount,e); continue; } break; } catch (InterruptedException e) { t.interrupt(); throw new ManifoldCFException("Interrupted: "+e.getMessage(),e,ManifoldCFException.INTERRUPTED); } catch (RuntimeException e) { sanityRetryCount = handleLivelinkRuntimeException(e,sanityRetryCount,true); continue; } } } return objectValue; } @Override public int hashCode() { return (volumeID << 5) ^ (volumeID >> 3) ^ (objectID << 5) ^ (objectID >> 3); } @Override public boolean equals(Object o) { if (!(o instanceof ObjectInformation)) return false; ObjectInformation other = (ObjectInformation)o; return volumeID == other.volumeID && objectID == other.objectID; } } /** Thread we can abandon that lists all users (except admin). */ protected class ListUsersThread extends Thread { protected LLValue rval = null; protected Throwable exception = null; public ListUsersThread() { super(); setDaemon(true); } public void run() { try { LLValue userList = new LLValue(); int status = LLUsers.ListUsers(userList); if (Logging.connectors.isDebugEnabled()) { Logging.connectors.debug("Livelink: User list retrieved: status="+Integer.toString(status)); } if (status < 0) { Logging.connectors.debug("Livelink: User list inaccessable ("+llServer.getErrors()+")"); return; } if (status != 0) { throw new ManifoldCFException("Error retrieving user list: status="+Integer.toString(status)+" ("+llServer.getErrors()+")"); } rval = userList; } catch (Throwable e) { this.exception = e; } } public LLValue finishUp() throws ManifoldCFException, InterruptedException { join(); Throwable thr = exception; if (thr != null) { if (thr instanceof RuntimeException) throw (RuntimeException)thr; else if (thr instanceof ManifoldCFException) throw (ManifoldCFException)thr; else if (thr instanceof Error) throw (Error)thr; else throw new RuntimeException("Unrecognized exception type: "+thr.getClass().getName()+": "+thr.getMessage(),thr); } return rval; } } /** Thread we can abandon that gets user information for a userID. */ protected class GetUserInfoThread extends Thread { protected final int user; protected Throwable exception = null; protected LLValue rval = null; public GetUserInfoThread(int user) { super(); setDaemon(true); this.user = user; } public void run() { try { LLValue userinfo = new LLValue().setAssoc(); int status = LLUsers.GetUserByID(user,userinfo); // Need to detect if object was deleted, and return null in this case!!! if (Logging.connectors.isDebugEnabled()) { Logging.connectors.debug("Livelink: User status retrieved for "+Integer.toString(user)+": status="+Integer.toString(status)); } // Treat both 103101 and 103102 as 'object not found'. 401101 is 'user not found'. if (status == 103101 || status == 103102 || status == 401101) return; // This error means we don't have permission to get the object's status, apparently if (status < 0) { Logging.connectors.debug("Livelink: User info inaccessable for user "+Integer.toString(user)+ " ("+llServer.getErrors()+")"); return; } if (status != 0) { throw new ManifoldCFException("Error retrieving user "+Integer.toString(user)+": status="+Integer.toString(status)+" ("+llServer.getErrors()+")"); } rval = userinfo; } catch (Throwable e) { this.exception = e; } } public LLValue finishUp() throws ManifoldCFException, InterruptedException { join(); Throwable thr = exception; if (thr != null) { if (thr instanceof RuntimeException) throw (RuntimeException)thr; else if (thr instanceof ManifoldCFException) throw (ManifoldCFException)thr; else if (thr instanceof Error) throw (Error)thr; else throw new RuntimeException("Unrecognized exception type: "+thr.getClass().getName()+": "+thr.getMessage(),thr); } return rval; } } /** Thread we can abandon that gets version information for a volume and an id and a revision. */ protected class GetVersionInfoThread extends Thread { protected final int vol; protected final int id; protected final int revNumber; protected Throwable exception = null; protected LLValue rval = null; public GetVersionInfoThread(int vol, int id, int revNumber) { super(); setDaemon(true); this.vol = vol; this.id = id; this.revNumber = revNumber; } public void run() { try { LLValue versioninfo = new LLValue().setAssocNotSet(); int status = LLDocs.GetVersionInfo(vol,id,revNumber,versioninfo); // Need to detect if object was deleted, and return null in this case!!! if (Logging.connectors.isDebugEnabled()) { Logging.connectors.debug("Livelink: Version status retrieved for "+Integer.toString(vol)+":"+Integer.toString(id)+", rev "+revNumber+": status="+Integer.toString(status)); } // Treat both 103101 and 103102 as 'object not found'. if (status == 103101 || status == 103102) return; // This error means we don't have permission to get the object's status, apparently if (status < 0) { Logging.connectors.debug("Livelink: Version info inaccessable for object "+Integer.toString(vol)+":"+Integer.toString(id)+", rev "+revNumber+ " ("+llServer.getErrors()+")"); return; } if (status != 0) { throw new ManifoldCFException("Error retrieving document version "+Integer.toString(vol)+":"+Integer.toString(id)+", rev "+revNumber+": status="+Integer.toString(status)+" ("+llServer.getErrors()+")"); } rval = versioninfo; } catch (Throwable e) { this.exception = e; } } public LLValue finishUp() throws ManifoldCFException, InterruptedException { join(); Throwable thr = exception; if (thr != null) { if (thr instanceof RuntimeException) throw (RuntimeException)thr; else if (thr instanceof ManifoldCFException) throw (ManifoldCFException)thr; else if (thr instanceof Error) throw (Error)thr; else throw new RuntimeException("Unrecognized exception type: "+thr.getClass().getName()+": "+thr.getMessage(),thr); } return rval; } } /** Thread we can abandon that gets object information for a volume and an id. */ protected class GetObjectInfoThread extends Thread { protected int vol; protected int id; protected Throwable exception = null; protected LLValue rval = null; public GetObjectInfoThread(int vol, int id) { super(); setDaemon(true); this.vol = vol; this.id = id; } public void run() { try { LLValue objinfo = new LLValue().setAssocNotSet(); int status = LLDocs.GetObjectInfo(vol,id,objinfo); // Need to detect if object was deleted, and return null in this case!!! if (Logging.connectors.isDebugEnabled()) { Logging.connectors.debug("Livelink: Status retrieved for "+Integer.toString(vol)+":"+Integer.toString(id)+": status="+Integer.toString(status)); } // Treat both 103101 and 103102 as 'object not found'. if (status == 103101 || status == 103102) return; // This error means we don't have permission to get the object's status, apparently if (status < 0) { Logging.connectors.debug("Livelink: Object info inaccessable for object "+Integer.toString(vol)+":"+Integer.toString(id)+ " ("+llServer.getErrors()+")"); return; } if (status != 0) { throw new ManifoldCFException("Error retrieving document object "+Integer.toString(vol)+":"+Integer.toString(id)+": status="+Integer.toString(status)+" ("+llServer.getErrors()+")"); } rval = objinfo; } catch (Throwable e) { this.exception = e; } } public LLValue finishUp() throws ManifoldCFException, InterruptedException { join(); Throwable thr = exception; if (thr != null) { if (thr instanceof RuntimeException) throw (RuntimeException)thr; else if (thr instanceof ManifoldCFException) throw (ManifoldCFException)thr; else if (thr instanceof Error) throw (Error)thr; else throw new RuntimeException("Unrecognized exception type: "+thr.getClass().getName()+": "+thr.getMessage(),thr); } return rval; } } /** Build a set of actual acls given a set of rights */ protected String[] lookupTokens(int[] rights, ObjectInformation objInfo) throws ManifoldCFException, ServiceInterruption { if (!objInfo.exists()) return null; String[] convertedAcls = new String[rights.length]; LLValue infoObject = null; int j = 0; int k = 0; while (j < rights.length) { int token = rights[j++]; String tokenValue; // Consider this token switch (token) { case LAPI_DOCUMENTS.RIGHT_OWNER: // Look up user for current document (UserID attribute) tokenValue = objInfo.getOwnerId().toString(); break; case LAPI_DOCUMENTS.RIGHT_GROUP: tokenValue = objInfo.getGroupId().toString(); break; case LAPI_DOCUMENTS.RIGHT_WORLD: // Add "Guest" token tokenValue = "GUEST"; break; case LAPI_DOCUMENTS.RIGHT_SYSTEM: // Add "System" token tokenValue = "SYSTEM"; break; default: tokenValue = Integer.toString(token); break; } // This might return a null if we could not look up the object corresponding to the right. If so, it is safe to skip it because // that always RESTRICTS view of the object (maybe erroneously), but does not expand visibility. if (tokenValue != null) convertedAcls[k++] = tokenValue; } String[] actualAcls = new String[k]; j = 0; while (j < k) { actualAcls[j] = convertedAcls[j]; j++; } return actualAcls; } protected class GetObjectCategoryIDsThread extends Thread { protected final int vol; protected final int id; protected Throwable exception = null; protected LLValue rval = null; public GetObjectCategoryIDsThread(int vol, int id) { super(); setDaemon(true); this.vol = vol; this.id = id; } public void run() { try { // Object ID LLValue objIDValue = new LLValue().setAssocNotSet(); objIDValue.add("ID", id); // Category ID List LLValue catIDList = new LLValue().setAssocNotSet(); int status = LLDocs.ListObjectCategoryIDs(objIDValue,catIDList); // Need to detect if object was deleted, and return null in this case!!! if (Logging.connectors.isDebugEnabled()) { Logging.connectors.debug("Livelink: Status value for getting object categories for "+Integer.toString(vol)+":"+Integer.toString(id)+" is: "+Integer.toString(status)); } if (status == 103101) return; if (status != 0) { throw new ManifoldCFException("Error retrieving document categories for "+Integer.toString(vol)+":"+Integer.toString(id)+": status="+Integer.toString(status)+" ("+llServer.getErrors()+")"); } rval = catIDList; } catch (Throwable e) { this.exception = e; } } public LLValue finishUp() throws ManifoldCFException, InterruptedException { join(); Throwable thr = exception; if (thr != null) { if (thr instanceof RuntimeException) throw (RuntimeException)thr; else if (thr instanceof ManifoldCFException) throw (ManifoldCFException)thr; else if (thr instanceof Error) throw (Error)thr; else throw new RuntimeException("Unrecognized exception type: "+thr.getClass().getName()+": "+thr.getMessage(),thr); } return rval; } } /** Get category IDs associated with an object. * @param vol is the volume ID * @param id the object ID * @return an array of integers containing category identifiers, or null if the object is not found. */ protected int[] getObjectCategoryIDs(int vol, int id) throws ManifoldCFException, ServiceInterruption { int sanityRetryCount = FAILURE_RETRY_COUNT; while (true) { GetObjectCategoryIDsThread t = new GetObjectCategoryIDsThread(vol,id); try { t.start(); LLValue catIDList; try { catIDList = t.finishUp(); } catch (ManifoldCFException e) { sanityRetryCount = assessRetry(sanityRetryCount,e); continue; } if (catIDList == null) return null; int size = catIDList.size(); if (Logging.connectors.isDebugEnabled()) { Logging.connectors.debug("Livelink: Object "+Integer.toString(vol)+":"+Integer.toString(id)+" has "+Integer.toString(size)+" attached categories"); } // Count the category ids int count = 0; int j = 0; while (j < size) { int type = catIDList.toValue(j).toInteger("Type"); if (type == LAPI_ATTRIBUTES.CATEGORY_TYPE_LIBRARY) count++; j++; } int[] rval = new int[count]; // Do the scan j = 0; count = 0; while (j < size) { int type = catIDList.toValue(j).toInteger("Type"); if (type == LAPI_ATTRIBUTES.CATEGORY_TYPE_LIBRARY) { int childID = catIDList.toValue(j).toInteger("ID"); rval[count++] = childID; } j++; } if (Logging.connectors.isDebugEnabled()) { Logging.connectors.debug("Livelink: Object "+Integer.toString(vol)+":"+Integer.toString(id)+" has "+Integer.toString(rval.length)+" attached library categories"); } return rval; } catch (InterruptedException e) { t.interrupt(); throw new ManifoldCFException("Interrupted: "+e.getMessage(),e,ManifoldCFException.INTERRUPTED); } catch (RuntimeException e) { sanityRetryCount = handleLivelinkRuntimeException(e,sanityRetryCount,true); continue; } } } /** RootValue version of getPathId. */ protected VolumeAndId getPathId(RootValue rv) throws ManifoldCFException, ServiceInterruption { return rv.getRootValue().getPathId(rv.getRemainderPath()); } /** Rootvalue version of getCategoryId. */ protected int getCategoryId(RootValue rv) throws ManifoldCFException, ServiceInterruption { return rv.getRootValue().getCategoryId(rv.getRemainderPath()); } // Protected static methods /** Check if a file or directory should be included, given a document specification. *@param filename is the name of the "file". *@param documentSpecification is the specification. *@return true if it should be included. */ protected static boolean checkInclude(String filename, Specification documentSpecification) throws ManifoldCFException { // Scan includes to insure we match int i = 0; while (i < documentSpecification.getChildCount()) { SpecificationNode sn = documentSpecification.getChild(i); if (sn.getType().equals("include")) { String filespec = sn.getAttributeValue("filespec"); // If it matches, we can exit this loop. if (checkMatch(filename,0,filespec)) break; } i++; } if (i == documentSpecification.getChildCount()) return false; // We matched an include. Now, scan excludes to ditch it if needed. i = 0; while (i < documentSpecification.getChildCount()) { SpecificationNode sn = documentSpecification.getChild(i); if (sn.getType().equals("exclude")) { String filespec = sn.getAttributeValue("filespec"); // If it matches, we return false. if (checkMatch(filename,0,filespec)) return false; } i++; } // System.out.println("Match!"); return true; } /** Check if a file should be ingested, given a document specification. It is presumed that * documents that pass checkInclude() will be checked with this method. *@param objID is the file ID. *@param documentSpecification is the specification. */ protected boolean checkIngest(LivelinkContext llc, int objID, Specification documentSpecification) throws ManifoldCFException { // Since the only exclusions at this point are not based on file contents, this is a no-op. return true; } /** Check a match between two strings with wildcards. *@param sourceMatch is the expanded string (no wildcards) *@param sourceIndex is the starting point in the expanded string. *@param match is the wildcard-based string. *@return true if there is a match. */ protected static boolean checkMatch(String sourceMatch, int sourceIndex, String match) { // Note: The java regex stuff looks pretty heavyweight for this purpose. // I've opted to try and do a simple recursive version myself, which is not compiled. // Basically, the match proceeds by recursive descent through the string, so that all *'s cause // recursion. boolean caseSensitive = false; return processCheck(caseSensitive, sourceMatch, sourceIndex, match, 0); } /** Recursive worker method for checkMatch. Returns 'true' if there is a path that consumes both * strings in their entirety in a matched way. *@param caseSensitive is true if file names are case sensitive. *@param sourceMatch is the source string (w/o wildcards) *@param sourceIndex is the current point in the source string. *@param match is the match string (w/wildcards) *@param matchIndex is the current point in the match string. *@return true if there is a match. */ protected static boolean processCheck(boolean caseSensitive, String sourceMatch, int sourceIndex, String match, int matchIndex) { // Logging.connectors.debug("Matching '"+sourceMatch+"' position "+Integer.toString(sourceIndex)+ // " against '"+match+"' position "+Integer.toString(matchIndex)); // Match up through the next * we encounter while (true) { // If we've reached the end, it's a match. if (sourceMatch.length() == sourceIndex && match.length() == matchIndex) return true; // If one has reached the end but the other hasn't, no match if (match.length() == matchIndex) return false; if (sourceMatch.length() == sourceIndex) { if (match.charAt(matchIndex) != '*') return false; matchIndex++; continue; } char x = sourceMatch.charAt(sourceIndex); char y = match.charAt(matchIndex); if (!caseSensitive) { if (x >= 'A' && x <= 'Z') x -= 'A'-'a'; if (y >= 'A' && y <= 'Z') y -= 'A'-'a'; } if (y == '*') { // Wildcard! // We will recurse at this point. // Basically, we want to combine the results for leaving the "*" in the match string // at this point and advancing the source index, with skipping the "*" and leaving the source // string alone. return processCheck(caseSensitive,sourceMatch,sourceIndex+1,match,matchIndex) || processCheck(caseSensitive,sourceMatch,sourceIndex,match,matchIndex+1); } if (y == '?' || x == y) { sourceIndex++; matchIndex++; } else return false; } } /** Class for returning volume id/folder id combination on path lookup. */ protected static class VolumeAndId { protected final int volumeID; protected final int folderID; public VolumeAndId(int volumeID, int folderID) { this.volumeID = volumeID; this.folderID = folderID; } public int getVolumeID() { return volumeID; } public int getPathId() { return folderID; } } /** Class that describes a metadata catid and path. */ protected static class MetadataPathItem { protected final int catID; protected final String catName; /** Constructor. */ public MetadataPathItem(int catID, String catName) { this.catID = catID; this.catName = catName; } /** Get the cat ID. *@return the id. */ public int getCatID() { return catID; } /** Get the cat name. *@return the category name path. */ public String getCatName() { return catName; } } /** Class that describes a metadata catid and attribute set. */ protected static class MetadataItem { protected final MetadataPathItem pathItem; protected final Set<String> attributeNames = new HashSet<String>(); /** Constructor. */ public MetadataItem(MetadataPathItem pathItem) { this.pathItem = pathItem; } /** Add an attribute name. */ public void addAttribute(String attributeName) { attributeNames.add(attributeName); } /** Get the path object. *@return the object. */ public MetadataPathItem getPathItem() { return pathItem; } /** Get an iterator over the attribute names. *@return the iterator. */ public Iterator<String> getAttributeNames() { return attributeNames.iterator(); } } /** Class that tracks paths associated with nodes, and also keeps track of the name * of the metadata attribute to use for the path. */ protected class SystemMetadataDescription { // The livelink context protected final LivelinkContext llc; // The path attribute name protected final String pathAttributeName; // The path separator protected final String pathSeparator; // The node ID to path name mapping (which acts like a cache) protected final Map<String,String> pathMap = new HashMap<String,String>(); // The path name map protected final MatchMap matchMap = new MatchMap(); // Acls protected final Set<String> aclMap = new HashSet<String>(); protected final boolean securityOn; // Filter string protected final String filterString; protected final Set<String> holder = new HashSet<String>(); protected final boolean includeAllMetadata; /** Constructor */ public SystemMetadataDescription(LivelinkContext llc, Specification spec) throws ManifoldCFException, ServiceInterruption { this.llc = llc; String pathAttributeName = null; String pathSeparator = null; boolean securityOn = true; StringBuilder fsb = new StringBuilder(); boolean first = true; boolean includeAllMetadata = false; for (int i = 0; i < spec.getChildCount(); i++) { SpecificationNode n = spec.getChild(i); if (n.getType().equals("pathnameattribute")) { pathAttributeName = n.getAttributeValue("value"); pathSeparator = n.getAttributeValue("separator"); if (pathSeparator == null) pathSeparator = "/"; } else if (n.getType().equals("pathmap")) { String pathMatch = n.getAttributeValue("match"); String pathReplace = n.getAttributeValue("replace"); matchMap.appendMatchPair(pathMatch,pathReplace); } else if (n.getType().equals("access")) { String token = n.getAttributeValue("token"); aclMap.add(token); } else if (n.getType().equals("security")) { String value = n.getAttributeValue("value"); if (value.equals("on")) securityOn = true; else if (value.equals("off")) securityOn = false; } else if (n.getType().equals("include")) { String includeMatch = n.getAttributeValue("filespec"); if (includeMatch != null) { // Peel off the extension int index = includeMatch.lastIndexOf("."); if (index != -1) { String type = includeMatch.substring(index+1).toLowerCase().replace('*','%'); if (first) first = false; else fsb.append(" or "); fsb.append("lower(FileType) like '").append(type).append("'"); } } } else if (n.getType().equals("allmetadata")) { String isAll = n.getAttributeValue("all"); if (isAll != null && isAll.equals("true")) includeAllMetadata = true; } else if (n.getType().equals("metadata")) { String category = n.getAttributeValue("category"); String attributeName = n.getAttributeValue("attribute"); String isAll = n.getAttributeValue("all"); if (isAll != null && isAll.equals("true")) { // Locate all metadata items for the specified category path, // and enter them into the array getSession(); String[] attrs = getCategoryAttributes(llc,category); if (attrs != null) { int j = 0; while (j < attrs.length) { attributeName = attrs[j++]; String metadataName = packCategoryAttribute(category,attributeName); holder.add(metadataName); } } } else { String metadataName = packCategoryAttribute(category,attributeName); holder.add(metadataName); } } } this.includeAllMetadata = includeAllMetadata; this.pathAttributeName = pathAttributeName; this.pathSeparator = pathSeparator; this.securityOn = securityOn; String filterStringPiece = fsb.toString(); if (filterStringPiece.length() == 0) this.filterString = "0>1"; else { StringBuilder sb = new StringBuilder(); sb.append("SubType=").append(new Integer(LAPI_DOCUMENTS.FOLDERSUBTYPE).toString()); sb.append(" or SubType=").append(new Integer(LAPI_DOCUMENTS.COMPOUNDDOCUMENTSUBTYPE).toString()); sb.append(" or SubType=").append(new Integer(LAPI_DOCUMENTS.PROJECTSUBTYPE).toString()); sb.append(" or (SubType=").append(new Integer(LAPI_DOCUMENTS.DOCUMENTSUBTYPE).toString()); sb.append(" and ("); // Walk through the document spec to find the documents that match under the specified root // include lower(column)=spec sb.append(filterStringPiece); sb.append("))"); this.filterString = sb.toString(); } } public boolean includeAllMetadata() { return includeAllMetadata; } public String[] getMetadataAttributes() { // Put into an array String[] specifiedMetadataAttributes = new String[holder.size()]; int i = 0; for (String attrName : holder) { specifiedMetadataAttributes[i++] = attrName; } return specifiedMetadataAttributes; } public String getFilterString() { return filterString; } public String[] getAcls() { if (!securityOn) return null; String[] rval = new String[aclMap.size()]; int i = 0; for (String token : aclMap) { rval[i++] = token; } return rval; } /** Get the path attribute name. *@return the path attribute name, or null if none specified. */ public String getPathAttributeName() { return pathAttributeName; } /** Get the path separator. */ public String getPathSeparator() { return pathSeparator; } /** Given an identifier, get the translated string that goes into the metadata. */ public String getPathAttributeValue(String documentIdentifier) throws ManifoldCFException, ServiceInterruption { String path = getNodePathString(documentIdentifier); if (path == null) return null; return matchMap.translate(path); } /** Get the matchmap string. */ public String getMatchMapString() { return matchMap.toString(); } /** For a given node, get its path. */ public String getNodePathString(String documentIdentifier) throws ManifoldCFException, ServiceInterruption { if (Logging.connectors.isDebugEnabled()) Logging.connectors.debug("Looking up path for '"+documentIdentifier+"'"); String path = pathMap.get(documentIdentifier); if (path == null) { // Not yet present. Look it up, recursively String identifierPart = documentIdentifier; // Get the current node's name first // D = Document; anything else = Folder if (identifierPart.startsWith("D") || identifierPart.startsWith("F")) { // Strip off the letter identifierPart = identifierPart.substring(1); } // See if there's a volume label; if not, use the default. int colonPosition = identifierPart.indexOf(":"); int volumeID; int objectID; try { if (colonPosition == -1) { // Default volume ID volumeID = LLENTWK_VOL; objectID = Integer.parseInt(identifierPart); } else { volumeID = Integer.parseInt(identifierPart.substring(0,colonPosition)); objectID = Integer.parseInt(identifierPart.substring(colonPosition+1)); } } catch (NumberFormatException e) { throw new ManifoldCFException("Bad document identifier: "+e.getMessage(),e); } ObjectInformation objInfo = llc.getObjectInformation(volumeID,objectID); if (!objInfo.exists()) { // The document identifier describes a path that does not exist. // This is unexpected, but don't die: just log a warning and allow the higher level to deal with it. Logging.connectors.warn("Livelink: Bad document identifier: '"+documentIdentifier+"' apparently does not exist, but need to find its path"); return null; } // Get the name attribute String name = objInfo.getName(); // Get the parentID attribute int parentID = objInfo.getParentId().intValue(); if (parentID == -1) path = name; else { String parentIdentifier = "F"+Integer.toString(volumeID)+":"+Integer.toString(parentID); String parentPath = getNodePathString(parentIdentifier); if (parentPath == null) return null; path = parentPath + pathSeparator + name; } pathMap.put(documentIdentifier,path); } return path; } } /** Class that manages to find catid's and attribute names that have been specified. * This accepts a part of the version string which contains the string-ified metadata * spec, rather than pulling it out of the document specification. That guarantees that * the version string actually corresponds to the document that was ingested. */ protected class MetadataDescription { protected final LivelinkContext llc; // This is a map of category name to category ID and attributes protected final Map<String,MetadataPathItem> categoryMap = new HashMap<String,MetadataPathItem>(); /** Constructor. */ public MetadataDescription(LivelinkContext llc) { this.llc = llc; } /** Iterate over the metadata items represented by the specified chunk of version string. *@return an iterator over MetadataItem objects. */ public Iterator<MetadataItem> getItems(String[] metadataItems) throws ManifoldCFException, ServiceInterruption { // This is the map that will be iterated over for a return value. // It gets built out of (hopefully cached) data from categoryMap. Map<String,MetadataItem> newMap = new HashMap<String,MetadataItem>(); // Start at root ObjectInformation rootValue = null; // Walk through string and process each metadata element in turn. for (String metadataSpec : metadataItems) { StringBuilder categoryBuffer = new StringBuilder(); StringBuilder attributeBuffer = new StringBuilder(); unpackCategoryAttribute(categoryBuffer,attributeBuffer,metadataSpec); String category = categoryBuffer.toString(); String attributeName = attributeBuffer.toString(); // If there's already an entry for this category in the return map, use it MetadataItem mi = newMap.get(category); if (mi == null) { // Now, look up the node information // Convert category to cat id. MetadataPathItem item = categoryMap.get(category); if (item == null) { RootValue rv = new RootValue(llc,category); if (rootValue == null) { rootValue = rv.getRootValue(); } // Get the object id of the category the path describes. // NOTE: We don't use the RootValue version of getCategoryId because // we want to use the cached value of rootValue, if it was around. int catObjectID = rootValue.getCategoryId(rv.getRemainderPath()); if (catObjectID != -1) { item = new MetadataPathItem(catObjectID,rv.getRemainderPath()); categoryMap.put(category,item); } } mi = new MetadataItem(item); newMap.put(category,mi); } // Add attribute name to category mi.addAttribute(attributeName); } return newMap.values().iterator(); } } /** This class caches the category path strings associated with a given category object identifier. * The goal is to allow reasonably speedy lookup of the path name, so we can put it into the metadata part of the * version string. */ protected class CategoryPathAccumulator { // Livelink context protected final LivelinkContext llc; // This is the map from category ID to category path name. // It's keyed by an Integer formed from the id, and has String values. protected final Map<Integer,String> categoryPathMap = new HashMap<Integer,String>(); // This is the map from category ID to attribute names. Keyed // by an Integer formed from the id, and has a String[] value. protected final Map<Integer,String[]> attributeMap = new HashMap<Integer,String[]>(); /** Constructor */ public CategoryPathAccumulator(LivelinkContext llc) { this.llc = llc; } /** Get a specified set of packed category paths with attribute names, given the category identifiers */ public String[] getCategoryPathsAttributeNames(int[] catIDs) throws ManifoldCFException, ServiceInterruption { Set<String> set = new HashSet<String>(); for (int x : catIDs) { Integer key = new Integer(x); String pathValue = categoryPathMap.get(key); if (pathValue == null) { // Chase the path back up the chain pathValue = findPath(key.intValue()); if (pathValue == null) continue; categoryPathMap.put(key,pathValue); } String[] attributeNames = attributeMap.get(key); if (attributeNames == null) { // Get the attributes for this category attributeNames = findAttributes(key.intValue()); if (attributeNames == null) continue; attributeMap.put(key,attributeNames); } // Now, put the path and the attributes into the hash. for (String attributeName : attributeNames) { String metadataName = packCategoryAttribute(pathValue,attributeName); set.add(metadataName); } } String[] rval = new String[set.size()]; int i = 0; for (String value : set) { rval[i++] = value; } return rval; } /** Find a category path given a category ID */ protected String findPath(int catID) throws ManifoldCFException, ServiceInterruption { return getObjectPath(llc.getObjectInformation(0,catID)); } /** Get the complete path for an object. */ protected String getObjectPath(ObjectInformation currentObject) throws ManifoldCFException, ServiceInterruption { String path = null; while (true) { if (currentObject.isCategoryWorkspace()) return CATEGORY_NAME + ((path==null)?"":":" + path); else if (currentObject.isEntityWorkspace()) return ENTWKSPACE_NAME + ((path==null)?"":":" + path); if (!currentObject.exists()) { // The document identifier describes a path that does not exist. // This is unexpected, but an exception would terminate the job, and we don't want that. Logging.connectors.warn("Livelink: Bad identifier found? "+currentObject.toString()+" apparently does not exist, but need to look up its path"); return null; } // Get the name attribute String name = currentObject.getName(); if (path == null) path = name; else path = name + "/" + path; // Get the parentID attribute int parentID = currentObject.getParentId().intValue(); if (parentID == -1) { // Oops, hit the top of the path without finding the workspace we're in. // No idea where it lives; note this condition and exit. Logging.connectors.warn("Livelink: Object ID "+currentObject.toString()+" doesn't seem to live in enterprise or category workspace! Path I got was '"+path+"'"); return null; } currentObject = llc.getObjectInformation(0,parentID); } } /** Find a set of attributes given a category ID */ protected String[] findAttributes(int catID) throws ManifoldCFException, ServiceInterruption { return getCategoryAttributes(catID); } } /** Class representing a root value object, plus remainder string. * This class peels off the workspace name prefix from a path string or * attribute string, and finds the right workspace root node and remainder * path. */ protected class RootValue { protected final LivelinkContext llc; protected final String workspaceName; protected ObjectInformation rootValue = null; protected final String remainderPath; /** Constructor. *@param pathString is the path string. */ public RootValue(LivelinkContext llc, String pathString) { this.llc = llc; int colonPos = pathString.indexOf(":"); if (colonPos == -1) { remainderPath = pathString; workspaceName = ENTWKSPACE_NAME; } else { workspaceName = pathString.substring(0,colonPos); remainderPath = pathString.substring(colonPos+1); } } /** Get the path string. *@return the path string (without the workspace name prefix). */ public String getRemainderPath() { return remainderPath; } /** Get the root node. *@return the root node. */ public ObjectInformation getRootValue() throws ManifoldCFException, ServiceInterruption { if (rootValue == null) { if (workspaceName.equals(CATEGORY_NAME)) rootValue = llc.getObjectInformation(LLCATWK_VOL,LLCATWK_ID); else if (workspaceName.equals(ENTWKSPACE_NAME)) rootValue = llc.getObjectInformation(LLENTWK_VOL,LLENTWK_ID); else throw new ManifoldCFException("Bad workspace name: "+workspaceName); } if (!rootValue.exists()) { Logging.connectors.warn("Livelink: Could not get workspace/volume ID! Retrying..."); // This cannot mean a real failure; it MUST mean that we have had an intermittent communication hiccup. So, pass it off as a service interruption. throw new ServiceInterruption("Service interruption getting root value",new ManifoldCFException("Could not get workspace/volume id"),System.currentTimeMillis()+60000L, System.currentTimeMillis()+600000L,-1,true); } return rootValue; } } // Here's an interesting note. All of the LAPI exceptions are subclassed off of RuntimeException. This makes life // hell because there is no superclass exception to capture, and even tweaky server communication issues wind up throwing // uncaught RuntimeException's up the stack. // // To fix this rather bad design, all places that invoke LAPI need to catch RuntimeException and run it through the following // method for interpretation and logging. // /** Interpret runtimeexception to search for livelink API errors. Throws an appropriately reinterpreted exception, or * just returns if the exception indicates that a short-cycle retry attempt should be made. (In that case, the appropriate * wait has been already performed). *@param e is the RuntimeException caught *@param failIfTimeout is true if, for transient conditions, we want to signal failure if the timeout condition is acheived. */ protected int handleLivelinkRuntimeException(RuntimeException e, int sanityRetryCount, boolean failIfTimeout) throws ManifoldCFException, ServiceInterruption { if ( e instanceof com.opentext.api.LLHTTPAccessDeniedException || e instanceof com.opentext.api.LLHTTPClientException || e instanceof com.opentext.api.LLHTTPServerException || e instanceof com.opentext.api.LLIndexOutOfBoundsException || e instanceof com.opentext.api.LLNoFieldSpecifiedException || e instanceof com.opentext.api.LLNoValueSpecifiedException || e instanceof com.opentext.api.LLSecurityProviderException || e instanceof com.opentext.api.LLUnknownFieldException || e instanceof NumberFormatException || e instanceof ArrayIndexOutOfBoundsException ) { String details = llServer.getErrors(); long currentTime = System.currentTimeMillis(); throw new ServiceInterruption("Livelink API error: "+e.getMessage()+((details==null)?"":"; "+details),e,currentTime + 5*60000L,currentTime+12*60*60000L,-1,failIfTimeout); } else if ( e instanceof com.opentext.api.LLBadServerCertificateException || e instanceof com.opentext.api.LLHTTPCGINotFoundException || e instanceof com.opentext.api.LLCouldNotConnectHTTPException || e instanceof com.opentext.api.LLHTTPForbiddenException || e instanceof com.opentext.api.LLHTTPProxyAuthRequiredException || e instanceof com.opentext.api.LLHTTPRedirectionException || e instanceof com.opentext.api.LLUnsupportedAuthMethodException || e instanceof com.opentext.api.LLWebAuthInitException ) { String details = llServer.getErrors(); throw new ManifoldCFException("Livelink API error: "+e.getMessage()+((details==null)?"":"; "+details),e); } else if (e instanceof com.opentext.api.LLSSLNotAvailableException) { String details = llServer.getErrors(); throw new ManifoldCFException("Missing llssl.jar error: "+e.getMessage()+((details==null)?"":"; "+details),e); } else if (e instanceof com.opentext.api.LLIllegalOperationException) { // This usually means that LAPI has had a minor communication difficulty but hasn't reported it accurately. // We *could* throw a ServiceInterruption, but OpenText recommends to just retry almost immediately. String details = llServer.getErrors(); return assessRetry(sanityRetryCount,new ManifoldCFException("Livelink API illegal operation error: "+e.getMessage()+((details==null)?"":"; "+details),e)); } else if (e instanceof com.opentext.api.LLIOException || (e instanceof RuntimeException && e.getClass().getName().startsWith("com.opentext.api."))) { // Catching obfuscated and unspecified opentext runtime exceptions now too - these come from llssl.jar. We // have to presume these are SSL connection errors; nothing else to go by unfortunately. UGH. // Treat this as a transient error; try again in 5 minutes, and only fail after 12 hours of trying // LAPI is returning errors that are not terribly explicit, and I don't have control over their wording, so check that server can be resolved by DNS, // so that a better error message can be returned. try { InetAddress.getByName(serverName); } catch (UnknownHostException e2) { throw new ManifoldCFException("Server name '"+serverName+"' cannot be resolved",e2); } long currentTime = System.currentTimeMillis(); throw new ServiceInterruption(e.getMessage(),e,currentTime + 5*60000L,currentTime+12*60*60000L,-1,failIfTimeout); } else throw e; } /** Do a retry, or throw an exception if the retry count has been exhausted */ protected static int assessRetry(int sanityRetryCount, ManifoldCFException e) throws ManifoldCFException { if (sanityRetryCount == 0) { throw e; } sanityRetryCount--; try { ManifoldCF.sleep(1000L); } catch (InterruptedException e2) { throw new ManifoldCFException(e2.getMessage(),e2,ManifoldCFException.INTERRUPTED); } // Exit the method return sanityRetryCount; } /** This thread performs a LAPI FetchVersion command, streaming the resulting * document back through a XThreadInputStream to the invoking thread. */ protected class DocumentReadingThread extends Thread { protected Throwable exception = null; protected final int volumeID; protected final int docID; protected final int versionNumber; protected final XThreadInputStream stream; public DocumentReadingThread(int volumeID, int docID, int versionNumber) { super(); this.volumeID = volumeID; this.docID = docID; this.versionNumber = versionNumber; this.stream = new XThreadInputStream(); setDaemon(true); } @Override public void run() { try { XThreadOutputStream outputStream = new XThreadOutputStream(stream); try { int status = LLDocs.FetchVersion(volumeID, docID, versionNumber, outputStream); if (status != 0) { throw new ManifoldCFException("Error retrieving contents of document "+Integer.toString(volumeID)+":"+Integer.toString(docID)+" revision "+versionNumber+" : Status="+Integer.toString(status)+" ("+llServer.getErrors()+")"); } } finally { outputStream.close(); } } catch (Throwable e) { this.exception = e; } } public InputStream getSafeInputStream() { return stream; } public void finishUp() throws InterruptedException, ManifoldCFException { // This will be called during the finally // block in the case where all is well (and // the stream completed) and in the case where // there were exceptions. stream.abort(); join(); Throwable thr = exception; if (thr != null) { if (thr instanceof ManifoldCFException) throw (ManifoldCFException) thr; else if (thr instanceof RuntimeException) throw (RuntimeException) thr; else if (thr instanceof Error) throw (Error) thr; else throw new RuntimeException("Unhandled exception of type: "+thr.getClass().getName(),thr); } } } /** This thread does the actual socket communication with the server. * It's set up so that it can be abandoned at shutdown time. * * The way it works is as follows: * - it starts the transaction * - it receives the response, and saves that for the calling class to inspect * - it transfers the data part to an input stream provided to the calling class * - it shuts the connection down * * If there is an error, the sequence is aborted, and an exception is recorded * for the calling class to examine. * * The calling class basically accepts the sequence above. It starts the * thread, and tries to get a response code. If instead an exception is seen, * the exception is thrown up the stack. */ protected static class ExecuteMethodThread extends Thread { /** Client and method, all preconfigured */ protected final HttpClient httpClient; protected final HttpRequestBase executeMethod; protected HttpResponse response = null; protected Throwable responseException = null; protected XThreadInputStream threadStream = null; protected InputStream bodyStream = null; protected boolean streamCreated = false; protected Throwable streamException = null; protected boolean abortThread = false; protected Throwable shutdownException = null; protected Throwable generalException = null; public ExecuteMethodThread(HttpClient httpClient, HttpRequestBase executeMethod) { super(); setDaemon(true); this.httpClient = httpClient; this.executeMethod = executeMethod; } public void run() { try { try { // Call the execute method appropriately synchronized (this) { if (!abortThread) { try { response = httpClient.execute(executeMethod); } catch (java.net.SocketTimeoutException e) { responseException = e; } catch (ConnectTimeoutException e) { responseException = e; } catch (InterruptedIOException e) { throw e; } catch (Throwable e) { responseException = e; } this.notifyAll(); } } // Start the transfer of the content if (responseException == null) { synchronized (this) { if (!abortThread) { try { bodyStream = response.getEntity().getContent(); if (bodyStream != null) { threadStream = new XThreadInputStream(bodyStream); } streamCreated = true; } catch (java.net.SocketTimeoutException e) { streamException = e; } catch (ConnectTimeoutException e) { streamException = e; } catch (InterruptedIOException e) { throw e; } catch (Throwable e) { streamException = e; } this.notifyAll(); } } } if (responseException == null && streamException == null) { if (threadStream != null) { // Stuff the content until we are done threadStream.stuffQueue(); } } } finally { if (bodyStream != null) { try { bodyStream.close(); } catch (IOException e) { } bodyStream = null; } synchronized (this) { try { executeMethod.abort(); } catch (Throwable e) { shutdownException = e; } this.notifyAll(); } } } catch (Throwable e) { // We catch exceptions here that should ONLY be InterruptedExceptions, as a result of the thread being aborted. this.generalException = e; } } public int getResponseCode() throws InterruptedException, IOException, HttpException { // Must wait until the response object is there while (true) { synchronized (this) { checkException(responseException); if (response != null) return response.getStatusLine().getStatusCode(); wait(); } } } public long getResponseContentLength() throws InterruptedException, IOException, HttpException { String contentLength = getFirstHeader("Content-Length"); if (contentLength == null || contentLength.length() == 0) return -1L; return new Long(contentLength.trim()).longValue(); } public String getFirstHeader(String headerName) throws InterruptedException, IOException, HttpException { // Must wait for the response object to appear while (true) { synchronized (this) { checkException(responseException); if (response != null) { Header h = response.getFirstHeader(headerName); if (h == null) return null; return h.getValue(); } wait(); } } } public InputStream getSafeInputStream() throws InterruptedException, IOException, HttpException { // Must wait until stream is created, or until we note an exception was thrown. while (true) { synchronized (this) { if (responseException != null) throw new IllegalStateException("Check for response before getting stream"); checkException(streamException); if (streamCreated) return threadStream; wait(); } } } public void abort() { // This will be called during the finally // block in the case where all is well (and // the stream completed) and in the case where // there were exceptions. synchronized (this) { if (streamCreated) { if (threadStream != null) threadStream.abort(); } abortThread = true; } } public void finishUp() throws InterruptedException { join(); } protected synchronized void checkException(Throwable exception) throws IOException, HttpException { if (exception != null) { // Throw the current exception, but clear it, so no further throwing is possible on the same problem. Throwable e = exception; if (e instanceof IOException) throw (IOException)e; else if (e instanceof HttpException) throw (HttpException)e; else if (e instanceof RuntimeException) throw (RuntimeException)e; else if (e instanceof Error) throw (Error)e; else throw new RuntimeException("Unhandled exception of type: "+e.getClass().getName(),e); } } } }
Fix for livelink connector for CONNECTORS-1077. git-svn-id: 4d319e5ed894aec93a653bc5b2159f21e28d8370@1633634 13f79535-47bb-0310-9956-ffa450edef68
connectors/livelink/connector/src/main/java/org/apache/manifoldcf/crawler/connectors/livelink/LivelinkConnector.java
Fix for livelink connector for CONNECTORS-1077.
Java
apache-2.0
1aaa0a90287b46aee818520b4b5af8828fe10672
0
INAETICS/Drones-Simulator,INAETICS/Drones-Simulator
package org.inaetics.dronessimulator.visualisation.messagehandlers; import org.inaetics.dronessimulator.common.protocol.KillMessage; import org.inaetics.dronessimulator.pubsub.api.Message; import org.inaetics.dronessimulator.pubsub.api.MessageHandler; import org.inaetics.dronessimulator.visualisation.BaseEntity; import org.inaetics.dronessimulator.visualisation.Drone; import java.util.concurrent.ConcurrentMap; public class KillMessageHandler implements MessageHandler { private final ConcurrentMap<String, BaseEntity> entities; public KillMessageHandler(ConcurrentMap<String, BaseEntity> entities) { this.entities = entities; } @Override public void handleMessage(Message message) { KillMessage killMessage = (KillMessage) message; BaseEntity baseEntity = entities.get(killMessage.getIdentifier()); if(baseEntity != null) { baseEntity.delete(); entities.remove(killMessage.getIdentifier()); } } }
implementation/visualisation/src/main/java/org/inaetics/dronessimulator/visualisation/messagehandlers/KillMessageHandler.java
package org.inaetics.dronessimulator.visualisation.messagehandlers; import org.inaetics.dronessimulator.common.protocol.KillMessage; import org.inaetics.dronessimulator.pubsub.api.Message; import org.inaetics.dronessimulator.pubsub.api.MessageHandler; import org.inaetics.dronessimulator.visualisation.BaseEntity; import org.inaetics.dronessimulator.visualisation.Drone; import java.util.concurrent.ConcurrentMap; public class KillMessageHandler implements MessageHandler { private final ConcurrentMap<String, BaseEntity> entities; public KillMessageHandler(ConcurrentMap<String, BaseEntity> entities) { this.entities = entities; } @Override public void handleMessage(Message message) { KillMessage killMessage = (KillMessage) message; entities.get(killMessage.getIdentifier()).delete(); entities.remove(killMessage.getIdentifier()); } }
Fixed bug where ordering of messages may cause a killmessage to arrive before a state message in visualisation. Due to this, something to kill might not have been there yet
implementation/visualisation/src/main/java/org/inaetics/dronessimulator/visualisation/messagehandlers/KillMessageHandler.java
Fixed bug where ordering of messages may cause a killmessage to arrive before a state message in visualisation. Due to this, something to kill might not have been there yet
Java
apache-2.0
4f7b60d8fd45b089ba5e8cf13c0486a4cfc56456
0
sekikn/ambari,sekikn/ambari,sekikn/ambari,sekikn/ambari,sekikn/ambari,sekikn/ambari,sekikn/ambari,sekikn/ambari,sekikn/ambari
/** * 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.ambari.metrics.core.timeline; import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.replay; import junit.framework.Assert; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.metrics2.sink.timeline.TimelineMetric; import org.easymock.EasyMock; import org.junit.Test; import java.net.URISyntaxException; import java.net.URL; import java.util.HashSet; import java.util.Set; public class TimelineMetricsFilterTest { @Test public void testAppBlacklisting() throws Exception{ Configuration metricsConf = new Configuration(); metricsConf.set("timeline.metrics.apps.blacklist", "hbase,datanode,nimbus"); TimelineMetricConfiguration configuration = EasyMock.createNiceMock(TimelineMetricConfiguration.class); expect(configuration.getMetricsConf()).andReturn(metricsConf).once(); replay(configuration); TimelineMetricsFilter.initializeMetricFilter(configuration); TimelineMetric timelineMetric = new TimelineMetric(); timelineMetric.setAppId("hbase"); Assert.assertFalse(TimelineMetricsFilter.acceptMetric(timelineMetric)); timelineMetric.setAppId("namenode"); Assert.assertTrue(TimelineMetricsFilter.acceptMetric(timelineMetric)); timelineMetric.setAppId("nimbus"); Assert.assertFalse(TimelineMetricsFilter.acceptMetric(timelineMetric)); } @Test public void testMetricWhitelisting() throws Exception { Configuration metricsConf = new Configuration(); TimelineMetricConfiguration configuration = EasyMock.createNiceMock(TimelineMetricConfiguration.class); expect(configuration.getMetricsConf()).andReturn(metricsConf).once(); expect(configuration.isWhitelistingEnabled()).andReturn(true).anyTimes(); replay(configuration); metricsConf.set("timeline.metrics.whitelist.file", getTestWhitelistFilePath()); TimelineMetricsFilter.initializeMetricFilter(configuration); TimelineMetric timelineMetric = new TimelineMetric(); timelineMetric.setMetricName("cpu_system"); Assert.assertTrue(TimelineMetricsFilter.acceptMetric(timelineMetric)); timelineMetric.setMetricName("cpu_system1"); Assert.assertFalse(TimelineMetricsFilter.acceptMetric(timelineMetric)); timelineMetric.setMetricName("jvm.JvmMetrics.MemHeapUsedM"); Assert.assertTrue(TimelineMetricsFilter.acceptMetric(timelineMetric)); timelineMetric.setMetricName("dfs.FSNamesystem.TotalFiles"); Assert.assertTrue(TimelineMetricsFilter.acceptMetric(timelineMetric)); } @Test public void testTogether() throws Exception { Configuration metricsConf = new Configuration(); metricsConf.set("timeline.metrics.apps.blacklist", "hbase,datanode,nimbus"); TimelineMetricConfiguration configuration = EasyMock.createNiceMock(TimelineMetricConfiguration.class); expect(configuration.getMetricsConf()).andReturn(metricsConf).once(); replay(configuration); metricsConf.set("timeline.metrics.whitelist.file", getTestWhitelistFilePath()); TimelineMetricsFilter.initializeMetricFilter(configuration); TimelineMetric timelineMetric = new TimelineMetric(); timelineMetric.setMetricName("cpu_system"); timelineMetric.setAppId("hbase"); Assert.assertFalse(TimelineMetricsFilter.acceptMetric(timelineMetric)); timelineMetric.setMetricName("cpu_system"); timelineMetric.setAppId("HOST"); Assert.assertTrue(TimelineMetricsFilter.acceptMetric(timelineMetric)); timelineMetric.setMetricName("jvm.JvmMetrics.MemHeapUsedM"); Assert.assertTrue(TimelineMetricsFilter.acceptMetric(timelineMetric)); timelineMetric.setMetricName("dfs.FSNamesystem.TotalFiles"); Assert.assertTrue(TimelineMetricsFilter.acceptMetric(timelineMetric)); } @Test public void testAmshbaseWhitelisting() throws Exception { TimelineMetricConfiguration configuration = EasyMock.createNiceMock(TimelineMetricConfiguration.class); Configuration metricsConf = new Configuration(); expect(configuration.getMetricsConf()).andReturn(metricsConf).once(); Set<String> whitelist = new HashSet(); whitelist.add("regionserver.Server.Delete_99th_percentile"); whitelist.add("regionserver.Server.Delete_max"); whitelist.add("regionserver.Server.Delete_mean"); expect(configuration.getAmshbaseWhitelist()).andReturn(whitelist).once(); replay(configuration); TimelineMetricsFilter.initializeMetricFilter(configuration); TimelineMetric timelineMetric = new TimelineMetric(); timelineMetric.setMetricName("regionserver.Server.Delete_max"); timelineMetric.setAppId("ams-hbase"); Assert.assertTrue(TimelineMetricsFilter.acceptMetric(timelineMetric)); timelineMetric.setMetricName("regionserver.Server.Delete_min3333"); timelineMetric.setAppId("ams-hbase"); Assert.assertFalse(TimelineMetricsFilter.acceptMetric(timelineMetric)); timelineMetric.setMetricName("jvm.JvmMetrics.MemHeapUsedM"); timelineMetric.setAppId("hbase"); Assert.assertTrue(TimelineMetricsFilter.acceptMetric(timelineMetric)); } @Test public void testHybridFilter() throws Exception { // Whitelist Apps - namenode, nimbus // Blacklist Apps - datanode, kafka_broker // Accept ams-hbase whitelisting. // Reject non whitelisted metrics from non whitelisted Apps (Say hbase) TimelineMetricConfiguration configuration = EasyMock.createNiceMock(TimelineMetricConfiguration.class); Configuration metricsConf = new Configuration(); metricsConf.set("timeline.metrics.apps.whitelist", "namenode,nimbus"); metricsConf.set("timeline.metrics.apps.blacklist", "datanode,kafka_broker"); metricsConf.set("timeline.metrics.whitelist.file", getTestWhitelistFilePath()); expect(configuration.getMetricsConf()).andReturn(metricsConf).once(); Set<String> whitelist = new HashSet<>(); whitelist.add("regionserver.Server.Delete_99th_percentile"); whitelist.add("regionserver.Server.Delete_max"); whitelist.add("regionserver.Server.Delete_mean"); expect(configuration.getAmshbaseWhitelist()).andReturn(whitelist).once(); expect(configuration.isWhitelistingEnabled()).andReturn(true).anyTimes(); replay(configuration); TimelineMetricsFilter.initializeMetricFilter(configuration); TimelineMetric timelineMetric = new TimelineMetric(); //Test App Whitelisting timelineMetric.setMetricName("metric.a.b.c"); timelineMetric.setAppId("namenode"); Assert.assertTrue(TimelineMetricsFilter.acceptMetric(timelineMetric)); timelineMetric.setMetricName("metric.d.e.f"); timelineMetric.setAppId("nimbus"); Assert.assertTrue(TimelineMetricsFilter.acceptMetric(timelineMetric)); //Test App Blacklisting timelineMetric.setMetricName("metric.d.e.f"); timelineMetric.setAppId("datanode"); Assert.assertFalse(TimelineMetricsFilter.acceptMetric(timelineMetric)); timelineMetric.setMetricName("metric.d.e.f"); timelineMetric.setAppId("kafka_broker"); Assert.assertFalse(TimelineMetricsFilter.acceptMetric(timelineMetric)); //Test ams-hbase Whitelisting timelineMetric.setMetricName("regionserver.Server.Delete_max"); timelineMetric.setAppId("ams-hbase"); Assert.assertTrue(TimelineMetricsFilter.acceptMetric(timelineMetric)); timelineMetric.setMetricName("regionserver.Server.Delete_min3333"); timelineMetric.setAppId("ams-hbase"); Assert.assertFalse(TimelineMetricsFilter.acceptMetric(timelineMetric)); timelineMetric.setMetricName("regionserver.Server.Delete_mean"); timelineMetric.setAppId("ams-hbase"); Assert.assertTrue(TimelineMetricsFilter.acceptMetric(timelineMetric)); //Test Metric Whitelisting timelineMetric.setMetricName("regionserver.WAL.SyncTime_max"); timelineMetric.setAppId("hbase"); Assert.assertTrue(TimelineMetricsFilter.acceptMetric(timelineMetric)); timelineMetric.setMetricName("regionserver.WAL.metric.not.needed"); timelineMetric.setAppId("hbase"); Assert.assertFalse(TimelineMetricsFilter.acceptMetric(timelineMetric)); } private static String getTestWhitelistFilePath() throws URISyntaxException { return ClassLoader.getSystemResource("test_data/metric_whitelist.dat").toURI().getPath(); } }
ambari-metrics/ambari-metrics-timelineservice/src/test/java/org/apache/ambari/metrics/core/timeline/TimelineMetricsFilterTest.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.ambari.metrics.core.timeline; import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.replay; import junit.framework.Assert; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.metrics2.sink.timeline.TimelineMetric; import org.easymock.EasyMock; import org.junit.Test; import java.net.URL; import java.util.HashSet; import java.util.Set; public class TimelineMetricsFilterTest { @Test public void testAppBlacklisting() throws Exception{ Configuration metricsConf = new Configuration(); metricsConf.set("timeline.metrics.apps.blacklist", "hbase,datanode,nimbus"); TimelineMetricConfiguration configuration = EasyMock.createNiceMock(TimelineMetricConfiguration.class); expect(configuration.getMetricsConf()).andReturn(metricsConf).once(); replay(configuration); TimelineMetricsFilter.initializeMetricFilter(configuration); TimelineMetric timelineMetric = new TimelineMetric(); timelineMetric.setAppId("hbase"); Assert.assertFalse(TimelineMetricsFilter.acceptMetric(timelineMetric)); timelineMetric.setAppId("namenode"); Assert.assertTrue(TimelineMetricsFilter.acceptMetric(timelineMetric)); timelineMetric.setAppId("nimbus"); Assert.assertFalse(TimelineMetricsFilter.acceptMetric(timelineMetric)); } @Test public void testMetricWhitelisting() throws Exception { Configuration metricsConf = new Configuration(); TimelineMetricConfiguration configuration = EasyMock.createNiceMock(TimelineMetricConfiguration.class); expect(configuration.getMetricsConf()).andReturn(metricsConf).once(); expect(configuration.isWhitelistingEnabled()).andReturn(true).anyTimes(); replay(configuration); URL fileUrl = ClassLoader.getSystemResource("test_data/metric_whitelist.dat"); metricsConf.set("timeline.metrics.whitelist.file", fileUrl.getPath()); TimelineMetricsFilter.initializeMetricFilter(configuration); TimelineMetric timelineMetric = new TimelineMetric(); timelineMetric.setMetricName("cpu_system"); Assert.assertTrue(TimelineMetricsFilter.acceptMetric(timelineMetric)); timelineMetric.setMetricName("cpu_system1"); Assert.assertFalse(TimelineMetricsFilter.acceptMetric(timelineMetric)); timelineMetric.setMetricName("jvm.JvmMetrics.MemHeapUsedM"); Assert.assertTrue(TimelineMetricsFilter.acceptMetric(timelineMetric)); timelineMetric.setMetricName("dfs.FSNamesystem.TotalFiles"); Assert.assertTrue(TimelineMetricsFilter.acceptMetric(timelineMetric)); } @Test public void testTogether() throws Exception { Configuration metricsConf = new Configuration(); metricsConf.set("timeline.metrics.apps.blacklist", "hbase,datanode,nimbus"); TimelineMetricConfiguration configuration = EasyMock.createNiceMock(TimelineMetricConfiguration.class); expect(configuration.getMetricsConf()).andReturn(metricsConf).once(); replay(configuration); URL fileUrl = ClassLoader.getSystemResource("test_data/metric_whitelist.dat"); metricsConf.set("timeline.metrics.whitelist.file", fileUrl.getPath()); TimelineMetricsFilter.initializeMetricFilter(configuration); TimelineMetric timelineMetric = new TimelineMetric(); timelineMetric.setMetricName("cpu_system"); timelineMetric.setAppId("hbase"); Assert.assertFalse(TimelineMetricsFilter.acceptMetric(timelineMetric)); timelineMetric.setMetricName("cpu_system"); timelineMetric.setAppId("HOST"); Assert.assertTrue(TimelineMetricsFilter.acceptMetric(timelineMetric)); timelineMetric.setMetricName("jvm.JvmMetrics.MemHeapUsedM"); Assert.assertTrue(TimelineMetricsFilter.acceptMetric(timelineMetric)); timelineMetric.setMetricName("dfs.FSNamesystem.TotalFiles"); Assert.assertTrue(TimelineMetricsFilter.acceptMetric(timelineMetric)); } @Test public void testAmshbaseWhitelisting() throws Exception { TimelineMetricConfiguration configuration = EasyMock.createNiceMock(TimelineMetricConfiguration.class); Configuration metricsConf = new Configuration(); expect(configuration.getMetricsConf()).andReturn(metricsConf).once(); Set<String> whitelist = new HashSet(); whitelist.add("regionserver.Server.Delete_99th_percentile"); whitelist.add("regionserver.Server.Delete_max"); whitelist.add("regionserver.Server.Delete_mean"); expect(configuration.getAmshbaseWhitelist()).andReturn(whitelist).once(); replay(configuration); TimelineMetricsFilter.initializeMetricFilter(configuration); TimelineMetric timelineMetric = new TimelineMetric(); timelineMetric.setMetricName("regionserver.Server.Delete_max"); timelineMetric.setAppId("ams-hbase"); Assert.assertTrue(TimelineMetricsFilter.acceptMetric(timelineMetric)); timelineMetric.setMetricName("regionserver.Server.Delete_min3333"); timelineMetric.setAppId("ams-hbase"); Assert.assertFalse(TimelineMetricsFilter.acceptMetric(timelineMetric)); timelineMetric.setMetricName("jvm.JvmMetrics.MemHeapUsedM"); timelineMetric.setAppId("hbase"); Assert.assertTrue(TimelineMetricsFilter.acceptMetric(timelineMetric)); } @Test public void testHybridFilter() throws Exception { // Whitelist Apps - namenode, nimbus // Blacklist Apps - datanode, kafka_broker // Accept ams-hbase whitelisting. // Reject non whitelisted metrics from non whitelisted Apps (Say hbase) TimelineMetricConfiguration configuration = EasyMock.createNiceMock(TimelineMetricConfiguration.class); Configuration metricsConf = new Configuration(); metricsConf.set("timeline.metrics.apps.whitelist", "namenode,nimbus"); metricsConf.set("timeline.metrics.apps.blacklist", "datanode,kafka_broker"); URL fileUrl = ClassLoader.getSystemResource("test_data/metric_whitelist.dat"); metricsConf.set("timeline.metrics.whitelist.file", fileUrl.getPath()); expect(configuration.getMetricsConf()).andReturn(metricsConf).once(); Set<String> whitelist = new HashSet(); whitelist.add("regionserver.Server.Delete_99th_percentile"); whitelist.add("regionserver.Server.Delete_max"); whitelist.add("regionserver.Server.Delete_mean"); expect(configuration.getAmshbaseWhitelist()).andReturn(whitelist).once(); expect(configuration.isWhitelistingEnabled()).andReturn(true).anyTimes(); replay(configuration); TimelineMetricsFilter.initializeMetricFilter(configuration); TimelineMetric timelineMetric = new TimelineMetric(); //Test App Whitelisting timelineMetric.setMetricName("metric.a.b.c"); timelineMetric.setAppId("namenode"); Assert.assertTrue(TimelineMetricsFilter.acceptMetric(timelineMetric)); timelineMetric.setMetricName("metric.d.e.f"); timelineMetric.setAppId("nimbus"); Assert.assertTrue(TimelineMetricsFilter.acceptMetric(timelineMetric)); //Test App Blacklisting timelineMetric.setMetricName("metric.d.e.f"); timelineMetric.setAppId("datanode"); Assert.assertFalse(TimelineMetricsFilter.acceptMetric(timelineMetric)); timelineMetric.setMetricName("metric.d.e.f"); timelineMetric.setAppId("kafka_broker"); Assert.assertFalse(TimelineMetricsFilter.acceptMetric(timelineMetric)); //Test ams-hbase Whitelisting timelineMetric.setMetricName("regionserver.Server.Delete_max"); timelineMetric.setAppId("ams-hbase"); Assert.assertTrue(TimelineMetricsFilter.acceptMetric(timelineMetric)); timelineMetric.setMetricName("regionserver.Server.Delete_min3333"); timelineMetric.setAppId("ams-hbase"); Assert.assertFalse(TimelineMetricsFilter.acceptMetric(timelineMetric)); timelineMetric.setMetricName("regionserver.Server.Delete_mean"); timelineMetric.setAppId("ams-hbase"); Assert.assertTrue(TimelineMetricsFilter.acceptMetric(timelineMetric)); //Test Metric Whitelisting timelineMetric.setMetricName("regionserver.WAL.SyncTime_max"); timelineMetric.setAppId("hbase"); Assert.assertTrue(TimelineMetricsFilter.acceptMetric(timelineMetric)); timelineMetric.setMetricName("regionserver.WAL.metric.not.needed"); timelineMetric.setAppId("hbase"); Assert.assertFalse(TimelineMetricsFilter.acceptMetric(timelineMetric)); } }
AMBARI-23811. TimelineMetricsFilterTest fails if dir name contains @ (#1237)
ambari-metrics/ambari-metrics-timelineservice/src/test/java/org/apache/ambari/metrics/core/timeline/TimelineMetricsFilterTest.java
AMBARI-23811. TimelineMetricsFilterTest fails if dir name contains @ (#1237)
Java
apache-2.0
cbfbae69945405573bea5dce436dce35e3a0a474
0
arshadalisoomro/BroadleafCommerce,caosg/BroadleafCommerce,wenmangbo/BroadleafCommerce,macielbombonato/BroadleafCommerce,rawbenny/BroadleafCommerce,daniellavoie/BroadleafCommerce,ljshj/BroadleafCommerce,bijukunjummen/BroadleafCommerce,macielbombonato/BroadleafCommerce,sitexa/BroadleafCommerce,wenmangbo/BroadleafCommerce,lgscofield/BroadleafCommerce,macielbombonato/BroadleafCommerce,udayinfy/BroadleafCommerce,cloudbearings/BroadleafCommerce,cengizhanozcan/BroadleafCommerce,alextiannus/BroadleafCommerce,lgscofield/BroadleafCommerce,trombka/blc-tmp,zhaorui1/BroadleafCommerce,daniellavoie/BroadleafCommerce,udayinfy/BroadleafCommerce,arshadalisoomro/BroadleafCommerce,TouK/BroadleafCommerce,alextiannus/BroadleafCommerce,bijukunjummen/BroadleafCommerce,cloudbearings/BroadleafCommerce,cloudbearings/BroadleafCommerce,trombka/blc-tmp,SerPenTeHoK/BroadleafCommerce,caosg/BroadleafCommerce,cengizhanozcan/BroadleafCommerce,sitexa/BroadleafCommerce,daniellavoie/BroadleafCommerce,zhaorui1/BroadleafCommerce,bijukunjummen/BroadleafCommerce,liqianggao/BroadleafCommerce,caosg/BroadleafCommerce,cengizhanozcan/BroadleafCommerce,liqianggao/BroadleafCommerce,ljshj/BroadleafCommerce,arshadalisoomro/BroadleafCommerce,SerPenTeHoK/BroadleafCommerce,ljshj/BroadleafCommerce,lgscofield/BroadleafCommerce,trombka/blc-tmp,liqianggao/BroadleafCommerce,zhaorui1/BroadleafCommerce,TouK/BroadleafCommerce,alextiannus/BroadleafCommerce,rawbenny/BroadleafCommerce,wenmangbo/BroadleafCommerce,TouK/BroadleafCommerce,sitexa/BroadleafCommerce,udayinfy/BroadleafCommerce,SerPenTeHoK/BroadleafCommerce,rawbenny/BroadleafCommerce
/* * #%L * BroadleafCommerce Framework Web * %% * Copyright (C) 2009 - 2013 Broadleaf Commerce * %% * 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. * #L% */ package org.broadleafcommerce.core.web.controller.account; import org.broadleafcommerce.common.exception.ServiceException; import org.broadleafcommerce.common.web.controller.BroadleafAbstractController; import org.broadleafcommerce.core.web.controller.account.validator.UpdateAccountValidator; import org.broadleafcommerce.profile.core.domain.Customer; import org.broadleafcommerce.profile.core.service.CustomerService; import org.broadleafcommerce.profile.web.core.CustomerState; import org.broadleafcommerce.profile.web.core.service.login.LoginService; import org.springframework.beans.factory.annotation.Value; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; public class BroadleafUpdateAccountController extends BroadleafAbstractController { @Value("${use.email.for.site.login:true}") protected boolean useEmailForLogin; @Resource(name="blLoginService") protected LoginService loginService; @Resource(name = "blCustomerService") protected CustomerService customerService; @Resource(name = "blUpdateAccountValidator") protected UpdateAccountValidator updateAccountValidator; protected String accountUpdatedMessage = "Account successfully updated"; protected static String updateAccountView = "account/updateAccount"; protected static String accountRedirectView = "redirect:/account"; public String viewUpdateAccount(HttpServletRequest request, Model model, UpdateAccountForm form) { Customer customer = CustomerState.getCustomer(); form.setEmailAddress(customer.getEmailAddress()); form.setFirstName(customer.getFirstName()); form.setLastName(customer.getLastName()); return getUpdateAccountView(); } public String processUpdateAccount(HttpServletRequest request, Model model, UpdateAccountForm form, BindingResult result, RedirectAttributes redirectAttributes) throws ServiceException { updateAccountValidator.validate(form, result); if (result.hasErrors()) { return getUpdateAccountView(); } Customer customer = CustomerState.getCustomer(); customer.setEmailAddress(form.getEmailAddress()); customer.setFirstName(form.getFirstName()); customer.setLastName(form.getLastName()); if (useEmailForLogin) { customer.setUsername(form.getEmailAddress()); } customerService.saveCustomer(customer); redirectAttributes.addFlashAttribute("successMessage", getAccountUpdatedMessage()); if (useEmailForLogin) { loginService.loginCustomer(customer.getUsername(), customer.getPassword()); } return getAccountRedirectView(); } public String getUpdateAccountView() { return updateAccountView; } public String getAccountRedirectView() { return accountRedirectView; } public String getAccountUpdatedMessage() { return accountUpdatedMessage; } }
core/broadleaf-framework-web/src/main/java/org/broadleafcommerce/core/web/controller/account/BroadleafUpdateAccountController.java
/* * #%L * BroadleafCommerce Framework Web * %% * Copyright (C) 2009 - 2013 Broadleaf Commerce * %% * 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. * #L% */ package org.broadleafcommerce.core.web.controller.account; import org.broadleafcommerce.common.exception.ServiceException; import org.broadleafcommerce.common.web.controller.BroadleafAbstractController; import org.broadleafcommerce.core.web.controller.account.validator.UpdateAccountValidator; import org.broadleafcommerce.profile.core.domain.Customer; import org.broadleafcommerce.profile.core.service.CustomerService; import org.broadleafcommerce.profile.web.core.CustomerState; import org.springframework.beans.factory.annotation.Value; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; public class BroadleafUpdateAccountController extends BroadleafAbstractController { @Value("${use.email.for.site.login:true}") protected boolean useEmailForLogin; @Resource(name = "blCustomerService") protected CustomerService customerService; @Resource(name = "blUpdateAccountValidator") protected UpdateAccountValidator updateAccountValidator; protected String accountUpdatedMessage = "Account successfully updated"; protected static String updateAccountView = "account/updateAccount"; protected static String accountRedirectView = "redirect:/account"; public String viewUpdateAccount(HttpServletRequest request, Model model, UpdateAccountForm form) { Customer customer = CustomerState.getCustomer(); form.setEmailAddress(customer.getEmailAddress()); form.setFirstName(customer.getFirstName()); form.setLastName(customer.getLastName()); return getUpdateAccountView(); } public String processUpdateAccount(HttpServletRequest request, Model model, UpdateAccountForm form, BindingResult result, RedirectAttributes redirectAttributes) throws ServiceException { updateAccountValidator.validate(form, result); if (result.hasErrors()) { return getUpdateAccountView(); } Customer customer = CustomerState.getCustomer(); customer.setEmailAddress(form.getEmailAddress()); customer.setFirstName(form.getFirstName()); customer.setLastName(form.getLastName()); if (useEmailForLogin) { customer.setUsername(form.getEmailAddress()); } customerService.saveCustomer(customer); redirectAttributes.addFlashAttribute("successMessage", getAccountUpdatedMessage()); return getAccountRedirectView(); } public String getUpdateAccountView() { return updateAccountView; } public String getAccountRedirectView() { return accountRedirectView; } public String getAccountUpdatedMessage() { return accountUpdatedMessage; } }
BroadleafCommerce/QA#616 - updated BroadleafUpdateAccountController to properly log a customer in if the email is changed.
core/broadleaf-framework-web/src/main/java/org/broadleafcommerce/core/web/controller/account/BroadleafUpdateAccountController.java
BroadleafCommerce/QA#616 - updated BroadleafUpdateAccountController to properly log a customer in if the email is changed.
Java
apache-2.0
4b0d2265b524c7020cd3de50f9bb3b6a460aa84a
0
nus-ncl/service-web,nus-ncl/service-web,nus-ncl/service-web,nus-ncl/service-web
package sg.ncl; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import lombok.extern.slf4j.Slf4j; import org.apache.commons.io.IOUtils; import org.apache.tomcat.util.codec.binary.Base64; import org.json.JSONArray; import org.json.JSONObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.*; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.*; import org.springframework.web.client.ResourceAccessException; import org.springframework.web.client.RestClientException; import org.springframework.web.client.RestTemplate; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import org.springframework.web.servlet.support.RequestContextUtils; import sg.ncl.domain.*; import sg.ncl.exceptions.*; import sg.ncl.testbed_interface.*; import javax.inject.Inject; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import javax.validation.Valid; import javax.validation.constraints.NotNull; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.nio.charset.StandardCharsets; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.EnumMap; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Pattern; import static sg.ncl.domain.ExceptionState.*; /** * * Spring Controller * Direct the views to appropriate locations and invoke the respective REST API * * @author Cassie, Desmond, Te Ye, Vu */ @Controller @Slf4j public class MainController { public static final String CONTENT_DISPOSITION = "Content-Disposition"; public static final String APPLICATION_FORCE_DOWNLOAD = "application/force-download"; private static final String SESSION_LOGGED_IN_USER_ID = "loggedInUserId"; private TeamManager teamManager = TeamManager.getInstance(); // private UserManager userManager = UserManager.getInstance(); // private ExperimentManager experimentManager = ExperimentManager.getInstance(); // private DomainManager domainManager = DomainManager.getInstance(); // private DatasetManager datasetManager = DatasetManager.getInstance(); // private NodeManager nodeManager = NodeManager.getInstance(); private static final String CONTACT_EMAIL = "[email protected]"; private static final String UNKNOWN = "?"; private static final String MESSAGE = "message"; private static final String MESSAGE_SUCCESS = "messageSuccess"; private static final String EXPERIMENT_MESSAGE = "exp_message"; private static final String ERROR_PREFIX = "Error: "; // error messages private static final String ERR_SERVER_OVERLOAD = "There is a problem with your request. Please contact " + CONTACT_EMAIL; private static final String CONNECTION_ERROR = "Connection Error"; private final String permissionDeniedMessage = "Permission denied. If the error persists, please contact " + CONTACT_EMAIL; // for user dashboard hashmap key values private static final String USER_DASHBOARD_TEAMS = "teams"; private static final String USER_DASHBOARD_RUNNING_EXPERIMENTS = "runningExperiments"; private static final String USER_DASHBOARD_FREE_NODES = "freeNodes"; private static final String DETER_UID = "deterUid"; private static final Pattern VALID_EMAIL_ADDRESS_REGEX = Pattern.compile("(?:(?:\\r\\n)?[ \\t])*(?:(?:(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*))*@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*|(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)*\\<(?:(?:\\r\\n)?[ \\t])*(?:@(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*(?:,@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*)*:(?:(?:\\r\\n)?[ \\t])*)?(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*))*@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*\\>(?:(?:\\r\\n)?[ \\t])*)|(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)*:(?:(?:\\r\\n)?[ \\t])*(?:(?:(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*))*@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*|(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)*\\<(?:(?:\\r\\n)?[ \\t])*(?:@(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*(?:,@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*)*:(?:(?:\\r\\n)?[ \\t])*)?(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*))*@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*\\>(?:(?:\\r\\n)?[ \\t])*)(?:,\\s*(?:(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*))*@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*|(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)*\\<(?:(?:\\r\\n)?[ \\t])*(?:@(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*(?:,@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*)*:(?:(?:\\r\\n)?[ \\t])*)?(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*))*@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*\\>(?:(?:\\r\\n)?[ \\t])*))*)?;\\s*)"); private static final String FORGET_PSWD_PAGE = "password_reset_email"; private static final String FORGET_PSWD_NEW_PSWD_PAGE = "password_reset_new_password"; private static final String NO_PERMISSION_PAGE = "nopermission"; private static final String TEAM_NAME = "teamName"; private static final String NODE_ID = "nodeId"; private static final String PERMISSION_DENIED = "Permission denied"; private static final String TEAM_NOT_FOUND = "Team not found"; @Autowired protected RestTemplate restTemplate; @Inject protected ObjectMapper objectMapper; @Inject protected ConnectionProperties properties; @Inject protected WebProperties webProperties; @Inject protected HttpSession httpScopedSession; @RequestMapping("/") public String index() { return "index"; } @RequestMapping("/overview") public String overview() { return "overview"; } @RequestMapping("/community") public String community() { return "community"; } @RequestMapping("/about") public String about() { return "about"; } @RequestMapping("/event") public String event() { return "event"; } @RequestMapping("/plan") public String plan() { return "plan"; } // @RequestMapping("/futureplan") // public String futureplan() { // return "futureplan"; // } @RequestMapping("/pricing") public String pricing() { return "pricing"; } @RequestMapping("/resources1") public String resources1() { return "resources1"; } @RequestMapping("/resources") public String resources() { return "resources"; } @RequestMapping("/research") public String research() { return "research"; } @RequestMapping("/calendar") public String calendar() { return "calendar"; } @RequestMapping("/calendar1") public String calendar1() { return "calendar1"; } @RequestMapping("/tools") public String tools() { return "tools"; } @RequestMapping("/createaccount") public String createAccount() { return "createaccount"; } @RequestMapping("/createexperiment") public String createExperimentTutorial() { return "createexperiment"; } @RequestMapping("/applyteam") public String applyteam() { return "applyteam"; } @RequestMapping("/jointeam") public String jointeam() { return "jointeam"; } @RequestMapping("/error_openstack") public String error_openstack() { return "error_openstack"; } // @RequestMapping("/resource2") // public String resource2() { // return "resource2"; // } @RequestMapping("/accessexperiment") public String accessexperiment() { return "accessexperiment"; } @RequestMapping("/resource2") public String resource2() { return "resource2"; } // @RequestMapping("/admin2") // public String admin2() { // return "admin2"; // } @RequestMapping("/tutorials") public String tutorials() { return "tutorials"; } @RequestMapping("/maintainance") public String maintainance() { return "maintainance"; } @RequestMapping("/TestbedInformation") public String TestbedInformation() { return "TestbedInformation"; } // @RequestMapping(value="/futureplan/download", method=RequestMethod.GET) // public void futureplanDownload(HttpServletResponse response) throws FuturePlanDownloadException, IOException { // InputStream stream = null; // response.setContentType("application/pdf"); // try { // stream = getClass().getClassLoader().getResourceAsStream("downloads/future_plan.pdf"); // response.setContentType("application/force-download"); // response.setHeader("Content-Disposition", "attachment; filename=future_plan.pdf"); // IOUtils.copy(stream, response.getOutputStream()); // response.flushBuffer(); // } catch (Exception ex) { // logger.info("Error writing file to output stream."); // throw new FuturePlanDownloadException("IOError writing file to output stream"); // } finally { // if (stream != null) { // stream.close(); // } // } // } @RequestMapping(value = "/orderform/download", method = RequestMethod.GET) public void OrderForm_v1Download(HttpServletResponse response) throws OrderFormDownloadException, IOException { InputStream stream = null; response.setContentType(MediaType.APPLICATION_PDF_VALUE); try { stream = getClass().getClassLoader().getResourceAsStream("downloads/order_form.pdf"); response.setContentType(APPLICATION_FORCE_DOWNLOAD); response.setHeader(CONTENT_DISPOSITION, "attachment; filename=order_form.pdf"); IOUtils.copy(stream, response.getOutputStream()); response.flushBuffer(); } catch (IOException ex) { log.info("Error for download orderform."); throw new OrderFormDownloadException("Error for download orderform."); } finally { if (stream != null) { stream.close(); } } } @RequestMapping(value = "/SubscriptionAgreement/download", method = RequestMethod.GET) public void subscriptionAgreementDownload(HttpServletResponse response) throws MasterSubscriptionAgreementDownloadException, IOException { InputStream stream = null; response.setContentType(MediaType.APPLICATION_PDF_VALUE); try { stream = getClass().getClassLoader().getResourceAsStream("downloads/SubscriptionAgreement.pdf"); response.setContentType(APPLICATION_FORCE_DOWNLOAD); response.setHeader(CONTENT_DISPOSITION, "attachment; filename=SubscriptionAgreement.pdf"); IOUtils.copy(stream, response.getOutputStream()); response.flushBuffer(); } catch (IOException ex) { log.info("Error for subscription download." + ex.getMessage()); throw new MasterSubscriptionAgreementDownloadException("Error for subscription download."); } finally { if (stream != null) { stream.close(); } } } @RequestMapping(value = "/UsagePolicy/download", method = RequestMethod.GET) public void usagePolicyDownload(HttpServletResponse response) throws UsagePolicyDownloadException, IOException { InputStream stream = null; response.setContentType(MediaType.APPLICATION_PDF_VALUE); try { stream = getClass().getClassLoader().getResourceAsStream("downloads/UsagePolicy.pdf"); response.setContentType(APPLICATION_FORCE_DOWNLOAD); response.setHeader(CONTENT_DISPOSITION, "attachment; filename=UsagePolicy.pdf"); IOUtils.copy(stream, response.getOutputStream()); response.flushBuffer(); } catch (IOException ex) { log.info("Error for usage policy download." + ex.getMessage()); throw new UsagePolicyDownloadException("Error for usage policy download."); } finally { if (stream != null) { stream.close(); } } } @RequestMapping("/contactus") public String contactus() { return "contactus"; } @RequestMapping("/notfound") public String redirectNotFound(HttpSession session) { if (session.getAttribute("id") != null && !session.getAttribute("id").toString().isEmpty()) { // user is already logged on and has encountered an error // redirect to dashboard return "redirect:/dashboard"; } else { // user have not logged on before // redirect to home page return "redirect:/"; } } @RequestMapping(value = "/login", method = RequestMethod.GET) public String login(Model model) { model.addAttribute("loginForm", new LoginForm()); return "login"; } @RequestMapping(value = "/emailVerification", params = {"id", "email", "key"}) public String verifyEmail( @NotNull @RequestParam("id") final String id, @NotNull @RequestParam("email") final String emailBase64, @NotNull @RequestParam("key") final String key ) throws UnsupportedEncodingException { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); ObjectNode keyObject = objectMapper.createObjectNode(); keyObject.put("key", key); HttpEntity<String> request = new HttpEntity<>(keyObject.toString(), headers); restTemplate.setErrorHandler(new MyResponseErrorHandler()); final String link = properties.getSioUsersUrl() + id + "/emails/" + emailBase64; log.info("Activation link: {}, verification key {}", link, key); ResponseEntity response = restTemplate.exchange(link, HttpMethod.PUT, request, String.class); if (RestUtil.isError(response.getStatusCode())) { log.error("Activation of user {} failed.", id); return "email_validation_failed"; } else { log.info("Activation of user {} completed.", id); return "email_validation_ok"; } } @RequestMapping(value = "/login", method = RequestMethod.POST) public String loginSubmit( @Valid @ModelAttribute("loginForm") LoginForm loginForm, BindingResult bindingResult, Model model, HttpSession session, final RedirectAttributes redirectAttributes) throws WebServiceRuntimeException { if (bindingResult.hasErrors()) { loginForm.setErrorMsg("Login failed: Invalid email/password."); return "login"; } String inputEmail = loginForm.getLoginEmail(); String inputPwd = loginForm.getLoginPassword(); if (inputEmail.trim().isEmpty() || inputPwd.trim().isEmpty()) { loginForm.setErrorMsg("Email or Password cannot be empty!"); return "login"; } String plainCreds = inputEmail + ":" + inputPwd; byte[] plainCredsBytes = plainCreds.getBytes(); byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes); String base64Creds = new String(base64CredsBytes); ResponseEntity response; HttpHeaders headers = new HttpHeaders(); headers.set("Authorization", "Basic " + base64Creds); HttpEntity<String> request = new HttpEntity<>(headers); restTemplate.setErrorHandler(new MyResponseErrorHandler()); try { response = restTemplate.exchange(properties.getSioAuthUrl(), HttpMethod.POST, request, String.class); } catch (RestClientException e) { log.warn("Error connecting to sio authentication service: {}", e); loginForm.setErrorMsg(ERR_SERVER_OVERLOAD); return "login"; } String jwtTokenString = response.getBody().toString(); log.info("token string {}", jwtTokenString); if (jwtTokenString == null || jwtTokenString.isEmpty()) { log.warn("login failed for {}: unknown response code", loginForm.getLoginEmail()); loginForm.setErrorMsg("Login failed: Invalid email/password."); return "login"; } if (RestUtil.isError(response.getStatusCode())) { try { MyErrorResource error = objectMapper.readValue(jwtTokenString, MyErrorResource.class); ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError()); if (exceptionState == ExceptionState.CREDENTIALS_NOT_FOUND_EXCEPTION) { log.warn("login failed for {}: credentials not found", loginForm.getLoginEmail()); loginForm.setErrorMsg("Login failed: Account does not exist. Please register."); return "login"; } log.warn("login failed for {}: {}", loginForm.getLoginEmail(), error.getError()); loginForm.setErrorMsg("Login failed: Invalid email/password."); return "login"; } catch (IOException ioe) { log.warn("IOException {}", ioe); throw new WebServiceRuntimeException(ioe.getMessage()); } } JSONObject tokenObject = new JSONObject(jwtTokenString); String token = tokenObject.getString("token"); String id = tokenObject.getString("id"); String role = ""; if (tokenObject.getJSONArray("roles") != null) { role = tokenObject.getJSONArray("roles").get(0).toString(); } if (token.trim().isEmpty() || id.trim().isEmpty() || role.trim().isEmpty()) { log.warn("login failed for {}: empty id {} or token {} or role {}", loginForm.getLoginEmail(), id, token, role); loginForm.setErrorMsg("Login failed: Invalid email/password."); return "login"; } // now check user status to decide what to show to the user User2 user = invokeAndExtractUserInfo(id); try { String userStatus = user.getStatus(); boolean emailVerified = user.getEmailVerified(); if (UserStatus.FROZEN.toString().equals(userStatus)) { log.warn("User {} login failed: account has been frozen", id); loginForm.setErrorMsg("Login Failed: Account Frozen. Please contact " + CONTACT_EMAIL); return "login"; } else if (!emailVerified || (UserStatus.CREATED.toString()).equals(userStatus)) { redirectAttributes.addAttribute("statuschecklist", userStatus); log.info("User {} not validated, redirected to email verification page", id); return "redirect:/email_checklist"; } else if ((UserStatus.PENDING.toString()).equals(userStatus)) { redirectAttributes.addAttribute("statuschecklist", userStatus); log.info("User {} not approved, redirected to application pending page", id); return "redirect:/email_checklist"; } else if ((UserStatus.APPROVED.toString()).equals(userStatus)) { // set session variables setSessionVariables(session, loginForm.getLoginEmail(), id, user.getFirstName(), role, token); log.info("login success for {}, id: {}", loginForm.getLoginEmail(), id); return "redirect:/dashboard"; } else { log.warn("login failed for user {}: account is rejected or closed", id); loginForm.setErrorMsg("Login Failed: Account Rejected/Closed."); return "login"; } } catch (Exception e) { log.warn("Error parsing json object for user: {}", e.getMessage()); loginForm.setErrorMsg(ERR_SERVER_OVERLOAD); return "login"; } } // triggered when user clicks "Forget Password?" @RequestMapping("/password_reset_email") public String passwordResetEmail(Model model) { model.addAttribute("passwordResetRequestForm", new PasswordResetRequestForm()); return FORGET_PSWD_PAGE; } // triggered when user clicks "Send Reset Email" button @PostMapping("/password_reset_request") public String sendPasswordResetRequest( @ModelAttribute("passwordResetRequestForm") PasswordResetRequestForm passwordResetRequestForm ) throws WebServiceRuntimeException { String email = passwordResetRequestForm.getEmail(); if (!VALID_EMAIL_ADDRESS_REGEX.matcher(email).matches()) { passwordResetRequestForm.setErrMsg("Please provide a valid email address"); return FORGET_PSWD_PAGE; } JSONObject obj = new JSONObject(); obj.put("username", email); log.info("Connecting to sio for password reset email: {}", email); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); HttpEntity<String> request = new HttpEntity<>(obj.toString(), headers); restTemplate.setErrorHandler(new MyResponseErrorHandler()); ResponseEntity response = null; try { response = restTemplate.exchange(properties.getPasswordResetRequestURI(), HttpMethod.POST, request, String.class); } catch (RestClientException e) { log.warn("Cannot connect to sio for password reset email: {}", e); passwordResetRequestForm.setErrMsg("Cannot connect. Server may be down!"); return FORGET_PSWD_PAGE; } if (RestUtil.isError(response.getStatusCode())) { log.warn("Server responded error for password reset email: {}", response.getStatusCode()); passwordResetRequestForm.setErrMsg("Email not registered. Please use a different email address."); return FORGET_PSWD_PAGE; } log.info("Password reset email sent for {}", email); return "password_reset_email_sent"; } // triggered when user clicks password reset link in the email @RequestMapping(path = "/passwordReset", params = {"key"}) public String passwordResetNewPassword(@NotNull @RequestParam("key") final String key, Model model) { PasswordResetForm form = new PasswordResetForm(); form.setKey(key); model.addAttribute("passwordResetForm", form); // redirect to the page for user to enter new password return FORGET_PSWD_NEW_PSWD_PAGE; } // actual call to sio to reset password @RequestMapping(path = "/password_reset") public String resetPassword(@ModelAttribute("passwordResetForm") PasswordResetForm passwordResetForm) throws IOException { if (!passwordResetForm.isPasswordOk()) { return FORGET_PSWD_NEW_PSWD_PAGE; } JSONObject obj = new JSONObject(); obj.put("key", passwordResetForm.getKey()); obj.put("new", passwordResetForm.getPassword1()); log.info("Connecting to sio for password reset, key = {}", passwordResetForm.getKey()); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); HttpEntity<String> request = new HttpEntity<>(obj.toString(), headers); restTemplate.setErrorHandler(new MyResponseErrorHandler()); ResponseEntity response = null; try { response = restTemplate.exchange(properties.getPasswordResetURI(), HttpMethod.PUT, request, String.class); } catch (RestClientException e) { log.warn("Error connecting to sio for password reset! {}", e); passwordResetForm.setErrMsg("Cannot connect to server! Please try again later."); return FORGET_PSWD_NEW_PSWD_PAGE; } if (RestUtil.isError(response.getStatusCode())) { EnumMap<ExceptionState, String> exceptionMessageMap = new EnumMap<>(ExceptionState.class); exceptionMessageMap.put(PASSWORD_RESET_REQUEST_TIMEOUT_EXCEPTION, "Password reset request timed out. Please request a new reset email."); exceptionMessageMap.put(PASSWORD_RESET_REQUEST_NOT_FOUND_EXCEPTION, "Invalid password reset request. Please request a new reset email."); exceptionMessageMap.put(ADAPTER_CONNECTION_EXCEPTION, "Server-side error. Please contact " + CONTACT_EMAIL); MyErrorResource error = objectMapper.readValue(response.getBody().toString(), MyErrorResource.class); ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError()); final String errMsg = exceptionMessageMap.get(exceptionState) == null ? ERR_SERVER_OVERLOAD : exceptionMessageMap.get(exceptionState); passwordResetForm.setErrMsg(errMsg); log.warn("Server responded error for password reset: {}", exceptionState.toString()); return FORGET_PSWD_NEW_PSWD_PAGE; } log.info("Password was reset, key = {}", passwordResetForm.getKey()); return "password_reset_success"; } @RequestMapping("/dashboard") public String dashboard(Model model, HttpSession session) throws WebServiceRuntimeException { HttpEntity<String> request = createHttpEntityHeaderOnly(); restTemplate.setErrorHandler(new MyResponseErrorHandler()); ResponseEntity response = restTemplate.exchange(properties.getDeterUid(session.getAttribute(webProperties.getSessionUserId()).toString()), HttpMethod.GET, request, String.class); String responseBody = response.getBody().toString(); try { if (RestUtil.isError(response.getStatusCode())) { log.error("No user exists : {}", session.getAttribute(webProperties.getSessionUserId())); MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class); model.addAttribute(DETER_UID, CONNECTION_ERROR); } else { log.info("Show the deter user id: {}", responseBody); model.addAttribute(DETER_UID, responseBody); } } catch (IOException e) { throw new WebServiceRuntimeException(e.getMessage()); } // retrieve user dashboard stats Map<String, Integer> userDashboardMap = getUserDashboardStats(session.getAttribute(webProperties.getSessionUserId()).toString()); List<TeamUsageInfo> usageInfoList = getTeamsUsageStatisticsForUser(session.getAttribute(webProperties.getSessionUserId()).toString()); model.addAttribute("userDashboardMap", userDashboardMap); model.addAttribute("usageInfoList", usageInfoList); return "dashboard"; } @RequestMapping(value = "/logout", method = RequestMethod.GET) public String logout(HttpSession session) { removeSessionVariables(session); return "redirect:/"; } //--------------------------Sign Up Page-------------------------- @RequestMapping(value = "/signup2", method = RequestMethod.GET) public String signup2(Model model, HttpServletRequest request) { Map<String, ?> inputFlashMap = RequestContextUtils.getInputFlashMap(request); if (inputFlashMap != null) { log.debug((String) inputFlashMap.get(MESSAGE)); model.addAttribute("signUpMergedForm", (SignUpMergedForm) inputFlashMap.get("signUpMergedForm")); } else { log.debug("InputFlashMap is null"); model.addAttribute("signUpMergedForm", new SignUpMergedForm()); } return "signup2"; } @RequestMapping(value = "/signup2", method = RequestMethod.POST) public String validateDetails( @Valid @ModelAttribute("signUpMergedForm") SignUpMergedForm signUpMergedForm, BindingResult bindingResult, final RedirectAttributes redirectAttributes) throws WebServiceRuntimeException { if (bindingResult.hasErrors() || signUpMergedForm.getIsValid() == false) { log.warn("Register form has errors {}", signUpMergedForm.toString()); return "signup2"; } if (!signUpMergedForm.getHasAcceptTeamOwnerPolicy()) { signUpMergedForm.setErrorTeamOwnerPolicy("Please accept the team owner policy"); log.warn("Policy not accepted"); return "signup2"; } // get form fields // craft the registration json JSONObject mainObject = new JSONObject(); JSONObject credentialsFields = new JSONObject(); credentialsFields.put("username", signUpMergedForm.getEmail().trim()); credentialsFields.put("password", signUpMergedForm.getPassword()); // create the user JSON JSONObject userFields = new JSONObject(); JSONObject userDetails = new JSONObject(); JSONObject addressDetails = new JSONObject(); userDetails.put("firstName", signUpMergedForm.getFirstName().trim()); userDetails.put("lastName", signUpMergedForm.getLastName().trim()); userDetails.put("jobTitle", signUpMergedForm.getJobTitle().trim()); userDetails.put("email", signUpMergedForm.getEmail().trim()); userDetails.put("phone", signUpMergedForm.getPhone().trim()); userDetails.put("institution", signUpMergedForm.getInstitution().trim()); userDetails.put("institutionAbbreviation", signUpMergedForm.getInstitutionAbbreviation().trim()); userDetails.put("institutionWeb", signUpMergedForm.getWebsite().trim()); userDetails.put("address", addressDetails); addressDetails.put("address1", signUpMergedForm.getAddress1().trim()); addressDetails.put("address2", signUpMergedForm.getAddress2().trim()); addressDetails.put("country", signUpMergedForm.getCountry().trim()); addressDetails.put("region", signUpMergedForm.getProvince().trim()); addressDetails.put("city", signUpMergedForm.getCity().trim()); addressDetails.put("zipCode", signUpMergedForm.getPostalCode().trim()); userFields.put("userDetails", userDetails); userFields.put("applicationDate", ZonedDateTime.now()); JSONObject teamFields = new JSONObject(); // add all to main json mainObject.put("credentials", credentialsFields); mainObject.put("user", userFields); mainObject.put("team", teamFields); // check if user chose create new team or join existing team by checking team name String createNewTeamName = signUpMergedForm.getTeamName().trim(); String joinNewTeamName = signUpMergedForm.getJoinTeamName().trim(); if (createNewTeamName != null && !createNewTeamName.isEmpty()) { log.info("Signup new team name {}", createNewTeamName); boolean errorsFound = false; if (createNewTeamName.length() < 2 || createNewTeamName.length() > 12) { errorsFound = true; signUpMergedForm.setErrorTeamName("Team name must be 2 to 12 alphabetic/numeric characters"); } if (signUpMergedForm.getTeamDescription() == null || signUpMergedForm.getTeamDescription().isEmpty()) { errorsFound = true; signUpMergedForm.setErrorTeamDescription("Team description cannot be empty"); } if (signUpMergedForm.getTeamWebsite() == null || signUpMergedForm.getTeamWebsite().isEmpty()) { errorsFound = true; signUpMergedForm.setErrorTeamWebsite("Team website cannot be empty"); } if (errorsFound) { log.warn("Signup new team error {}", signUpMergedForm.toString()); // clear join team name first before submitting the form signUpMergedForm.setJoinTeamName(null); return "signup2"; } else { teamFields.put("name", signUpMergedForm.getTeamName().trim()); teamFields.put("description", signUpMergedForm.getTeamDescription().trim()); teamFields.put("website", signUpMergedForm.getTeamWebsite().trim()); teamFields.put("organisationType", signUpMergedForm.getTeamOrganizationType()); teamFields.put("visibility", signUpMergedForm.getIsPublic()); mainObject.put("isJoinTeam", false); try { registerUserToDeter(mainObject); } catch ( TeamNotFoundException | TeamNameAlreadyExistsException | UsernameAlreadyExistsException | EmailAlreadyExistsException | InvalidTeamNameException | InvalidPasswordException | DeterLabOperationFailedException e) { redirectAttributes.addFlashAttribute(MESSAGE, e.getMessage()); redirectAttributes.addFlashAttribute("signUpMergedForm", signUpMergedForm); return "redirect:/signup2"; } catch (Exception e) { redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD); redirectAttributes.addFlashAttribute("signUpMergedForm", signUpMergedForm); return "redirect:/signup2"; } log.info("Signup new team success"); return "redirect:/team_application_submitted"; } } else if (joinNewTeamName != null && !joinNewTeamName.isEmpty()) { log.info("Signup join team name {}", joinNewTeamName); // get the team JSON from team name Team2 joinTeamInfo; try { joinTeamInfo = getTeamIdByName(signUpMergedForm.getJoinTeamName().trim()); } catch (TeamNotFoundException | AdapterConnectionException e) { redirectAttributes.addFlashAttribute(MESSAGE, e.getMessage()); redirectAttributes.addFlashAttribute("signUpMergedForm", signUpMergedForm); return "redirect:/signup2"; } teamFields.put("id", joinTeamInfo.getId()); // set the flag to indicate to controller that it is joining an existing team mainObject.put("isJoinTeam", true); try { registerUserToDeter(mainObject); } catch ( TeamNotFoundException | AdapterConnectionException | TeamNameAlreadyExistsException | UsernameAlreadyExistsException | EmailAlreadyExistsException | InvalidTeamNameException | InvalidPasswordException | DeterLabOperationFailedException e) { redirectAttributes.addFlashAttribute(MESSAGE, e.getMessage()); redirectAttributes.addFlashAttribute("signUpMergedForm", signUpMergedForm); return "redirect:/signup2"; } catch (Exception e) { redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD); redirectAttributes.addFlashAttribute("signUpMergedForm", signUpMergedForm); return "redirect:/signup2"; } log.info("Signup join team success"); log.info("jointeam info: {}", joinTeamInfo); redirectAttributes.addFlashAttribute("team", joinTeamInfo); return "redirect:/join_application_submitted"; } else { log.warn("Signup unreachable statement"); // logic error not suppose to reach here // possible if user fill up create new team but without the team name redirectAttributes.addFlashAttribute("signupError", "There is a problem when submitting your form. Please re-enter and submit the details again."); redirectAttributes.addFlashAttribute("signUpMergedForm", signUpMergedForm); return "redirect:/signup2"; } } /** * Use when registering new accounts * * @param mainObject A JSONObject that contains user's credentials, personal details and team application details */ private void registerUserToDeter(JSONObject mainObject) throws WebServiceRuntimeException, TeamNotFoundException, AdapterConnectionException, TeamNameAlreadyExistsException, UsernameAlreadyExistsException, EmailAlreadyExistsException, InvalidTeamNameException, InvalidPasswordException, DeterLabOperationFailedException { HttpEntity<String> request = createHttpEntityWithBodyNoAuthHeader(mainObject.toString()); restTemplate.setErrorHandler(new MyResponseErrorHandler()); ResponseEntity response = restTemplate.exchange(properties.getSioRegUrl(), HttpMethod.POST, request, String.class); String responseBody = response.getBody().toString(); log.info("Register user to deter response: {}", responseBody); try { if (RestUtil.isError(response.getStatusCode())) { MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class); log.warn("Register user exception error: {}", error.getError()); ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError()); final String errorPrefix = "Error: "; switch (exceptionState) { case DETERLAB_OPERATION_FAILED_EXCEPTION: log.warn("Register new user failed on DeterLab: {}", error.getMessage()); throw new DeterLabOperationFailedException(errorPrefix + (error.getMessage().contains("unknown error") ? ERR_SERVER_OVERLOAD : error.getMessage())); case TEAM_NAME_ALREADY_EXISTS_EXCEPTION: log.warn("Register new users new team request : team name already exists"); throw new TeamNameAlreadyExistsException("Team name already exists"); case INVALID_TEAM_NAME_EXCEPTION: log.warn("Register new users new team request : team name invalid"); throw new InvalidTeamNameException("Invalid team name: must be 6-12 alphanumeric characters only"); case INVALID_PASSWORD_EXCEPTION: log.warn("Register new users new team request : invalid password"); throw new InvalidPasswordException("Password is too simple"); case USERNAME_ALREADY_EXISTS_EXCEPTION: // throw from user service { String email = mainObject.getJSONObject("user").getJSONObject("userDetails").getString("email"); log.warn("Register new users : email already exists: {}", email); throw new UsernameAlreadyExistsException(errorPrefix + email + " already in use."); } case EMAIL_ALREADY_EXISTS_EXCEPTION: // throw from adapter deterlab { String email = mainObject.getJSONObject("user").getJSONObject("userDetails").getString("email"); log.warn("Register new users : email already exists: {}", email); throw new EmailAlreadyExistsException(errorPrefix + email + " already in use."); } default: log.warn("Registration or adapter connection fail"); // possible sio or adapter connection fail throw new AdapterConnectionException(ERR_SERVER_OVERLOAD); } } else { // do nothing log.info("Not an error for status code: {}", response.getStatusCode()); } } catch (IOException e) { throw new WebServiceRuntimeException(e.getMessage()); } } /** * Use when users register a new account for joining existing team * * @param teamName The team name to join * @return the team id from sio */ private Team2 getTeamIdByName(String teamName) throws WebServiceRuntimeException, TeamNotFoundException, AdapterConnectionException { // FIXME check if team name exists // FIXME check for general exception? HttpEntity<String> request = createHttpEntityHeaderOnlyNoAuthHeader(); restTemplate.setErrorHandler(new MyResponseErrorHandler()); ResponseEntity response = restTemplate.exchange(properties.getTeamByName(teamName), HttpMethod.GET, request, String.class); String responseBody = response.getBody().toString(); try { if (RestUtil.isError(response.getStatusCode())) { MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class); ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError()); if (exceptionState == ExceptionState.TEAM_NOT_FOUND_EXCEPTION) { log.warn("Get team by name : team name error"); throw new TeamNotFoundException("Team name " + teamName + " does not exists"); } else { log.warn("Team service or adapter connection fail"); // possible sio or adapter connection fail throw new AdapterConnectionException(ERR_SERVER_OVERLOAD); } } else { return extractTeamInfo(responseBody); } } catch (IOException e) { throw new WebServiceRuntimeException(e.getMessage()); } } //--------------------------Account Settings Page-------------------------- @RequestMapping(value = "/account_settings", method = RequestMethod.GET) public String accountDetails(Model model, HttpSession session) throws WebServiceRuntimeException { String userId_uri = properties.getSioUsersUrl() + session.getAttribute("id"); HttpEntity<String> request = createHttpEntityHeaderOnly(); restTemplate.setErrorHandler(new MyResponseErrorHandler()); ResponseEntity response = restTemplate.exchange(userId_uri, HttpMethod.GET, request, String.class); String responseBody = response.getBody().toString(); try { if (RestUtil.isError(response.getStatusCode())) { log.error("No user to edit : {}", session.getAttribute("id")); MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class); throw new RestClientException("[" + error.getError() + "] "); } else { User2 user2 = extractUserInfo(responseBody); // need to do this so that we can compare after submitting the form session.setAttribute(webProperties.getSessionUserAccount(), user2); model.addAttribute("editUser", user2); return "account_settings"; } } catch (IOException e) { throw new WebServiceRuntimeException(e.getMessage()); } } @RequestMapping(value = "/account_settings", method = RequestMethod.POST) public String editAccountDetails( @ModelAttribute("editUser") User2 editUser, final RedirectAttributes redirectAttributes, HttpSession session) throws WebServiceRuntimeException { boolean errorsFound = false; String editPhrase = "editPhrase"; // check fields first if (errorsFound == false && editUser.getFirstName().isEmpty()) { redirectAttributes.addFlashAttribute("editFirstName", "fail"); errorsFound = true; } if (errorsFound == false && editUser.getLastName().isEmpty()) { redirectAttributes.addFlashAttribute("editLastName", "fail"); errorsFound = true; } if (errorsFound == false && editUser.getPhone().isEmpty()) { redirectAttributes.addFlashAttribute("editPhone", "fail"); errorsFound = true; } if (errorsFound == false && (editUser.getPhone().matches("(.*)[a-zA-Z](.*)") || editUser.getPhone().length() < 6)) { // previously already check if phone is empty // now check phone must contain only digits redirectAttributes.addFlashAttribute("editPhone", "fail"); errorsFound = true; } if (errorsFound == false && !editUser.getConfirmPassword().isEmpty() && !editUser.isPasswordValid()) { redirectAttributes.addFlashAttribute(editPhrase, "invalid"); errorsFound = true; } if (errorsFound == false && editUser.getJobTitle().isEmpty()) { redirectAttributes.addFlashAttribute("editJobTitle", "fail"); errorsFound = true; } if (errorsFound == false && editUser.getInstitution().isEmpty()) { redirectAttributes.addFlashAttribute("editInstitution", "fail"); errorsFound = true; } if (errorsFound == false && editUser.getCountry().isEmpty()) { redirectAttributes.addFlashAttribute("editCountry", "fail"); errorsFound = true; } if (errorsFound) { session.removeAttribute(webProperties.getSessionUserAccount()); return "redirect:/account_settings"; } else { // used to compare original and edited User2 objects User2 originalUser = (User2) session.getAttribute(webProperties.getSessionUserAccount()); JSONObject userObject = new JSONObject(); JSONObject userDetails = new JSONObject(); JSONObject address = new JSONObject(); userDetails.put("firstName", editUser.getFirstName()); userDetails.put("lastName", editUser.getLastName()); userDetails.put("email", editUser.getEmail()); userDetails.put("phone", editUser.getPhone()); userDetails.put("jobTitle", editUser.getJobTitle()); userDetails.put("address", address); userDetails.put("institution", editUser.getInstitution()); userDetails.put("institutionAbbreviation", originalUser.getInstitutionAbbreviation()); userDetails.put("institutionWeb", originalUser.getInstitutionWeb()); address.put("address1", originalUser.getAddress1()); address.put("address2", originalUser.getAddress2()); address.put("country", editUser.getCountry()); address.put("city", originalUser.getCity()); address.put("region", originalUser.getRegion()); address.put("zipCode", originalUser.getPostalCode()); userObject.put("userDetails", userDetails); String userId_uri = properties.getSioUsersUrl() + session.getAttribute(webProperties.getSessionUserId()); HttpEntity<String> request = createHttpEntityWithBody(userObject.toString()); restTemplate.exchange(userId_uri, HttpMethod.PUT, request, String.class); if (!originalUser.getFirstName().equals(editUser.getFirstName())) { redirectAttributes.addFlashAttribute("editFirstName", "success"); } if (!originalUser.getLastName().equals(editUser.getLastName())) { redirectAttributes.addFlashAttribute("editLastName", "success"); } if (!originalUser.getPhone().equals(editUser.getPhone())) { redirectAttributes.addFlashAttribute("editPhone", "success"); } if (!originalUser.getJobTitle().equals(editUser.getJobTitle())) { redirectAttributes.addFlashAttribute("editJobTitle", "success"); } if (!originalUser.getInstitution().equals(editUser.getInstitution())) { redirectAttributes.addFlashAttribute("editInstitution", "success"); } if (!originalUser.getCountry().equals(editUser.getCountry())) { redirectAttributes.addFlashAttribute("editCountry", "success"); } // credential service change password if (editUser.isPasswordMatch()) { JSONObject credObject = new JSONObject(); credObject.put("password", editUser.getPassword()); HttpEntity<String> credRequest = createHttpEntityWithBody(credObject.toString()); restTemplate.setErrorHandler(new MyResponseErrorHandler()); ResponseEntity response = restTemplate.exchange(properties.getUpdateCredentials(session.getAttribute("id").toString()), HttpMethod.PUT, credRequest, String.class); String responseBody = response.getBody().toString(); try { if (RestUtil.isError(response.getStatusCode())) { MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class); redirectAttributes.addFlashAttribute(editPhrase, "fail"); } else { redirectAttributes.addFlashAttribute(editPhrase, "success"); } } catch (IOException e) { throw new WebServiceRuntimeException(e.getMessage()); } finally { session.removeAttribute(webProperties.getSessionUserAccount()); } } } return "redirect:/account_settings"; } //--------------------User Side Approve Members Page------------ @RequestMapping("/approve_new_user") public String approveNewUser(Model model, HttpSession session) throws Exception { // HashMap<Integer, Team> rv = new HashMap<Integer, Team>(); // rv = teamManager.getTeamMapByTeamOwner(getSessionIdOfLoggedInUser(session)); // boolean userHasAnyJoinRequest = hasAnyJoinRequest(rv); // model.addAttribute("teamMapOwnedByUser", rv); // model.addAttribute("userHasAnyJoinRequest", userHasAnyJoinRequest); List<JoinRequestApproval> rv = new ArrayList<>(); List<JoinRequestApproval> temp; // get list of teamids HttpEntity<String> request = createHttpEntityHeaderOnly(); ResponseEntity response = restTemplate.exchange(properties.getUser(session.getAttribute("id").toString()), HttpMethod.GET, request, String.class); String responseBody = response.getBody().toString(); JSONObject object = new JSONObject(responseBody); JSONArray teamIdsJsonArray = object.getJSONArray("teams"); for (int i = 0; i < teamIdsJsonArray.length(); i++) { String teamId = teamIdsJsonArray.get(i).toString(); HttpEntity<String> teamRequest = createHttpEntityHeaderOnly(); ResponseEntity teamResponse = restTemplate.exchange(properties.getTeamById(teamId), HttpMethod.GET, teamRequest, String.class); String teamResponseBody = teamResponse.getBody().toString(); Team2 team2 = new Team2(); JSONObject teamObject = new JSONObject(teamResponseBody); JSONArray membersArray = teamObject.getJSONArray("members"); team2.setId(teamObject.getString("id")); team2.setName(teamObject.getString("name")); boolean isTeamLeader = false; temp = new ArrayList<>(); for (int j = 0; j < membersArray.length(); j++) { JSONObject memberObject = membersArray.getJSONObject(j); String userId = memberObject.getString("userId"); String teamMemberType = memberObject.getString("memberType"); String teamMemberStatus = memberObject.getString("memberStatus"); String teamJoinedDate = formatZonedDateTime(memberObject.get("joinedDate").toString()); JoinRequestApproval joinRequestApproval = new JoinRequestApproval(); if (userId.equals(session.getAttribute("id").toString()) && teamMemberType.equals(MemberType.OWNER.toString())) { isTeamLeader = true; } if (teamMemberStatus.equals(MemberStatus.PENDING.toString()) && teamMemberType.equals(MemberType.MEMBER.toString())) { User2 myUser = invokeAndExtractUserInfo(userId); joinRequestApproval.setUserId(myUser.getId()); joinRequestApproval.setUserEmail(myUser.getEmail()); joinRequestApproval.setUserName(myUser.getFirstName() + " " + myUser.getLastName()); joinRequestApproval.setApplicationDate(teamJoinedDate); joinRequestApproval.setTeamId(team2.getId()); joinRequestApproval.setTeamName(team2.getName()); temp.add(joinRequestApproval); log.info("Join request: UserId: {}, UserEmail: {}", myUser.getId(), myUser.getEmail()); } } if (isTeamLeader) { if (!temp.isEmpty()) { rv.addAll(temp); } } } model.addAttribute("joinApprovalList", rv); return "approve_new_user"; } @RequestMapping("/approve_new_user/accept/{teamId}/{userId}") public String userSideAcceptJoinRequest( @PathVariable String teamId, @PathVariable String userId, HttpSession session, RedirectAttributes redirectAttributes) throws WebServiceRuntimeException { log.info("Approve join request: User {}, Team {}, Approver {}", userId, teamId, session.getAttribute("id").toString()); JSONObject mainObject = new JSONObject(); JSONObject userFields = new JSONObject(); userFields.put("id", session.getAttribute("id").toString()); mainObject.put("user", userFields); HttpEntity<String> request = createHttpEntityWithBody(mainObject.toString()); ResponseEntity response; try { response = restTemplate.exchange(properties.getApproveJoinRequest(teamId, userId), HttpMethod.POST, request, String.class); } catch (RestClientException e) { log.warn("Error connecting to sio team service: {}", e); redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD); return "redirect:/approve_new_user"; } String responseBody = response.getBody().toString(); if (RestUtil.isError(response.getStatusCode())) { try { MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class); ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError()); switch (exceptionState) { case DETERLAB_OPERATION_FAILED_EXCEPTION: log.warn("Approve join request: User {}, Team {} fail", userId, teamId); redirectAttributes.addFlashAttribute(MESSAGE, "Approve join request fail"); break; default: log.warn("Server side error: {}", error.getError()); redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD); break; } return "redirect:/approve_new_user"; } catch (IOException ioe) { log.warn("IOException {}", ioe); throw new WebServiceRuntimeException(ioe.getMessage()); } } // everything looks OK? log.info("Join request has been APPROVED, User {}, Team {}", userId, teamId); redirectAttributes.addFlashAttribute(MESSAGE_SUCCESS, "Join request has been APPROVED."); return "redirect:/approve_new_user"; } @RequestMapping("/approve_new_user/reject/{teamId}/{userId}") public String userSideRejectJoinRequest( @PathVariable String teamId, @PathVariable String userId, HttpSession session, RedirectAttributes redirectAttributes) throws WebServiceRuntimeException { log.info("Reject join request: User {}, Team {}, Approver {}", userId, teamId, session.getAttribute("id").toString()); JSONObject mainObject = new JSONObject(); JSONObject userFields = new JSONObject(); userFields.put("id", session.getAttribute("id").toString()); mainObject.put("user", userFields); HttpEntity<String> request = createHttpEntityWithBody(mainObject.toString()); ResponseEntity response; try { response = restTemplate.exchange(properties.getRejectJoinRequest(teamId, userId), HttpMethod.DELETE, request, String.class); } catch (RestClientException e) { log.warn("Error connecting to sio team service: {}", e); redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD); return "redirect:/approve_new_user"; } String responseBody = response.getBody().toString(); if (RestUtil.isError(response.getStatusCode())) { try { MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class); ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError()); switch (exceptionState) { case DETERLAB_OPERATION_FAILED_EXCEPTION: log.warn("Reject join request: User {}, Team {} fail", userId, teamId); redirectAttributes.addFlashAttribute(MESSAGE, "Reject join request fail"); break; default: log.warn("Server side error: {}", error.getError()); redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD); break; } return "redirect:/approve_new_user"; } catch (IOException ioe) { log.warn("IOException {}", ioe); throw new WebServiceRuntimeException(ioe.getMessage()); } } // everything looks OK? log.info("Join request has been REJECTED, User {}, Team {}", userId, teamId); redirectAttributes.addFlashAttribute(MESSAGE, "Join request has been REJECTED."); return "redirect:/approve_new_user"; } //--------------------------Teams Page-------------------------- @RequestMapping("/public_teams") public String publicTeamsBeforeLogin(Model model) { TeamManager2 teamManager2 = new TeamManager2(); // get public teams HttpEntity<String> teamRequest = createHttpEntityHeaderOnlyNoAuthHeader(); ResponseEntity teamResponse = restTemplate.exchange(properties.getTeamsByVisibility(TeamVisibility.PUBLIC.toString()), HttpMethod.GET, teamRequest, String.class); String teamResponseBody = teamResponse.getBody().toString(); JSONArray teamPublicJsonArray = new JSONArray(teamResponseBody); for (int i = 0; i < teamPublicJsonArray.length(); i++) { JSONObject teamInfoObject = teamPublicJsonArray.getJSONObject(i); Team2 team2 = extractTeamInfo(teamInfoObject.toString()); teamManager2.addTeamToPublicTeamMap(team2); } model.addAttribute("publicTeamMap2", teamManager2.getPublicTeamMap()); return "public_teams"; } @RequestMapping("/teams") public String teams(Model model, HttpSession session) { // int currentLoggedInUserId = getSessionIdOfLoggedInUser(session); // model.addAttribute("infoMsg", teamManager.getInfoMsg()); // model.addAttribute("currentLoggedInUserId", currentLoggedInUserId); // model.addAttribute("teamMap", teamManager.getTeamMap(currentLoggedInUserId)); // model.addAttribute("publicTeamMap", teamManager.getPublicTeamMap()); // model.addAttribute("invitedToParticipateMap2", teamManager.getInvitedToParticipateMap2(currentLoggedInUserId)); // model.addAttribute("joinRequestMap2", teamManager.getJoinRequestTeamMap2(currentLoggedInUserId)); TeamManager2 teamManager2 = new TeamManager2(); // stores the list of images created or in progress of creation by teams // e.g. teamNameA : "created" : [imageA, imageB], "inProgress" : [imageC, imageD] Map<String, Map<String, List<Image>>> imageMap = new HashMap<>(); // get list of teamids HttpEntity<String> request = createHttpEntityHeaderOnly(); ResponseEntity response = restTemplate.exchange(properties.getUser(session.getAttribute("id").toString()), HttpMethod.GET, request, String.class); String responseBody = response.getBody().toString(); JSONObject object = new JSONObject(responseBody); JSONArray teamIdsJsonArray = object.getJSONArray("teams"); String userEmail = object.getJSONObject("userDetails").getString("email"); for (int i = 0; i < teamIdsJsonArray.length(); i++) { String teamId = teamIdsJsonArray.get(i).toString(); HttpEntity<String> teamRequest = createHttpEntityHeaderOnly(); ResponseEntity teamResponse = restTemplate.exchange(properties.getTeamById(teamId), HttpMethod.GET, teamRequest, String.class); String teamResponseBody = teamResponse.getBody().toString(); Team2 team2 = extractTeamInfo(teamResponseBody); teamManager2.addTeamToTeamMap(team2); Team2 joinRequestTeam = extractTeamInfoUserJoinRequest(session.getAttribute("id").toString(), teamResponseBody); if (joinRequestTeam != null) { teamManager2.addTeamToUserJoinRequestTeamMap(joinRequestTeam); } imageMap.put(team2.getName(), invokeAndGetImageList(teamId)); } // check if inner image map is empty, have to do it via this manner // returns true if the team contains an image list boolean isInnerImageMapPresent = imageMap.values().stream().filter(perTeamImageMap -> !perTeamImageMap.isEmpty()).findFirst().isPresent(); model.addAttribute("userEmail", userEmail); model.addAttribute("teamMap2", teamManager2.getTeamMap()); model.addAttribute("userJoinRequestMap", teamManager2.getUserJoinRequestMap()); model.addAttribute("isInnerImageMapPresent", isInnerImageMapPresent); model.addAttribute("imageMap", imageMap); return "teams"; } /** * Exectues the service-image and returns a Map containing the list of images in two partitions. * One partition contains the list of already created images. * The other partition contains the list of currently saving in progress images. * * @param teamId The ncl team id to retrieve the list of images from. * @return Returns a Map containing the list of images in two partitions. */ private Map<String, List<Image>> invokeAndGetImageList(String teamId) { log.info("Getting list of saved images for team {}", teamId); Map<String, List<Image>> resultMap = new HashMap<>(); List<Image> createdImageList = new ArrayList<>(); List<Image> inProgressImageList = new ArrayList<>(); HttpEntity<String> imageRequest = createHttpEntityHeaderOnly(); ResponseEntity imageResponse; try { imageResponse = restTemplate.exchange(properties.getTeamSavedImages(teamId), HttpMethod.GET, imageRequest, String.class); } catch (ResourceAccessException e) { log.warn("Error connecting to image service: {}", e); return new HashMap<>(); } String imageResponseBody = imageResponse.getBody().toString(); String osImageList = new JSONObject(imageResponseBody).getString(teamId); JSONObject osImageObject = new JSONObject(osImageList); log.debug("osImageList: {}", osImageList); log.debug("osImageObject: {}", osImageObject); if (osImageObject == JSONObject.NULL || osImageObject.length() == 0) { log.info("List of saved images for team {} is empty.", teamId); return resultMap; } for (int k = 0; k < osImageObject.names().length(); k++) { String imageName = osImageObject.names().getString(k); String imageStatus = osImageObject.getString(imageName); log.info("Image list for team {}: image name {}, status {}", teamId, imageName, imageStatus); Image image = new Image(); image.setImageName(imageName); image.setDescription("-"); image.setTeamId(teamId); if ("created".equals(imageStatus)) { createdImageList.add(image); } else if ("notfound".equals(imageStatus)) { inProgressImageList.add(image); } } resultMap.put("created", createdImageList); resultMap.put("inProgress", inProgressImageList); return resultMap; } // @RequestMapping("/accept_participation/{teamId}") // public String acceptParticipationRequest(@PathVariable Integer teamId, Model model, HttpSession session) { // int currentLoggedInUserId = getSessionIdOfLoggedInUser(session); // // get user's participation request list // // add this user id to the requested list // teamManager.acceptParticipationRequest(currentLoggedInUserId, teamId); // // remove participation request since accepted // teamManager.removeParticipationRequest(currentLoggedInUserId, teamId); // // // must get team name // String teamName = teamManager.getTeamNameByTeamId(teamId); // teamManager.setInfoMsg("You have just joined Team " + teamName + " !"); // // return "redirect:/teams"; // } // @RequestMapping("/ignore_participation/{teamId}") // public String ignoreParticipationRequest(@PathVariable Integer teamId, Model model, HttpSession session) { // // get user's participation request list // // remove this user id from the requested list // String teamName = teamManager.getTeamNameByTeamId(teamId); // teamManager.ignoreParticipationRequest2(getSessionIdOfLoggedInUser(session), teamId); // teamManager.setInfoMsg("You have just ignored a team request from Team " + teamName + " !"); // // return "redirect:/teams"; // } // @RequestMapping("/withdraw/{teamId}") public String withdrawnJoinRequest(@PathVariable Integer teamId, HttpSession session) { // get user team request // remove this user id from the user's request list String teamName = teamManager.getTeamNameByTeamId(teamId); teamManager.removeUserJoinRequest2(getSessionIdOfLoggedInUser(session), teamId); teamManager.setInfoMsg("You have withdrawn your join request for Team " + teamName); return "redirect:/teams"; } // @RequestMapping(value="/teams/invite_members/{teamId}", method=RequestMethod.GET) // public String inviteMember(@PathVariable Integer teamId, Model model) { // model.addAttribute("teamIdVar", teamId); // model.addAttribute("teamPageInviteMemberForm", new TeamPageInviteMemberForm()); // return "team_page_invite_members"; // } // @RequestMapping(value="/teams/invite_members/{teamId}", method=RequestMethod.POST) // public String sendInvitation(@PathVariable Integer teamId, @ModelAttribute TeamPageInviteMemberForm teamPageInviteMemberForm,Model model) { // int userId = userManager.getUserIdByEmail(teamPageInviteMemberForm.getInviteUserEmail()); // teamManager.addInvitedToParticipateMap(userId, teamId); // return "redirect:/teams"; // } @RequestMapping(value = "/teams/members_approval/{teamId}", method = RequestMethod.GET) public String membersApproval(@PathVariable Integer teamId, Model model) { model.addAttribute("team", teamManager.getTeamByTeamId(teamId)); return "team_page_approve_members"; } @RequestMapping("/teams/members_approval/accept/{teamId}/{userId}") public String acceptJoinRequest(@PathVariable Integer teamId, @PathVariable Integer userId) { teamManager.acceptJoinRequest(userId, teamId); return "redirect:/teams/members_approval/{teamId}"; } @RequestMapping("/teams/members_approval/reject/{teamId}/{userId}") public String rejectJoinRequest(@PathVariable Integer teamId, @PathVariable Integer userId) { teamManager.rejectJoinRequest(userId, teamId); return "redirect:/teams/members_approval/{teamId}"; } //--------------------------Team Profile Page-------------------------- @RequestMapping(value = "/team_profile/{teamId}", method = RequestMethod.GET) public String teamProfile(@PathVariable String teamId, Model model, HttpSession session) { HttpEntity<String> request = createHttpEntityHeaderOnly(); ResponseEntity response = restTemplate.exchange(properties.getTeamById(teamId), HttpMethod.GET, request, String.class); String responseBody = response.getBody().toString(); Team2 team = extractTeamInfo(responseBody); model.addAttribute("team", team); model.addAttribute("owner", team.getOwner()); model.addAttribute("membersList", team.getMembersList()); session.setAttribute("originalTeam", team); request = createHttpEntityHeaderOnly(); response = restTemplate.exchange(properties.getExpListByTeamId(teamId), HttpMethod.GET, request, String.class); JSONArray experimentsArray = new JSONArray(response.getBody().toString()); List<Experiment2> experimentList = new ArrayList<>(); Map<Long, Realization> realizationMap = new HashMap<>(); for (int k = 0; k < experimentsArray.length(); k++) { Experiment2 experiment2 = extractExperiment(experimentsArray.getJSONObject(k).toString()); Realization realization = invokeAndExtractRealization(experiment2.getTeamName(), experiment2.getId()); realizationMap.put(experiment2.getId(), realization); experimentList.add(experiment2); } model.addAttribute("experimentList", experimentList); model.addAttribute("realizationMap", realizationMap); return "team_profile"; } @RequestMapping(value = "/team_profile/{teamId}", method = RequestMethod.POST) public String editTeamProfile( @PathVariable String teamId, @ModelAttribute("team") Team2 editTeam, final RedirectAttributes redirectAttributes, HttpSession session) { boolean errorsFound = false; if (editTeam.getDescription().isEmpty()) { errorsFound = true; redirectAttributes.addFlashAttribute("editDesc", "fail"); } if (errorsFound) { // safer to remove session.removeAttribute("originalTeam"); return "redirect:/team_profile/" + editTeam.getId(); } // can edit team description and team website for now JSONObject teamfields = new JSONObject(); teamfields.put("id", teamId); teamfields.put("name", editTeam.getName()); teamfields.put("description", editTeam.getDescription()); teamfields.put("website", "http://default.com"); teamfields.put("organisationType", editTeam.getOrganisationType()); teamfields.put("privacy", "OPEN"); teamfields.put("status", editTeam.getStatus()); teamfields.put("members", editTeam.getMembersList()); HttpEntity<String> request = createHttpEntityWithBody(teamfields.toString()); ResponseEntity response = restTemplate.exchange(properties.getTeamById(teamId), HttpMethod.PUT, request, String.class); Team2 originalTeam = (Team2) session.getAttribute("originalTeam"); if (!originalTeam.getDescription().equals(editTeam.getDescription())) { redirectAttributes.addFlashAttribute("editDesc", "success"); } // safer to remove session.removeAttribute("originalTeam"); return "redirect:/team_profile/" + teamId; } @RequestMapping("/remove_member/{teamId}/{userId}") public String removeMember(@PathVariable Integer teamId, @PathVariable Integer userId, Model model) { // TODO check if user is indeed in the team // TODO what happens to active experiments of the user? // remove member from the team // reduce the team count teamManager.removeMembers(userId, teamId); return "redirect:/team_profile/{teamId}"; } // @RequestMapping("/team_profile/{teamId}/start_experiment/{expId}") // public String startExperimentFromTeamProfile(@PathVariable Integer teamId, @PathVariable Integer expId, Model model, HttpSession session) { // // start experiment // // ensure experiment is stopped first before starting // experimentManager.startExperiment(getSessionIdOfLoggedInUser(session), expId); // return "redirect:/team_profile/{teamId}"; // } // @RequestMapping("/team_profile/{teamId}/stop_experiment/{expId}") // public String stopExperimentFromTeamProfile(@PathVariable Integer teamId, @PathVariable Integer expId, Model model, HttpSession session) { // // stop experiment // // ensure experiment is in ready mode before stopping // experimentManager.stopExperiment(getSessionIdOfLoggedInUser(session), expId); // return "redirect:/team_profile/{teamId}"; // } // @RequestMapping("/team_profile/{teamId}/remove_experiment/{expId}") // public String removeExperimentFromTeamProfile(@PathVariable Integer teamId, @PathVariable Integer expId, Model model, HttpSession session) { // // remove experiment // // TODO check userid is indeed the experiment owner or team owner // // ensure experiment is stopped first // if (experimentManager.removeExperiment(getSessionIdOfLoggedInUser(session), expId) == true) { // // decrease exp count to be display on Teams page // teamManager.decrementExperimentCount(teamId); // } // model.addAttribute("experimentList", experimentManager.getExperimentListByExperimentOwner(getSessionIdOfLoggedInUser(session))); // return "redirect:/team_profile/{teamId}"; // } // @RequestMapping(value="/team_profile/invite_user/{teamId}", method=RequestMethod.GET) // public String inviteUserFromTeamProfile(@PathVariable Integer teamId, Model model) { // model.addAttribute("teamIdVar", teamId); // model.addAttribute("teamPageInviteMemberForm", new TeamPageInviteMemberForm()); // return "team_profile_invite_members"; // } // @RequestMapping(value="/team_profile/invite_user/{teamId}", method=RequestMethod.POST) // public String sendInvitationFromTeamProfile(@PathVariable Integer teamId, @ModelAttribute TeamPageInviteMemberForm teamPageInviteMemberForm, Model model) { // int userId = userManager.getUserIdByEmail(teamPageInviteMemberForm.getInviteUserEmail()); // teamManager.addInvitedToParticipateMap(userId, teamId); // return "redirect:/team_profile/{teamId}"; // } //--------------------------Apply for New Team Page-------------------------- @RequestMapping(value = "/teams/apply_team", method = RequestMethod.GET) public String teamPageApplyTeam(Model model) { model.addAttribute("teamPageApplyTeamForm", new TeamPageApplyTeamForm()); return "team_page_apply_team"; } @RequestMapping(value = "/teams/apply_team", method = RequestMethod.POST) public String checkApplyTeamInfo( @Valid TeamPageApplyTeamForm teamPageApplyTeamForm, BindingResult bindingResult, HttpSession session, final RedirectAttributes redirectAttributes) throws WebServiceRuntimeException { final String logPrefix = "Existing user apply for new team: {}"; if (bindingResult.hasErrors()) { log.warn(logPrefix, "Application form error " + teamPageApplyTeamForm.toString()); return "team_page_apply_team"; } // log data to ensure data has been parsed log.debug(logPrefix, properties.getRegisterRequestToApplyTeam(session.getAttribute("id").toString())); log.info(logPrefix, teamPageApplyTeamForm.toString()); JSONObject mainObject = new JSONObject(); JSONObject teamFields = new JSONObject(); mainObject.put("team", teamFields); teamFields.put("name", teamPageApplyTeamForm.getTeamName()); teamFields.put("description", teamPageApplyTeamForm.getTeamDescription()); teamFields.put("website", teamPageApplyTeamForm.getTeamWebsite()); teamFields.put("organisationType", teamPageApplyTeamForm.getTeamOrganizationType()); teamFields.put("visibility", teamPageApplyTeamForm.getIsPublic()); String nclUserId = session.getAttribute("id").toString(); HttpEntity<String> request = createHttpEntityWithBody(mainObject.toString()); ResponseEntity response; try { response = restTemplate.exchange(properties.getRegisterRequestToApplyTeam(nclUserId), HttpMethod.POST, request, String.class); String responseBody = response.getBody().toString(); if (RestUtil.isError(response.getStatusCode())) { // prepare the exception mapping EnumMap<ExceptionState, String> exceptionMessageMap = new EnumMap<>(ExceptionState.class); exceptionMessageMap.put(USER_ID_NULL_OR_EMPTY_EXCEPTION, "User id is null or empty "); exceptionMessageMap.put(TEAM_NAME_NULL_OR_EMPTY_EXCEPTION, "Team name is null or empty "); exceptionMessageMap.put(USER_NOT_FOUND_EXCEPTION, "User not found"); exceptionMessageMap.put(TEAM_NAME_ALREADY_EXISTS_EXCEPTION, "Team name already exists"); exceptionMessageMap.put(INVALID_TEAM_NAME_EXCEPTION, "Team name contains invalid characters"); exceptionMessageMap.put(TEAM_MEMBER_ALREADY_EXISTS_EXCEPTION, "Team member already exists"); exceptionMessageMap.put(ADAPTER_CONNECTION_EXCEPTION, "Connection to adapter failed"); exceptionMessageMap.put(ADAPTER_INTERNAL_ERROR_EXCEPTION, "Internal server error on adapter"); exceptionMessageMap.put(DETERLAB_OPERATION_FAILED_EXCEPTION, "Operation failed on DeterLab"); MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class); ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError()); final String errorMessage = exceptionMessageMap.containsKey(exceptionState) ? error.getMessage() : ERR_SERVER_OVERLOAD; log.warn(logPrefix, responseBody); redirectAttributes.addFlashAttribute("message", errorMessage); return "redirect:/teams/apply_team"; } else { // no errors, everything ok log.info (logPrefix, "Application for team " + teamPageApplyTeamForm.getTeamName() + " submitted"); return "redirect:/teams/team_application_submitted"; } } catch (ResourceAccessException | IOException e) { log.error(logPrefix, e); throw new WebServiceRuntimeException(e.getMessage()); } } @RequestMapping(value = "/acceptable_usage_policy", method = RequestMethod.GET) public String teamOwnerPolicy() { return "acceptable_usage_policy"; } @RequestMapping(value = "/terms_and_conditions", method = RequestMethod.GET) public String termsAndConditions() { return "terms_and_conditions"; } //--------------------------Join Team Page-------------------------- @RequestMapping(value = "/teams/join_team", method = RequestMethod.GET) public String teamPageJoinTeam(Model model) { model.addAttribute("teamPageJoinTeamForm", new TeamPageJoinTeamForm()); return "team_page_join_team"; } @RequestMapping(value = "/teams/join_team", method = RequestMethod.POST) public String checkJoinTeamInfo( @Valid TeamPageJoinTeamForm teamPageJoinForm, BindingResult bindingResult, Model model, HttpSession session, final RedirectAttributes redirectAttributes) throws WebServiceRuntimeException { final String logPrefix = "Existing user join team: {}"; if (bindingResult.hasErrors()) { log.warn(logPrefix, "Application form error " + teamPageJoinForm.toString()); return "team_page_join_team"; } JSONObject mainObject = new JSONObject(); JSONObject teamFields = new JSONObject(); JSONObject userFields = new JSONObject(); mainObject.put("team", teamFields); mainObject.put("user", userFields); userFields.put("id", session.getAttribute("id")); // ncl-id teamFields.put("name", teamPageJoinForm.getTeamName()); log.info(logPrefix, "User " + session.getAttribute("id") + ", team " + teamPageJoinForm.getTeamName()); HttpEntity<String> request = createHttpEntityWithBody(mainObject.toString()); ResponseEntity response; try { restTemplate.setErrorHandler(new MyResponseErrorHandler()); response = restTemplate.exchange(properties.getJoinRequestExistingUser(), HttpMethod.POST, request, String.class); String responseBody = response.getBody().toString(); if (RestUtil.isError(response.getStatusCode())) { // prepare the exception mapping EnumMap<ExceptionState, String> exceptionMessageMap = new EnumMap<>(ExceptionState.class); exceptionMessageMap.put(USER_NOT_FOUND_EXCEPTION, "User not found"); exceptionMessageMap.put(USER_ID_NULL_OR_EMPTY_EXCEPTION, "User id is null or empty"); exceptionMessageMap.put(TEAM_NOT_FOUND_EXCEPTION, "Team name not found"); exceptionMessageMap.put(TEAM_NAME_NULL_OR_EMPTY_EXCEPTION, "Team name is null or empty"); exceptionMessageMap.put(USER_ALREADY_IN_TEAM_EXCEPTION, "User already in team"); exceptionMessageMap.put(TEAM_MEMBER_ALREADY_EXISTS_EXCEPTION, "Team member already exists"); exceptionMessageMap.put(ADAPTER_CONNECTION_EXCEPTION, "Connection to adapter failed"); exceptionMessageMap.put(ADAPTER_INTERNAL_ERROR_EXCEPTION, "Internal server error on adapter"); exceptionMessageMap.put(DETERLAB_OPERATION_FAILED_EXCEPTION, "Operation failed on DeterLab"); MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class); ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError()); final String errorMessage = exceptionMessageMap.containsKey(exceptionState) ? error.getMessage() : ERR_SERVER_OVERLOAD; log.warn(logPrefix, responseBody); redirectAttributes.addFlashAttribute("message", errorMessage); return "redirect:/teams/join_team"; } else { log.info(logPrefix, "Application for join team " + teamPageJoinForm.getTeamName()+ " submitted"); return "redirect:/teams/join_application_submitted/" + teamPageJoinForm.getTeamName(); } } catch (ResourceAccessException | IOException e) { throw new WebServiceRuntimeException(e.getMessage()); } } //--------------------------Experiment Page-------------------------- @RequestMapping(value = "/experiments", method = RequestMethod.GET) public String experiments(Model model, HttpSession session) throws WebServiceRuntimeException { // long start = System.currentTimeMillis(); List<Experiment2> experimentList = new ArrayList<>(); Map<Long, Realization> realizationMap = new HashMap<>(); HttpEntity<String> request = createHttpEntityHeaderOnly(); restTemplate.setErrorHandler(new MyResponseErrorHandler()); ResponseEntity response = restTemplate.exchange(properties.getDeterUid(session.getAttribute("id").toString()), HttpMethod.GET, request, String.class); String responseBody = response.getBody().toString(); try { if (RestUtil.isError(response.getStatusCode())) { log.error("No user to get experiment: {}", session.getAttribute("id")); MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class); log.info("experiment error: {} - {} - {} - user token:{}", error.getError(), error.getMessage(), error.getLocalizedMessage(), httpScopedSession.getAttribute(webProperties.getSessionJwtToken())); model.addAttribute(DETER_UID, CONNECTION_ERROR); } else { log.info("Show the deter user id: {}", responseBody); model.addAttribute(DETER_UID, responseBody); } } catch (IOException e) { throw new WebServiceRuntimeException(e.getMessage()); } // get list of teamids ResponseEntity userRespEntity = restTemplate.exchange(properties.getUser(session.getAttribute("id").toString()), HttpMethod.GET, request, String.class); JSONObject object = new JSONObject(userRespEntity.getBody().toString()); JSONArray teamIdsJsonArray = object.getJSONArray("teams"); for (int i = 0; i < teamIdsJsonArray.length(); i++) { String teamId = teamIdsJsonArray.get(i).toString(); HttpEntity<String> teamRequest = createHttpEntityHeaderOnly(); ResponseEntity teamResponse = restTemplate.exchange(properties.getTeamById(teamId), HttpMethod.GET, teamRequest, String.class); String teamResponseBody = teamResponse.getBody().toString(); if (!isMemberJoinRequestPending(session.getAttribute("id").toString(), teamResponseBody)) { // get experiments lists of the teams HttpEntity<String> expRequest = createHttpEntityHeaderOnly(); ResponseEntity expRespEntity = restTemplate.exchange(properties.getExpListByTeamId(teamId), HttpMethod.GET, expRequest, String.class); JSONArray experimentsArray = new JSONArray(expRespEntity.getBody().toString()); for (int k = 0; k < experimentsArray.length(); k++) { Experiment2 experiment2 = extractExperiment(experimentsArray.getJSONObject(k).toString()); Realization realization = invokeAndExtractRealization(experiment2.getTeamName(), experiment2.getId()); realizationMap.put(experiment2.getId(), realization); experimentList.add(experiment2); } } } model.addAttribute("experimentList", experimentList); model.addAttribute("realizationMap", realizationMap); // System.out.println("Elapsed time to get experiment page:" + (System.currentTimeMillis() - start)); return "experiments"; } @RequestMapping(value = "/experiments/create", method = RequestMethod.GET) public String createExperiment(Model model, HttpSession session) throws WebServiceRuntimeException { log.info("Loading create experiment page"); // a list of teams that the logged in user is in List<String> scenarioFileNameList = getScenarioFileNameList(); List<Team2> userTeamsList = new ArrayList<>(); // get list of teamids HttpEntity<String> request = createHttpEntityHeaderOnly(); ResponseEntity response = restTemplate.exchange(properties.getUser(session.getAttribute("id").toString()), HttpMethod.GET, request, String.class); String responseBody = response.getBody().toString(); JSONObject object = new JSONObject(responseBody); JSONArray teamIdsJsonArray = object.getJSONArray("teams"); for (int i = 0; i < teamIdsJsonArray.length(); i++) { String teamId = teamIdsJsonArray.get(i).toString(); HttpEntity<String> teamRequest = createHttpEntityHeaderOnly(); ResponseEntity teamResponse = restTemplate.exchange(properties.getTeamById(teamId), HttpMethod.GET, teamRequest, String.class); String teamResponseBody = teamResponse.getBody().toString(); Team2 team2 = extractTeamInfo(teamResponseBody); userTeamsList.add(team2); } model.addAttribute("scenarioFileNameList", scenarioFileNameList); model.addAttribute("experimentForm", new ExperimentForm()); model.addAttribute("userTeamsList", userTeamsList); return "experiment_page_create_experiment"; } @RequestMapping(value = "/experiments/create", method = RequestMethod.POST) public String validateExperiment( @ModelAttribute("experimentForm") ExperimentForm experimentForm, HttpSession session, BindingResult bindingResult, final RedirectAttributes redirectAttributes) throws WebServiceRuntimeException { if (bindingResult.hasErrors()) { log.info("Create experiment - form has errors"); return "redirect:/experiments/create"; } if (experimentForm.getName() == null || experimentForm.getName().isEmpty()) { redirectAttributes.addFlashAttribute(MESSAGE, "Experiment Name cannot be empty"); return "redirect:/experiments/create"; } if (experimentForm.getDescription() == null || experimentForm.getDescription().isEmpty()) { redirectAttributes.addFlashAttribute(MESSAGE, "Description cannot be empty"); return "redirect:/experiments/create"; } experimentForm.setScenarioContents(getScenarioContentsFromFile(experimentForm.getScenarioFileName())); JSONObject experimentObject = new JSONObject(); experimentObject.put("userId", session.getAttribute("id").toString()); experimentObject.put("teamId", experimentForm.getTeamId()); experimentObject.put(TEAM_NAME, experimentForm.getTeamName()); experimentObject.put("name", experimentForm.getName().replaceAll("\\s+", "")); // truncate whitespaces and non-visible characters like \n experimentObject.put("description", experimentForm.getDescription()); experimentObject.put("nsFile", "file"); experimentObject.put("nsFileContent", experimentForm.getNsFileContent()); experimentObject.put("idleSwap", "240"); experimentObject.put("maxDuration", "960"); log.info("Calling service to create experiment"); HttpEntity<String> request = createHttpEntityWithBody(experimentObject.toString()); restTemplate.setErrorHandler(new MyResponseErrorHandler()); ResponseEntity response = restTemplate.exchange(properties.getSioExpUrl(), HttpMethod.POST, request, String.class); String responseBody = response.getBody().toString(); try { if (RestUtil.isError(response.getStatusCode())) { MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class); ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError()); switch (exceptionState) { case NS_FILE_PARSE_EXCEPTION: log.warn("Ns file error"); redirectAttributes.addFlashAttribute(MESSAGE, "There is an error when parsing the NS File."); break; case EXPERIMENT_NAME_ALREADY_EXISTS_EXCEPTION: log.warn("Exp name already exists"); redirectAttributes.addFlashAttribute(MESSAGE, "Experiment name already exists."); break; default: log.warn("Exp service or adapter fail"); // possible sio or adapter connection fail redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD); break; } log.info("Experiment {} created", experimentForm); return "redirect:/experiments/create"; } } catch (IOException e) { throw new WebServiceRuntimeException(e.getMessage()); } // // TODO Uploaded function for network configuration and optional dataset // if (!networkFile.isEmpty()) { // try { // String networkFileName = getSessionIdOfLoggedInUser(session) + "-networkconfig-" + networkFile.getOriginalFilename(); // BufferedOutputStream stream = new BufferedOutputStream( // new FileOutputStream(new File(App.EXP_CONFIG_DIR + "/" + networkFileName))); // FileCopyUtils.copy(networkFile.getInputStream(), stream); // stream.close(); // redirectAttributes.addFlashAttribute(MESSAGE, // "You successfully uploaded " + networkFile.getOriginalFilename() + "!"); // // remember network file name here // } // catch (Exception e) { // redirectAttributes.addFlashAttribute(MESSAGE, // "You failed to upload " + networkFile.getOriginalFilename() + " => " + e.getMessage()); // return "redirect:/experiments/create"; // } // } // // if (!dataFile.isEmpty()) { // try { // String dataFileName = getSessionIdOfLoggedInUser(session) + "-data-" + dataFile.getOriginalFilename(); // BufferedOutputStream stream = new BufferedOutputStream( // new FileOutputStream(new File(App.EXP_CONFIG_DIR + "/" + dataFileName))); // FileCopyUtils.copy(dataFile.getInputStream(), stream); // stream.close(); // redirectAttributes.addFlashAttribute("message2", // "You successfully uploaded " + dataFile.getOriginalFilename() + "!"); // // remember data file name here // } // catch (Exception e) { // redirectAttributes.addFlashAttribute("message2", // "You failed to upload " + dataFile.getOriginalFilename() + " => " + e.getMessage()); // } // } // // // add current experiment to experiment manager // experimentManager.addExperiment(getSessionIdOfLoggedInUser(session), experiment); // // increase exp count to be display on Teams page // teamManager.incrementExperimentCount(experiment.getTeamId()); return "redirect:/experiments"; } @RequestMapping(value = "/experiments/save_image/{teamId}/{expId}/{nodeId}", method = RequestMethod.GET) public String saveExperimentImage(@PathVariable String teamId, @PathVariable String expId, @PathVariable String nodeId, Model model) { Map<String, Map<String, String>> singleNodeInfoMap = new HashMap<>(); Image saveImageForm = new Image(); String teamName = invokeAndExtractTeamInfo(teamId).getName(); Realization realization = invokeAndExtractRealization(teamName, Long.parseLong(expId)); // experiment may have many nodes // extract just the particular node details to display for (Map.Entry<String, Map<String, String>> nodesInfo : realization.getNodesInfoMap().entrySet()) { String nodeName = nodesInfo.getKey(); Map<String, String> singleNodeDetailsMap = nodesInfo.getValue(); if (singleNodeDetailsMap.get(NODE_ID).equals(nodeId)) { singleNodeInfoMap.put(nodeName, singleNodeDetailsMap); // store the current os of the node into the form also // have to pass the the services saveImageForm.setCurrentOS(singleNodeDetailsMap.get("os")); } } saveImageForm.setTeamId(teamId); saveImageForm.setNodeId(nodeId); model.addAttribute("teamName", teamName); model.addAttribute("singleNodeInfoMap", singleNodeInfoMap); model.addAttribute("pathTeamId", teamId); model.addAttribute("pathExperimentId", expId); model.addAttribute("pathNodeId", nodeId); model.addAttribute("experimentName", realization.getExperimentName()); model.addAttribute("saveImageForm", saveImageForm); return "save_experiment_image"; } // bindingResult is required in the method signature to perform the JSR303 validation for Image object @RequestMapping(value = "/experiments/save_image/{teamId}/{expId}/{nodeId}", method = RequestMethod.POST) public String saveExperimentImage( @Valid @ModelAttribute("saveImageForm") Image saveImageForm, BindingResult bindingResult, RedirectAttributes redirectAttributes, @PathVariable String teamId, @PathVariable String expId, @PathVariable String nodeId) throws IOException { if (saveImageForm.getImageName().length() < 2) { log.warn("Save image form has errors {}", saveImageForm); redirectAttributes.addFlashAttribute("message", "Image name too short, minimum 2 characters"); return "redirect:/experiments/save_image/" + teamId + "/" + expId + "/" + nodeId; } log.info("Saving image: team {}, experiment {}, node {}", teamId, expId, nodeId); ObjectMapper mapper = new ObjectMapper(); HttpEntity<String> request = createHttpEntityWithBody(mapper.writeValueAsString(saveImageForm)); restTemplate.setErrorHandler(new MyResponseErrorHandler()); ResponseEntity response = restTemplate.exchange(properties.saveImage(), HttpMethod.POST, request, String.class); String responseBody = response.getBody().toString(); if (RestUtil.isError(response.getStatusCode())) { MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class); ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError()); log.warn("Save image: error with exception {}", exceptionState); switch (exceptionState) { case DETERLAB_OPERATION_FAILED_EXCEPTION: log.warn("Save image: error, operation failed on DeterLab"); redirectAttributes.addFlashAttribute("message", error.getMessage()); break; case ADAPTER_CONNECTION_EXCEPTION: log.warn("Save image: error, cannot connect to adapter"); redirectAttributes.addFlashAttribute("message", "connection to adapter failed"); break; case ADAPTER_INTERNAL_ERROR_EXCEPTION: log.warn("Save image: error, adapter internal server error"); redirectAttributes.addFlashAttribute("message", "internal error was found on the adapter"); break; default: log.warn("Save image: other error"); redirectAttributes.addFlashAttribute("message", ERR_SERVER_OVERLOAD); } return "redirect:/experiments/save_image/" + teamId + "/" + expId + "/" + nodeId; } // everything looks ok log.info("Save image in progress: team {}, experiment {}, node {}, image {}", teamId, expId, nodeId, saveImageForm.getImageName()); return "redirect:/experiments"; } /* private String processSaveImageRequest(@Valid @ModelAttribute("saveImageForm") Image saveImageForm, RedirectAttributes redirectAttributes, @PathVariable String teamId, @PathVariable String expId, @PathVariable String nodeId, ResponseEntity response, String responseBody) throws IOException { if (RestUtil.isError(response.getStatusCode())) { MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class); ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError()); log.warn("Save image exception: {}", exceptionState); switch (exceptionState) { case DETERLAB_OPERATION_FAILED_EXCEPTION: log.warn("adapter deterlab operation failed exception"); redirectAttributes.addFlashAttribute("message", error.getMessage()); break; default: log.warn("Image service or adapter fail"); // possible sio or adapter connection fail redirectAttributes.addFlashAttribute("message", ERR_SERVER_OVERLOAD); break; } return "redirect:/experiments/save_image/" + teamId + "/" + expId + "/" + nodeId; } else { // everything ok log.info("Image service in progress for Team: {}, Exp: {}, Node: {}, Image: {}", teamId, expId, nodeId, saveImageForm.getImageName()); return "redirect:/experiments"; } } */ // @RequestMapping("/experiments/configuration/{expId}") // public String viewExperimentConfiguration(@PathVariable Integer expId, Model model) { // // get experiment from expid // // retrieve the scenario contents to be displayed // Experiment currExp = experimentManager.getExperimentByExpId(expId); // model.addAttribute("scenarioContents", currExp.getScenarioContents()); // return "experiment_scenario_contents"; // } @RequestMapping("/remove_experiment/{teamName}/{teamId}/{expId}") public String removeExperiment(@PathVariable String teamName, @PathVariable String teamId, @PathVariable String expId, final RedirectAttributes redirectAttributes, HttpSession session) throws WebServiceRuntimeException { // TODO check userid is indeed the experiment owner or team owner // ensure experiment is stopped first Realization realization = invokeAndExtractRealization(teamName, Long.parseLong(expId)); // check valid authentication to remove experiments if (!validateIfAdmin(session) && !realization.getUserId().equals(session.getAttribute("id").toString())) { log.warn("Permission denied when remove Team:{}, Experiment: {} with User: {}, Role:{}", teamId, expId, session.getAttribute("id"), session.getAttribute(webProperties.getSessionRoles())); redirectAttributes.addFlashAttribute(MESSAGE, "An error occurred while trying to remove experiment;" + permissionDeniedMessage); return "redirect:/experiments"; } if (!realization.getState().equals(RealizationState.NOT_RUNNING.toString())) { log.warn("Trying to remove Team: {}, Experiment: {} with State: {} that is still in progress?", teamId, expId, realization.getState()); redirectAttributes.addFlashAttribute(MESSAGE, "An error occurred while trying to remove Exp: " + realization.getExperimentName() + ". Please refresh the page again. If the error persists, please contact " + CONTACT_EMAIL); return "redirect:/experiments"; } log.info("Removing experiment: at " + properties.getDeleteExperiment(teamId, expId)); HttpEntity<String> request = createHttpEntityHeaderOnly(); restTemplate.setErrorHandler(new MyResponseErrorHandler()); ResponseEntity response; try { response = restTemplate.exchange(properties.getDeleteExperiment(teamId, expId), HttpMethod.DELETE, request, String.class); } catch (Exception e) { log.warn("Error connecting to experiment service to remove experiment", e.getMessage()); redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD); return "redirect:/experiments"; } String responseBody = response.getBody().toString(); try { if (RestUtil.isError(response.getStatusCode())) { MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class); ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError()); switch (exceptionState) { case EXPERIMENT_DELETE_EXCEPTION: case FORBIDDEN_EXCEPTION: log.warn("remove experiment failed for Team: {}, Exp: {}", teamId, expId); redirectAttributes.addFlashAttribute(MESSAGE, error.getMessage()); break; case OBJECT_OPTIMISTIC_LOCKING_FAILURE_EXCEPTION: // do nothing log.info("remove experiment database locking failure"); break; default: // do nothing break; } return "redirect:/experiments"; } else { // everything ok log.info("remove experiment success for Team: {}, Exp: {}", teamId, expId); redirectAttributes.addFlashAttribute("exp_remove_message", "Team: " + teamName + " has removed Exp: " + realization.getExperimentName()); return "redirect:/experiments"; } } catch (IOException e) { throw new WebServiceRuntimeException(e.getMessage()); } } @RequestMapping("/start_experiment/{teamName}/{expId}") public String startExperiment( @PathVariable String teamName, @PathVariable String expId, final RedirectAttributes redirectAttributes, Model model, HttpSession session) throws WebServiceRuntimeException { // ensure experiment is stopped first before starting Realization realization = invokeAndExtractRealization(teamName, Long.parseLong(expId)); if (!checkPermissionRealizeExperiment(realization, session)) { log.warn("Permission denied to start experiment: {} for team: {}", realization.getExperimentName(), teamName); redirectAttributes.addFlashAttribute(MESSAGE, permissionDeniedMessage); return "redirect:/experiments"; } String teamStatus = getTeamStatus(realization.getTeamId()); if (!teamStatus.equals(TeamStatus.APPROVED.name())) { log.warn("Error: trying to realize an experiment {} on team {} with status {}", realization.getExperimentName(), realization.getTeamId(), teamStatus); redirectAttributes.addFlashAttribute(MESSAGE, teamName + " is in " + teamStatus + " status and does not have permission to start experiment. Please contact " + CONTACT_EMAIL); return "redirect:/experiments"; } if (!realization.getState().equals(RealizationState.NOT_RUNNING.toString())) { log.warn("Trying to start Team: {}, Experiment: {} with State: {} that is not running?", teamName, expId, realization.getState()); redirectAttributes.addFlashAttribute(MESSAGE, "An error occurred while trying to start Exp: " + realization.getExperimentName() + ". Please refresh the page again. If the error persists, please contact " + CONTACT_EMAIL); return "redirect:/experiments"; } log.info("Starting experiment: at " + properties.getStartExperiment(teamName, expId)); HttpEntity<String> request = createHttpEntityHeaderOnly(); restTemplate.setErrorHandler(new MyResponseErrorHandler()); ResponseEntity response; try { response = restTemplate.exchange(properties.getStartExperiment(teamName, expId), HttpMethod.POST, request, String.class); } catch (Exception e) { log.warn("Error connecting to experiment service to start experiment", e.getMessage()); redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD); return "redirect:/experiments"; } String responseBody = response.getBody().toString(); try { if (RestUtil.isError(response.getStatusCode())) { MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class); ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError()); switch (exceptionState) { case EXPERIMENT_START_EXCEPTION: case FORBIDDEN_EXCEPTION: log.warn("start experiment failed for Team: {}, Exp: {}", teamName, expId); redirectAttributes.addFlashAttribute(MESSAGE, error.getMessage()); return "redirect:/experiments"; case OBJECT_OPTIMISTIC_LOCKING_FAILURE_EXCEPTION: // do nothing log.info("start experiment database locking failure"); break; default: // do nothing break; } log.warn("start experiment some other error occurred exception: {}", exceptionState); // possible for it to be error but experiment has started up finish // if user clicks on start but reloads the page // model.addAttribute(EXPERIMENT_MESSAGE, "Team: " + teamName + " has started Exp: " + realization.getExperimentName()); return "experiments"; } else { // everything ok log.info("start experiment success for Team: {}, Exp: {}", teamName, expId); redirectAttributes.addFlashAttribute(EXPERIMENT_MESSAGE, "Experiment " + realization.getExperimentName() + " in team " + teamName + " is starting. This may take up to 10 minutes depending on the scale of your experiment. Please refresh this page later."); return "redirect:/experiments"; } } catch (IOException e) { log.warn("start experiment error: {]", e.getMessage()); throw new WebServiceRuntimeException(e.getMessage()); } } @RequestMapping("/stop_experiment/{teamName}/{expId}") public String stopExperiment(@PathVariable String teamName, @PathVariable String expId, Model model, final RedirectAttributes redirectAttributes, HttpSession session) throws WebServiceRuntimeException { // ensure experiment is active first before stopping Realization realization = invokeAndExtractRealization(teamName, Long.parseLong(expId)); if (isNotAdminAndNotInTeam(session, realization)) { log.warn("Permission denied to stop experiment: {} for team: {}", realization.getExperimentName(), teamName); redirectAttributes.addFlashAttribute(MESSAGE, permissionDeniedMessage); return "redirect:/experiments"; } if (!realization.getState().equals(RealizationState.RUNNING.toString())) { log.warn("Trying to stop Team: {}, Experiment: {} with State: {} that is still in progress?", teamName, expId, realization.getState()); redirectAttributes.addFlashAttribute(MESSAGE, "An error occurred while trying to stop Exp: " + realization.getExperimentName() + ". Please refresh the page again. If the error persists, please contact " + CONTACT_EMAIL); return "redirect:/experiments"; } log.info("Stopping experiment: at " + properties.getStopExperiment(teamName, expId)); HttpEntity<String> request = createHttpEntityHeaderOnly(); restTemplate.setErrorHandler(new MyResponseErrorHandler()); ResponseEntity response; return abc(teamName, expId, redirectAttributes, realization, request); } @RequestMapping("/get_topology/{teamName}/{expId}") @ResponseBody public String getTopology(@PathVariable String teamName, @PathVariable String expId) { try { HttpEntity<String> request = createHttpEntityHeaderOnly(); ResponseEntity response = restTemplate.exchange(properties.getTopology(teamName, expId), HttpMethod.GET, request, String.class); log.info("Retrieve experiment topo success"); return "data:image/png;base64," + response.getBody(); } catch (Exception e) { log.error("Error getting topology thumbnail", e.getMessage()); return ""; } } private String abc(@PathVariable String teamName, @PathVariable String expId, RedirectAttributes redirectAttributes, Realization realization, HttpEntity<String> request) throws WebServiceRuntimeException { ResponseEntity response; try { response = restTemplate.exchange(properties.getStopExperiment(teamName, expId), HttpMethod.POST, request, String.class); } catch (Exception e) { log.warn("Error connecting to experiment service to stop experiment", e.getMessage()); redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD); return "redirect:/experiments"; } String responseBody = response.getBody().toString(); try { if (RestUtil.isError(response.getStatusCode())) { MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class); ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError()); if (exceptionState == ExceptionState.FORBIDDEN_EXCEPTION) { log.warn("Permission denied to stop experiment: {} for team: {}", realization.getExperimentName(), teamName); redirectAttributes.addFlashAttribute(MESSAGE, permissionDeniedMessage); } if (exceptionState == ExceptionState.OBJECT_OPTIMISTIC_LOCKING_FAILURE_EXCEPTION) { log.info("stop experiment database locking failure"); } } else { // everything ok log.info("stop experiment success for Team: {}, Exp: {}", teamName, expId); redirectAttributes.addFlashAttribute(EXPERIMENT_MESSAGE, "Experiment " + realization.getExperimentName() + " in team " + teamName + " is stopping. Please refresh this page in a few minutes."); } return "redirect:/experiments"; } catch (IOException e) { throw new WebServiceRuntimeException(e.getMessage()); } } private boolean isNotAdminAndNotInTeam(HttpSession session, Realization realization) { return !validateIfAdmin(session) && !checkPermissionRealizeExperiment(realization, session); } //---------------------------------Dataset Page-------------------------- // @RequestMapping("/data/public/request_access/{dataOwnerId}") // public String requestAccessForDataset(@PathVariable Integer dataOwnerId, Model model) { // // TODO // // send reuqest to team owner // // show feedback to users // User rv = userManager.getUserById(dataOwnerId); // model.addAttribute("ownerName", rv.getError()); // model.addAttribute("ownerEmail", rv.getEmail()); // return "data_request_access"; // } //----------------------------------------------------------------------- //--------------------------Admin Revamp--------------------------------- //----------------------------------------------------------------------- //---------------------------------Admin--------------------------------- @RequestMapping("/admin") public String admin(Model model, HttpSession session) { if (!validateIfAdmin(session)) { return NO_PERMISSION_PAGE; } TeamManager2 teamManager2 = new TeamManager2(); Map<String, List<String>> userToTeamMap = new HashMap<>(); // userId : list of team names List<Team2> pendingApprovalTeamsList = new ArrayList<>(); //------------------------------------ // get list of teams // get list of teams pending for approval //------------------------------------ HttpEntity<String> request = createHttpEntityHeaderOnly(); ResponseEntity responseEntity = restTemplate.exchange(properties.getSioTeamsUrl(), HttpMethod.GET, request, String.class); JSONArray jsonArray = new JSONArray(responseEntity.getBody().toString()); for (int i = 0; i < jsonArray.length(); i++) { JSONObject jsonObject = jsonArray.getJSONObject(i); Team2 one = extractTeamInfo(jsonObject.toString()); teamManager2.addTeamToTeamMap(one); if (one.getStatus().equals(TeamStatus.PENDING.name())) { pendingApprovalTeamsList.add(one); } } //------------------------------------ // get list of users //------------------------------------ ResponseEntity response2 = restTemplate.exchange(properties.getSioUsersUrl(), HttpMethod.GET, request, String.class); String responseBody2 = response2.getBody().toString(); JSONArray jsonUserArray = new JSONArray(responseBody2); List<User2> usersList = new ArrayList<>(); for (int i = 0; i < jsonUserArray.length(); i++) { JSONObject userObject = jsonUserArray.getJSONObject(i); User2 user = extractUserInfo(userObject.toString()); usersList.add(user); // get list of teams' names for each user List<String> perUserTeamList = new ArrayList<>(); if (userObject.get("teams") != null) { JSONArray teamJsonArray = userObject.getJSONArray("teams"); for (int k = 0; k < teamJsonArray.length(); k++) { Team2 team = invokeAndExtractTeamInfo(teamJsonArray.get(k).toString()); perUserTeamList.add(team.getName()); } userToTeamMap.put(user.getId(), perUserTeamList); } } //------------------------------------ // get list of datasets //------------------------------------ ResponseEntity response3 = restTemplate.exchange(properties.getData(), HttpMethod.GET, request, String.class); String responseBody3 = response3.getBody().toString(); List<Dataset> datasetsList = new ArrayList<>(); JSONArray dataJsonArray = new JSONArray(responseBody3); for (int i = 0; i < dataJsonArray.length(); i++) { JSONObject dataInfoObject = dataJsonArray.getJSONObject(i); Dataset dataset = extractDataInfo(dataInfoObject.toString()); datasetsList.add(dataset); } model.addAttribute("teamsMap", teamManager2.getTeamMap()); model.addAttribute("pendingApprovalTeamsList", pendingApprovalTeamsList); model.addAttribute("usersList", usersList); model.addAttribute("userToTeamMap", userToTeamMap); model.addAttribute("dataList", datasetsList); return "admin2"; } @RequestMapping("/admin/experiments") public String adminExperimentsManagement(Model model, HttpSession session) { if (!validateIfAdmin(session)) { return NO_PERMISSION_PAGE; } //------------------------------------ // get list of experiments //------------------------------------ HttpEntity<String> expRequest = createHttpEntityHeaderOnly(); ResponseEntity expResponseEntity = restTemplate.exchange(properties.getAllExperiment(), HttpMethod.GET, expRequest, String.class); JSONArray jsonExpArray = new JSONArray(expResponseEntity.getBody().toString()); List<Experiment2> experimentList = new ArrayList<>(); Map<Long, Realization> realizationMap = new HashMap<>(); for (int i = 0; i < jsonExpArray.length(); i++) { Experiment2 experiment2 = extractExperiment(jsonExpArray.getJSONObject(i).toString()); Realization realization = invokeAndExtractRealization(experiment2.getTeamName(), experiment2.getId()); realizationMap.put(experiment2.getId(), realization); experimentList.add(experiment2); } model.addAttribute("adminExpList", experimentList); model.addAttribute("adminRealizationMap", realizationMap); return "experiment_dashboard"; } @RequestMapping(value = "/admin/{teamId}", method = RequestMethod.GET) public String admin(@PathVariable String teamId, Model model, HttpSession session) { HttpEntity<String> exprequest = createHttpEntityHeaderOnly(); ResponseEntity expresponse = restTemplate.exchange(properties.getExpListByTeamId(teamId), HttpMethod.GET, exprequest, String.class); JSONArray experimentsArray = new JSONArray(expresponse.getBody().toString()); List<Experiment2> experimentList = new ArrayList<>(); Map<Long, Realization> realizationMap = new HashMap<>(); for (int k = 0; k < experimentsArray.length(); k++) { Experiment2 experiment2 = extractExperiment(experimentsArray.getJSONObject(k).toString()); Realization realization = invokeAndExtractRealization(experiment2.getTeamName(), experiment2.getId()); realizationMap.put(experiment2.getId(), realization); experimentList.add(experiment2); } model.addAttribute("experimentList", experimentList); model.addAttribute("realizationMap", realizationMap); return "admin2"; } // @RequestMapping(value="/admin/domains/add", method=RequestMethod.POST) // public String addDomain(@Valid Domain domain, BindingResult bindingResult) { // if (bindingResult.hasErrors()) { // return "redirect:/admin"; // } else { // domainManager.addDomains(domain.getDomainName()); // } // return "redirect:/admin"; // } // @RequestMapping("/admin/domains/remove/{domainKey}") // public String removeDomain(@PathVariable String domainKey) { // domainManager.removeDomains(domainKey); // return "redirect:/admin"; // } @RequestMapping("/admin/teams/accept/{teamId}/{teamOwnerId}") public String approveTeam( @PathVariable String teamId, @PathVariable String teamOwnerId, final RedirectAttributes redirectAttributes, HttpSession session ) throws WebServiceRuntimeException { if (!validateIfAdmin(session)) { return NO_PERMISSION_PAGE; } //FIXME require approver info log.info("Approving new team {}, team owner {}", teamId, teamOwnerId); HttpEntity<String> request = createHttpEntityHeaderOnly(); restTemplate.setErrorHandler(new MyResponseErrorHandler()); ResponseEntity response = restTemplate.exchange( properties.getApproveTeam(teamId, teamOwnerId, TeamStatus.APPROVED), HttpMethod.POST, request, String.class); String responseBody = response.getBody().toString(); if (RestUtil.isError(response.getStatusCode())) { MyErrorResource error; try { error = objectMapper.readValue(responseBody, MyErrorResource.class); } catch (IOException e) { throw new WebServiceRuntimeException(e.getMessage()); } ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError()); switch (exceptionState) { case TEAM_ID_NULL_OR_EMPTY_EXCEPTION: log.warn("Approve team: TeamId cannot be null or empty: {}", teamId); redirectAttributes.addFlashAttribute(MESSAGE, "TeamId cannot be null or empty"); break; case USER_ID_NULL_OR_EMPTY_EXCEPTION: log.warn("Approve team: UserId cannot be null or empty: {}", teamOwnerId); redirectAttributes.addFlashAttribute(MESSAGE, "UserId cannot be null or empty"); break; case INVALID_TEAM_STATUS_EXCEPTION: log.warn("Approve team: TeamStatus is invalid"); redirectAttributes.addFlashAttribute(MESSAGE, "Team status is invalid"); break; case TEAM_NOT_FOUND_EXCEPTION: log.warn("Approve team: Team {} not found", teamId); redirectAttributes.addFlashAttribute(MESSAGE, "Team does not exist"); break; case DETERLAB_OPERATION_FAILED_EXCEPTION: log.warn("Approve team: Team {} fail", teamId); redirectAttributes.addFlashAttribute(MESSAGE, "Approve team request fail on Deterlab"); break; default: log.warn("Approve team : sio or deterlab adapter connection error"); // possible sio or adapter connection fail redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD); break; } return "redirect:/admin"; } // http status code is OK, then need to check the response message String msg = new JSONObject(responseBody).getString("msg"); if ("approve project OK".equals(msg)) { log.info("Approve team {} OK", teamId); } else { log.warn("Approve team {} FAIL", teamId); redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD); } return "redirect:/admin"; } @RequestMapping("/admin/teams/reject/{teamId}/{teamOwnerId}") public String rejectTeam( @PathVariable String teamId, @PathVariable String teamOwnerId, final RedirectAttributes redirectAttributes, HttpSession session ) throws WebServiceRuntimeException { if (!validateIfAdmin(session)) { return NO_PERMISSION_PAGE; } //FIXME require approver info log.info("Rejecting new team {}, team owner {}", teamId, teamOwnerId); HttpEntity<String> request = createHttpEntityHeaderOnly(); restTemplate.setErrorHandler(new MyResponseErrorHandler()); ResponseEntity response = restTemplate.exchange( properties.getApproveTeam(teamId, teamOwnerId, TeamStatus.REJECTED), HttpMethod.POST, request, String.class); String responseBody = response.getBody().toString(); if (RestUtil.isError(response.getStatusCode())) { MyErrorResource error; try { error = objectMapper.readValue(responseBody, MyErrorResource.class); } catch (IOException e) { throw new WebServiceRuntimeException(e.getMessage()); } ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError()); switch (exceptionState) { case TEAM_ID_NULL_OR_EMPTY_EXCEPTION: log.warn("Reject team: TeamId cannot be null or empty: {}", teamId); redirectAttributes.addFlashAttribute(MESSAGE, "TeamId cannot be null or empty"); break; case USER_ID_NULL_OR_EMPTY_EXCEPTION: log.warn("Reject team: UserId cannot be null or empty: {}", teamOwnerId); redirectAttributes.addFlashAttribute(MESSAGE, "UserId cannot be null or empty"); break; case INVALID_TEAM_STATUS_EXCEPTION: log.warn("Reject team: TeamStatus is invalid"); redirectAttributes.addFlashAttribute(MESSAGE, "Team status is invalid"); break; case TEAM_NOT_FOUND_EXCEPTION: log.warn("Reject team: Team {} not found", teamId); redirectAttributes.addFlashAttribute(MESSAGE, "Team does not exist"); break; case DETERLAB_OPERATION_FAILED_EXCEPTION: log.warn("Reject team: Team {} fail", teamId); redirectAttributes.addFlashAttribute(MESSAGE, "Reject team request fail on Deterlab"); break; default: log.warn("Reject team : sio or deterlab adapter connection error"); // possible sio or adapter connection fail redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD); break; } return "redirect:/admin"; } // http status code is OK, then need to check the response message String msg = new JSONObject(responseBody).getString("msg"); if ("reject project OK".equals(msg)) { log.info("Reject team {} OK", teamId); } else { log.warn("Reject team {} FAIL", teamId); redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD); } return "redirect:/admin"; } @RequestMapping("/admin/teams/{teamId}") public String setupTeamRestriction( @PathVariable final String teamId, @RequestParam(value = "action", required=true) final String action, final RedirectAttributes redirectAttributes, HttpSession session) throws IOException { final String logMessage = "Updating restriction settings for team {}: {}"; // check if admin if (!validateIfAdmin(session)) { log.warn(logMessage, teamId, PERMISSION_DENIED); return NO_PERMISSION_PAGE; } Team2 team = invokeAndExtractTeamInfo(teamId); // check if team is approved before restricted if ("restrict".equals(action) && team.getStatus().equals(TeamStatus.APPROVED.name())) { return restrictTeam(team, redirectAttributes); } // check if team is restricted before freeing it back to approved else if ("free".equals(action) && team.getStatus().equals(TeamStatus.RESTRICTED.name())) { return freeTeam(team, redirectAttributes); } else { log.warn(logMessage, teamId, "Cannot " + action + " team with status " + team.getStatus()); redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + "Cannot " + action + " team " + team.getName() + " with status " + team.getStatus()); return "redirect:/admin"; } } private String restrictTeam(final Team2 team, RedirectAttributes redirectAttributes) throws IOException { log.info("Restricting team {}", team.getId()); HttpEntity<String> request = createHttpEntityHeaderOnly(); ResponseEntity response = restTemplate.exchange( properties.getSioTeamsStatusUrl(team.getId(), TeamStatus.RESTRICTED), HttpMethod.PUT, request, String.class); String responseBody = response.getBody().toString(); if (RestUtil.isError(response.getStatusCode())) { MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class); ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError()); String logMessage = "Failed to restrict team {}: {}"; switch (exceptionState) { case TEAM_NOT_FOUND_EXCEPTION: log.warn(logMessage, team.getId(), TEAM_NOT_FOUND); redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + TEAM_NOT_FOUND); break; case INVALID_STATUS_TRANSITION_EXCEPTION: log.warn(logMessage, team.getId(), error.getMessage()); redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + error.getMessage()); break; case INVALID_TEAM_STATUS_EXCEPTION: log.warn(logMessage, team.getId(), error.getMessage()); redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + error.getMessage()); break; case FORBIDDEN_EXCEPTION: log.warn(logMessage, team.getId(), PERMISSION_DENIED); redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + PERMISSION_DENIED); break; default: log.warn(logMessage, team.getId(), exceptionState.getExceptionName()); redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD); } return "redirect:/admin"; } else { // good log.info("Team {} has been restricted", team.getId()); redirectAttributes.addFlashAttribute(MESSAGE_SUCCESS, "Team " + team.getName() + " status has been changed to " + TeamStatus.RESTRICTED.name()); return "redirect:/admin"; } } private String freeTeam(final Team2 team, RedirectAttributes redirectAttributes) throws IOException { log.info("Freeing team {}", team.getId()); HttpEntity<String> request = createHttpEntityHeaderOnly(); ResponseEntity response = restTemplate.exchange( properties.getSioTeamsStatusUrl(team.getId(), TeamStatus.APPROVED), HttpMethod.PUT, request, String.class); String responseBody = response.getBody().toString(); if (RestUtil.isError(response.getStatusCode())) { MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class); ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError()); String logMessage = "Failed to free team {}: {}"; switch (exceptionState) { case TEAM_NOT_FOUND_EXCEPTION: log.warn(logMessage, team.getId(), TEAM_NOT_FOUND); redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + TEAM_NOT_FOUND); break; case INVALID_STATUS_TRANSITION_EXCEPTION: log.warn(logMessage, team.getId(), error.getMessage()); redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + error.getMessage()); break; case INVALID_TEAM_STATUS_EXCEPTION: log.warn(logMessage, team.getId(), error.getMessage()); redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + error.getMessage()); break; case FORBIDDEN_EXCEPTION: log.warn(logMessage, team.getId(), PERMISSION_DENIED); redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + PERMISSION_DENIED); break; default: log.warn(logMessage, team.getId(), exceptionState.getExceptionName()); redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD); } return "redirect:/admin"; } else { // good log.info("Team {} has been freed", team.getId()); redirectAttributes.addFlashAttribute(MESSAGE_SUCCESS, "Team " + team.getName() + " status has been changed to " + TeamStatus.APPROVED.name()); return "redirect:/admin"; } } @RequestMapping("/admin/users/{userId}") public String freezeUnfreezeUsers( @PathVariable final String userId, @RequestParam(value = "action", required = true) final String action, final RedirectAttributes redirectAttributes, HttpSession session) throws IOException { User2 user = invokeAndExtractUserInfo(userId); // check if admin if (!validateIfAdmin(session)) { log.warn("Access denied when trying to freeze/unfreeze user {}: must be admin!", userId); return NO_PERMISSION_PAGE; } // check if user status is approved before freeze if ("freeze".equals(action) && user.getStatus().equals(UserStatus.APPROVED.toString())) { return freezeUser(user, redirectAttributes); } // check if user status is frozen before unfreeze else if ("unfreeze".equals(action) && user.getStatus().equals(UserStatus.FROZEN.toString())) { return unfreezeUser(user, redirectAttributes); } else { log.warn("Error in freeze/unfreeze user {}: failed to {} user with status {}", userId, action, user.getStatus()); redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + "failed to " + action + " user " + user.getEmail() + " with status " + user.getStatus()); return "redirect:/admin"; } } private String freezeUser(final User2 user, RedirectAttributes redirectAttributes) throws IOException { log.info("Freezing user {}, email {}", user.getId(), user.getEmail()); HttpEntity<String> request = createHttpEntityHeaderOnly(); ResponseEntity response = restTemplate.exchange( properties.getSioUsersStatusUrl(user.getId(), UserStatus.FROZEN.toString()), HttpMethod.PUT, request, String.class); String responseBody = response.getBody().toString(); if (RestUtil.isError(response.getStatusCode())) { MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class); ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError()); switch (exceptionState) { case USER_NOT_FOUND_EXCEPTION: log.warn("Failed to freeze user {}: user not found", user.getId()); redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + " user " + user.getEmail() + " not found."); break; case INVALID_STATUS_TRANSITION_EXCEPTION: log.warn("Failed to freeze user {}: invalid status transition {}", user.getId(), error.getMessage()); redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + error.getMessage() + " is not allowed."); break; case INVALID_USER_STATUS_EXCEPTION: log.warn("Failed to freeze user {}: invalid user status {}", user.getId(), error.getMessage()); redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + error.getMessage() + " is not a valid status."); break; case FORBIDDEN_EXCEPTION: log.warn("Failed to freeze user {}: must be an Admin", user.getId()); redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + " permission denied."); break; default: log.warn("Failed to freeze user {}: {}", user.getId(), exceptionState.getExceptionName()); redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD); break; } return "redirect:/admin"; } else { // good log.info("User {} has been frozen", user.getId()); redirectAttributes.addFlashAttribute(MESSAGE_SUCCESS, "User " + user.getEmail() + " has been banned."); return "redirect:/admin"; } } private String unfreezeUser(final User2 user, RedirectAttributes redirectAttributes) throws IOException { log.info("Unfreezing user {}, email {}", user.getId(), user.getEmail()); HttpEntity<String> request = createHttpEntityHeaderOnly(); ResponseEntity response = restTemplate.exchange( properties.getSioUsersStatusUrl(user.getId(), UserStatus.APPROVED.toString()), HttpMethod.PUT, request, String.class); String responseBody = response.getBody().toString(); if (RestUtil.isError(response.getStatusCode())) { MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class); ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError()); switch (exceptionState) { case USER_NOT_FOUND_EXCEPTION: log.warn("Failed to unfreeze user {}: user not found", user.getId()); redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + " user " + user.getEmail() + " not found."); break; case INVALID_STATUS_TRANSITION_EXCEPTION: log.warn("Failed to unfreeze user {}: invalid status transition {}", user.getId(), error.getMessage()); redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + error.getMessage() + " is not allowed."); break; case INVALID_USER_STATUS_EXCEPTION: log.warn("Failed to unfreeze user {}: invalid user status {}", user.getId(), error.getMessage()); redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + error.getMessage() + " is not a valid status."); break; case FORBIDDEN_EXCEPTION: log.warn("Failed to unfreeze user {}: must be an Admin", user.getId()); redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + " permission denied."); break; default: log.warn("Failed to unfreeze user {}: {}", user.getId(), exceptionState.getExceptionName()); redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD); break; } return "redirect:/admin"; } else { // good log.info("User {} has been unfrozen", user.getId()); redirectAttributes.addFlashAttribute(MESSAGE_SUCCESS, "User " + user.getEmail() + " has been unbanned."); return "redirect:/admin"; } } // @RequestMapping("/admin/experiments/remove/{expId}") // public String adminRemoveExp(@PathVariable Integer expId) { // int teamId = experimentManager.getExperimentByExpId(expId).getTeamId(); // experimentManager.adminRemoveExperiment(expId); // // // decrease exp count to be display on Teams page // teamManager.decrementExperimentCount(teamId); // return "redirect:/admin"; // } // @RequestMapping(value="/admin/data/contribute", method=RequestMethod.GET) // public String adminContributeDataset(Model model) { // model.addAttribute("dataset", new Dataset()); // // File rootFolder = new File(App.ROOT); // List<String> fileNames = Arrays.stream(rootFolder.listFiles()) // .map(f -> f.getError()) // .collect(Collectors.toList()); // // model.addAttribute("files", // Arrays.stream(rootFolder.listFiles()) // .sorted(Comparator.comparingLong(f -> -1 * f.lastModified())) // .map(f -> f.getError()) // .collect(Collectors.toList()) // ); // // return "admin_contribute_data"; // } // @RequestMapping(value="/admin/data/contribute", method=RequestMethod.POST) // public String validateAdminContributeDataset(@ModelAttribute("dataset") Dataset dataset, HttpSession session, @RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes) throws IOException { // BufferedOutputStream stream = null; // FileOutputStream fileOutputStream = null; // // TODO // // validation // // get file from user upload to server // if (!file.isEmpty()) { // try { // String fileName = getSessionIdOfLoggedInUser(session) + "-" + file.getOriginalFilename(); // fileOutputStream = new FileOutputStream(new File(App.ROOT + "/" + fileName)); // stream = new BufferedOutputStream(fileOutputStream); // FileCopyUtils.copy(file.getInputStream(), stream); // redirectAttributes.addFlashAttribute(MESSAGE, // "You successfully uploaded " + file.getOriginalFilename() + "!"); // datasetManager.addDataset(getSessionIdOfLoggedInUser(session), dataset, file.getOriginalFilename()); // } // catch (Exception e) { // redirectAttributes.addFlashAttribute(MESSAGE, // "You failed to upload " + file.getOriginalFilename() + " => " + e.getMessage()); // } finally { // if (stream != null) { // stream.close(); // } // if (fileOutputStream != null) { // fileOutputStream.close(); // } // } // } // else { // redirectAttributes.addFlashAttribute(MESSAGE, // "You failed to upload " + file.getOriginalFilename() + " because the file was empty"); // } // return "redirect:/admin"; // } // @RequestMapping("/admin/data/remove/{datasetId}") // public String adminRemoveDataset(@PathVariable Integer datasetId) { // datasetManager.removeDataset(datasetId); // return "redirect:/admin"; // } // @RequestMapping(value="/admin/node/add", method=RequestMethod.GET) // public String adminAddNode(Model model) { // model.addAttribute("node", new Node()); // return "admin_add_node"; // } // @RequestMapping(value="/admin/node/add", method=RequestMethod.POST) // public String adminAddNode(@ModelAttribute("node") Node node) { // // TODO // // validate fields, eg should be integer // nodeManager.addNode(node); // return "redirect:/admin"; // } //--------------------------Static pages for teams-------------------------- @RequestMapping("/teams/team_application_submitted") public String teamAppSubmitFromTeamsPage() { return "team_page_application_submitted"; } @RequestMapping("/teams/join_application_submitted/{teamName}") public String teamAppJoinFromTeamsPage(@PathVariable String teamName, Model model) throws WebServiceRuntimeException { log.info("Redirecting to join application submitted page"); HttpEntity<String> request = createHttpEntityHeaderOnly(); restTemplate.setErrorHandler(new MyResponseErrorHandler()); ResponseEntity response = restTemplate.exchange(properties.getTeamByName(teamName), HttpMethod.GET, request, String.class); String responseBody = response.getBody().toString(); try { if (RestUtil.isError(response.getStatusCode())) { MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class); ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError()); switch (exceptionState) { case TEAM_NOT_FOUND_EXCEPTION: log.warn("submitted join team request : team name error"); break; default: log.warn("submitted join team request : some other failure"); // possible sio or adapter connection fail break; } return "redirect:/teams/join_team"; } } catch (IOException e) { throw new WebServiceRuntimeException(e.getMessage()); } Team2 one = extractTeamInfo(responseBody); model.addAttribute("team", one); return "team_page_join_application_submitted"; } //--------------------------Static pages for sign up-------------------------- @RequestMapping("/team_application_submitted") public String teamAppSubmit() { return "team_application_submitted"; } /** * A page to show new users has successfully registered to apply to join an existing team * The page contains the team owner information which the users requested to join * * @param model The model which is passed from signup * @return A success page otherwise an error page if the user tries to access this page directly */ @RequestMapping("/join_application_submitted") public String joinTeamAppSubmit(Model model) { // model attribute should be passed from /signup2 // team is required to display the team owner details if (model.containsAttribute("team")) { return "join_team_application_submitted"; } return "error"; } @RequestMapping("/email_not_validated") public String emailNotValidated() { return "email_not_validated"; } @RequestMapping("/team_application_under_review") public String teamAppUnderReview() { return "team_application_under_review"; } // model attribute name come from /login @RequestMapping("/email_checklist") public String emailChecklist(@ModelAttribute("statuschecklist") String status) { return "email_checklist"; } @RequestMapping("/join_application_awaiting_approval") public String joinTeamAppAwaitingApproval(Model model) { model.addAttribute("loginForm", new LoginForm()); model.addAttribute("signUpMergedForm", new SignUpMergedForm()); return "join_team_application_awaiting_approval"; } //--------------------------Get List of scenarios filenames-------------------------- private List<String> getScenarioFileNameList() throws WebServiceRuntimeException { log.info("Retrieving scenario file names"); // List<String> scenarioFileNameList = null; // try { // scenarioFileNameList = IOUtils.readLines(getClass().getClassLoader().getResourceAsStream("scenarios"), StandardCharsets.UTF_8); // } catch (IOException e) { // throw new WebServiceRuntimeException(e.getMessage()); // } // File folder = null; // try { // folder = new ClassPathResource("scenarios").getFile(); // } catch (IOException e) { // throw new WebServiceRuntimeException(e.getMessage()); // } // List<String> scenarioFileNameList = new ArrayList<>(); // File[] files = folder.listFiles(); // for (File file : files) { // if (file.isFile()) { // scenarioFileNameList.add(file.getError()); // } // } // FIXME: hardcode list of filenames for now List<String> scenarioFileNameList = new ArrayList<>(); scenarioFileNameList.add("Scenario 1 - Experiment with a single node"); scenarioFileNameList.add("Scenario 2 - Experiment with 2 nodes and 10Gb link"); scenarioFileNameList.add("Scenario 3 - Experiment with 3 nodes in a LAN"); scenarioFileNameList.add("Scenario 4 - Experiment with 2 nodes and customized link property"); // scenarioFileNameList.add("Scenario 4 - Two nodes linked with a 10Gbps SDN switch"); // scenarioFileNameList.add("Scenario 5 - Three nodes with Blockchain capabilities"); log.info("Scenario file list: {}", scenarioFileNameList); return scenarioFileNameList; } private String getScenarioContentsFromFile(String scenarioFileName) throws WebServiceRuntimeException { // FIXME: switch to better way of referencing scenario descriptions to actual filenames String actualScenarioFileName; if (scenarioFileName.contains("Scenario 1")) { actualScenarioFileName = "basic1.ns"; } else if (scenarioFileName.contains("Scenario 2")) { actualScenarioFileName = "basic2.ns"; } else if (scenarioFileName.contains("Scenario 3")) { actualScenarioFileName = "basic3.ns"; } else if (scenarioFileName.contains("Scenario 4")) { actualScenarioFileName = "basic4.ns"; } else { // defaults to basic single node actualScenarioFileName = "basic1.ns"; } try { log.info("Retrieving scenario files {}", getClass().getClassLoader().getResourceAsStream("scenarios/" + actualScenarioFileName)); List<String> lines = IOUtils.readLines(getClass().getClassLoader().getResourceAsStream("scenarios/" + actualScenarioFileName), StandardCharsets.UTF_8); StringBuilder sb = new StringBuilder(); for (String line : lines) { sb.append(line); sb.append(System.getProperty("line.separator")); } log.info("Experiment ns file contents: {}", sb); return sb.toString(); } catch (IOException e) { throw new WebServiceRuntimeException(e.getMessage()); } } //---Check if user is a team owner and has any join request waiting for approval---- private boolean hasAnyJoinRequest(HashMap<Integer, Team> teamMapOwnedByUser) { for (Map.Entry<Integer, Team> entry : teamMapOwnedByUser.entrySet()) { Team currTeam = entry.getValue(); if (currTeam.isUserJoinRequestEmpty() == false) { // at least one team has join user request return true; } } // loop through all teams but never return a single true // therefore, user's controlled teams has no join request return false; } //--------------------------MISC-------------------------- private int getSessionIdOfLoggedInUser(HttpSession session) { return Integer.parseInt(session.getAttribute(SESSION_LOGGED_IN_USER_ID).toString()); } private User2 extractUserInfo(String userJson) { User2 user2 = new User2(); if (userJson == null) { // return empty user return user2; } JSONObject object = new JSONObject(userJson); JSONObject userDetails = object.getJSONObject("userDetails"); JSONObject address = userDetails.getJSONObject("address"); user2.setId(object.getString("id")); user2.setFirstName(getJSONStr(userDetails.getString("firstName"))); user2.setLastName(getJSONStr(userDetails.getString("lastName"))); user2.setJobTitle(userDetails.getString("jobTitle")); user2.setEmail(userDetails.getString("email")); user2.setPhone(userDetails.getString("phone")); user2.setAddress1(address.getString("address1")); user2.setAddress2(address.getString("address2")); user2.setCountry(address.getString("country")); user2.setRegion(address.getString("region")); user2.setPostalCode(address.getString("zipCode")); user2.setCity(address.getString("city")); user2.setInstitution(userDetails.getString("institution")); user2.setInstitutionAbbreviation(userDetails.getString("institutionAbbreviation")); user2.setInstitutionWeb(userDetails.getString("institutionWeb")); user2.setStatus(object.getString("status")); user2.setEmailVerified(object.getBoolean("emailVerified")); return user2; } private Team2 extractTeamInfo(String json) { Team2 team2 = new Team2(); JSONObject object = new JSONObject(json); JSONArray membersArray = object.getJSONArray("members"); try { team2.setCreatedDate(formatZonedDateTime(object.get("applicationDate").toString())); } catch (Exception e) { log.warn("Error getting team application date {}", e); team2.setCreatedDate(UNKNOWN); } team2.setId(object.getString("id")); team2.setName(object.getString("name")); team2.setDescription(object.getString("description")); team2.setWebsite(object.getString("website")); team2.setOrganisationType(object.getString("organisationType")); team2.setStatus(object.getString("status")); team2.setVisibility(object.getString("visibility")); for (int i = 0; i < membersArray.length(); i++) { JSONObject memberObject = membersArray.getJSONObject(i); String userId = memberObject.getString("userId"); String teamMemberType = memberObject.getString("memberType"); String teamMemberStatus = memberObject.getString("memberStatus"); User2 myUser = invokeAndExtractUserInfo(userId); if (teamMemberType.equals(MemberType.MEMBER.toString())) { team2.addMembers(myUser); // add to pending members list for Members Awaiting Approval function if (teamMemberStatus.equals(MemberStatus.PENDING.toString())) { team2.addPendingMembers(myUser); } } else if (teamMemberType.equals(MemberType.OWNER.toString())) { // explicit safer check team2.setOwner(myUser); } } team2.setMembersCount(membersArray.length()); return team2; } // use to extract JSON Strings from services // in the case where the JSON Strings are null, return "Connection Error" private String getJSONStr(String jsonString) { if (jsonString == null || jsonString.isEmpty()) { return CONNECTION_ERROR; } return jsonString; } /** * Checks if user is pending for join request approval from team leader * Use for fixing bug for view experiment page where users previously can view the experiments just by issuing a join request * * @param json the response body after calling team service * @param loginUserId the current logged in user id * @return True if the user is anything but APPROVED, false otherwise */ private boolean isMemberJoinRequestPending(String loginUserId, String json) { if (json == null) { return true; } JSONObject object = new JSONObject(json); JSONArray membersArray = object.getJSONArray("members"); for (int i = 0; i < membersArray.length(); i++) { JSONObject memberObject = membersArray.getJSONObject(i); String userId = memberObject.getString("userId"); String teamMemberStatus = memberObject.getString("memberStatus"); if (userId.equals(loginUserId) && !teamMemberStatus.equals(MemberStatus.APPROVED.toString())) { return true; } } log.info("User: {} is viewing experiment page", loginUserId); return false; } private Team2 extractTeamInfoUserJoinRequest(String userId, String json) { Team2 team2 = new Team2(); JSONObject object = new JSONObject(json); JSONArray membersArray = object.getJSONArray("members"); for (int i = 0; i < membersArray.length(); i++) { JSONObject memberObject = membersArray.getJSONObject(i); String uid = memberObject.getString("userId"); String teamMemberStatus = memberObject.getString("memberStatus"); if (uid.equals(userId) && teamMemberStatus.equals(MemberStatus.PENDING.toString())) { team2.setId(object.getString("id")); team2.setName(object.getString("name")); team2.setDescription(object.getString("description")); team2.setWebsite(object.getString("website")); team2.setOrganisationType(object.getString("organisationType")); team2.setStatus(object.getString("status")); team2.setVisibility(object.getString("visibility")); team2.setMembersCount(membersArray.length()); return team2; } } // no such member in the team found return null; } protected Dataset extractDataInfo(String json) { log.debug(json); JSONObject object = new JSONObject(json); Dataset dataset = new Dataset(); dataset.setId(object.getInt("id")); dataset.setName(object.getString("name")); dataset.setDescription(object.getString("description")); dataset.setContributorId(object.getString("contributorId")); dataset.addVisibility(object.getString("visibility")); dataset.addAccessibility(object.getString("accessibility")); try { dataset.setReleasedDate(getZonedDateTime(object.get("releasedDate").toString())); } catch (IOException e) { log.warn("Error getting released date {}", e); dataset.setReleasedDate(null); } dataset.setContributor(invokeAndExtractUserInfo(dataset.getContributorId())); JSONArray resources = object.getJSONArray("resources"); for (int i = 0; i < resources.length(); i++) { JSONObject resource = resources.getJSONObject(i); DataResource dataResource = new DataResource(); dataResource.setId(resource.getLong("id")); dataResource.setUri(resource.getString("uri")); dataset.addResource(dataResource); } JSONArray approvedUsers = object.getJSONArray("approvedUsers"); for (int i =0; i < approvedUsers.length(); i++) { dataset.addApprovedUser(approvedUsers.getString(0)); } return dataset; } protected User2 invokeAndExtractUserInfo(String userId) { HttpEntity<String> request = createHttpEntityHeaderOnlyNoAuthHeader(); ResponseEntity response; try { response = restTemplate.exchange(properties.getUser(userId), HttpMethod.GET, request, String.class); } catch (Exception e) { log.warn("User service not available to retrieve User: {}", userId); return new User2(); } return extractUserInfo(response.getBody().toString()); } private Team2 invokeAndExtractTeamInfo(String teamId) { HttpEntity<String> request = createHttpEntityHeaderOnly(); ResponseEntity responseEntity = restTemplate.exchange(properties.getTeamById(teamId), HttpMethod.GET, request, String.class); return extractTeamInfo(responseEntity.getBody().toString()); } private Experiment2 extractExperiment(String experimentJson) { Experiment2 experiment2 = new Experiment2(); JSONObject object = new JSONObject(experimentJson); experiment2.setId(object.getLong("id")); experiment2.setUserId(object.getString("userId")); experiment2.setTeamId(object.getString("teamId")); experiment2.setTeamName(object.getString(TEAM_NAME)); experiment2.setName(object.getString("name")); experiment2.setDescription(object.getString("description")); experiment2.setNsFile(object.getString("nsFile")); experiment2.setNsFileContent(object.getString("nsFileContent")); experiment2.setIdleSwap(object.getInt("idleSwap")); experiment2.setMaxDuration(object.getInt("maxDuration")); return experiment2; } private Realization invokeAndExtractRealization(String teamName, Long id) { HttpEntity<String> request = createHttpEntityHeaderOnly(); restTemplate.setErrorHandler(new MyResponseErrorHandler()); ResponseEntity response = null; try { log.info("retrieving the latest exp status: {}", properties.getRealizationByTeam(teamName, id.toString())); response = restTemplate.exchange(properties.getRealizationByTeam(teamName, id.toString()), HttpMethod.GET, request, String.class); } catch (Exception e) { return getCleanRealization(); } String responseBody; if (response.getBody() == null) { return getCleanRealization(); } else { responseBody = response.getBody().toString(); } try { if (RestUtil.isError(response.getStatusCode())) { MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class); log.warn("error in retrieving realization for team: {}, realization: {}", teamName, id); return getCleanRealization(); } else { return extractRealization(responseBody); } } catch (IOException e) { return getCleanRealization(); } } private Realization extractRealization(String json) { log.info("extracting realization: {}", json); Realization realization = new Realization(); JSONObject object = new JSONObject(json); realization.setExperimentId(object.getLong("experimentId")); realization.setExperimentName(object.getString("experimentName")); realization.setUserId(object.getString("userId")); realization.setTeamId(object.getString("teamId")); realization.setState(object.getString("state")); String exp_report = ""; Object expDetailsObject = object.get("details"); log.info("exp detail object: {}", expDetailsObject); if (expDetailsObject == JSONObject.NULL || expDetailsObject.toString().isEmpty()) { log.info("set details empty"); realization.setDetails(""); realization.setNumberOfNodes(0); } else { log.info("exp report to string: {}", expDetailsObject.toString()); exp_report = expDetailsObject.toString(); realization.setDetails(exp_report); JSONObject nodesInfoObject = new JSONObject(expDetailsObject.toString()); for (Object key : nodesInfoObject.keySet()) { Map<String, String> nodeDetails = new HashMap<>(); String nodeName = (String) key; JSONObject nodeDetailsJson = new JSONObject(nodesInfoObject.get(nodeName).toString()); nodeDetails.put("os", nodeDetailsJson.getString("os")); nodeDetails.put("qualifiedName", nodeDetailsJson.getString("qualifiedName")); nodeDetails.put(NODE_ID, nodeDetailsJson.getString(NODE_ID)); realization.addNodeDetails(nodeName, nodeDetails); } log.info("nodes info object: {}", nodesInfoObject); realization.setNumberOfNodes(nodesInfoObject.keySet().size()); } return realization; } /** * @param zonedDateTimeJSON JSON string * @return a date in the format MMM-d-yyyy */ protected String formatZonedDateTime(String zonedDateTimeJSON) throws Exception { ZonedDateTime zonedDateTime = getZonedDateTime(zonedDateTimeJSON); DateTimeFormatter format = DateTimeFormatter.ofPattern("MMM-d-yyyy"); return zonedDateTime.format(format); } protected ZonedDateTime getZonedDateTime(String zonedDateTimeJSON) throws IOException { ObjectMapper mapper = new ObjectMapper(); mapper.registerModule(new JavaTimeModule()); return mapper.readValue(zonedDateTimeJSON, ZonedDateTime.class); } /** * Creates a HttpEntity with a request body and header but no authorization header * To solve the expired jwt token * * @param jsonString The JSON request converted to string * @return A HttpEntity request * @see HttpEntity createHttpEntityHeaderOnly() for request with only header */ protected HttpEntity<String> createHttpEntityWithBodyNoAuthHeader(String jsonString) { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); return new HttpEntity<>(jsonString, headers); } /** * Creates a HttpEntity that contains only a header and empty body but no authorization header * To solve the expired jwt token * * @return A HttpEntity request * @see HttpEntity createHttpEntityWithBody() for request with both body and header */ protected HttpEntity<String> createHttpEntityHeaderOnlyNoAuthHeader() { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); return new HttpEntity<>(headers); } /** * Creates a HttpEntity with a request body and header * * @param jsonString The JSON request converted to string * @return A HttpEntity request * @implNote Authorization header must be set to the JwTToken in the format [Bearer: TOKEN_ID] * @see HttpEntity createHttpEntityHeaderOnly() for request with only header */ protected HttpEntity<String> createHttpEntityWithBody(String jsonString) { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); headers.set("Authorization", httpScopedSession.getAttribute(webProperties.getSessionJwtToken()).toString()); return new HttpEntity<>(jsonString, headers); } /** * Creates a HttpEntity that contains only a header and empty body * * @return A HttpEntity request * @implNote Authorization header must be set to the JwTToken in the format [Bearer: TOKEN_ID] * @see HttpEntity createHttpEntityWithBody() for request with both body and header */ protected HttpEntity<String> createHttpEntityHeaderOnly() { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); headers.set("Authorization", httpScopedSession.getAttribute(webProperties.getSessionJwtToken()).toString()); return new HttpEntity<>(headers); } private void setSessionVariables(HttpSession session, String loginEmail, String id, String firstName, String userRoles, String token) { User2 user = invokeAndExtractUserInfo(id); session.setAttribute(webProperties.getSessionEmail(), loginEmail); session.setAttribute(webProperties.getSessionUserId(), id); session.setAttribute(webProperties.getSessionUserFirstName(), firstName); session.setAttribute(webProperties.getSessionRoles(), userRoles); session.setAttribute(webProperties.getSessionJwtToken(), "Bearer " + token); log.info("Session variables - sessionLoggedEmail: {}, id: {}, name: {}, roles: {}, token: {}", loginEmail, id, user.getFirstName(), userRoles, token); } private void removeSessionVariables(HttpSession session) { log.info("removing session variables: email: {}, userid: {}, user first name: {}", session.getAttribute(webProperties.getSessionEmail()), session.getAttribute(webProperties.getSessionUserId()), session.getAttribute(webProperties.getSessionUserFirstName())); session.removeAttribute(webProperties.getSessionEmail()); session.removeAttribute(webProperties.getSessionUserId()); session.removeAttribute(webProperties.getSessionUserFirstName()); session.removeAttribute(webProperties.getSessionRoles()); session.removeAttribute(webProperties.getSessionJwtToken()); session.invalidate(); } protected boolean validateIfAdmin(HttpSession session) { //log.info("User: {} is logged on as: {}", session.getAttribute(webProperties.getSessionEmail()), session.getAttribute(webProperties.getSessionRoles())); return session.getAttribute(webProperties.getSessionRoles()).equals(UserType.ADMIN.toString()); } /** * Ensure that only users of the team can realize or un-realize experiment * A pre-condition is that the users must be approved. * Teams must also be approved. * * @return the main experiment page */ private boolean checkPermissionRealizeExperiment(Realization realization, HttpSession session) { // get list of teamids HttpEntity<String> request = createHttpEntityHeaderOnly(); ResponseEntity userRespEntity = restTemplate.exchange(properties.getUser(session.getAttribute("id").toString()), HttpMethod.GET, request, String.class); JSONObject object = new JSONObject(userRespEntity.getBody().toString()); JSONArray teamIdsJsonArray = object.getJSONArray("teams"); for (int i = 0; i < teamIdsJsonArray.length(); i++) { String teamId = teamIdsJsonArray.get(i).toString(); if (teamId.equals(realization.getTeamId())) { return true; } } return false; } private String getTeamStatus(String teamId) { Team2 team = invokeAndExtractTeamInfo(teamId); return team.getStatus(); } private Realization getCleanRealization() { Realization realization = new Realization(); realization.setExperimentId(0L); realization.setExperimentName(""); realization.setUserId(""); realization.setTeamId(""); realization.setState(RealizationState.ERROR.toString()); realization.setDetails(""); realization.setNumberOfNodes(0); return realization; } /** * Computes the number of teams that the user is in and the number of running experiments to populate data for the user dashboard * * @return a map in the form teams: numberOfTeams, experiments: numberOfExperiments */ private Map<String, Integer> getUserDashboardStats(String userId) { int numberOfRunningExperiments = 0; Map<String, Integer> userDashboardStats = new HashMap<>(); // get list of teamids HttpEntity<String> request = createHttpEntityHeaderOnly(); ResponseEntity userRespEntity = restTemplate.exchange(properties.getUser(userId), HttpMethod.GET, request, String.class); JSONObject object = new JSONObject(userRespEntity.getBody().toString()); JSONArray teamIdsJsonArray = object.getJSONArray("teams"); for (int i = 0; i < teamIdsJsonArray.length(); i++) { String teamId = teamIdsJsonArray.get(i).toString(); HttpEntity<String> teamRequest = createHttpEntityHeaderOnly(); ResponseEntity teamResponse = restTemplate.exchange(properties.getTeamById(teamId), HttpMethod.GET, teamRequest, String.class); String teamResponseBody = teamResponse.getBody().toString(); if (!isMemberJoinRequestPending(userId, teamResponseBody)) { // get experiments lists of the teams HttpEntity<String> expRequest = createHttpEntityHeaderOnly(); ResponseEntity expRespEntity = restTemplate.exchange(properties.getExpListByTeamId(teamId), HttpMethod.GET, expRequest, String.class); JSONArray experimentsArray = new JSONArray(expRespEntity.getBody().toString()); numberOfRunningExperiments = getNumberOfRunningExperiments(numberOfRunningExperiments, experimentsArray); } } userDashboardStats.put(USER_DASHBOARD_TEAMS, teamIdsJsonArray.length()); userDashboardStats.put(USER_DASHBOARD_RUNNING_EXPERIMENTS, numberOfRunningExperiments); userDashboardStats.put(USER_DASHBOARD_FREE_NODES, getNumberOfFreeNodes()); return userDashboardStats; } private int getNumberOfRunningExperiments(int numberOfRunningExperiments, JSONArray experimentsArray) { for (int k = 0; k < experimentsArray.length(); k++) { Experiment2 experiment2 = extractExperiment(experimentsArray.getJSONObject(k).toString()); Realization realization = invokeAndExtractRealization(experiment2.getTeamName(), experiment2.getId()); if (realization.getState().equals(RealizationState.RUNNING.toString())) { numberOfRunningExperiments++; } } return numberOfRunningExperiments; } private int getNumberOfFreeNodes() { String freeNodes; log.info("Retrieving number of free nodes from: {}", properties.getFreeNodes()); try { String jsonResult = restTemplate.getForObject(properties.getFreeNodes(), String.class); JSONObject object = new JSONObject(jsonResult); freeNodes = object.getString("numberOfFreeNodes"); } catch (RestClientException e) { log.warn("Error connecting to service-telemetry: {}", e); freeNodes = "0"; } return Integer.parseInt(freeNodes); } private List<TeamUsageInfo> getTeamsUsageStatisticsForUser(String userId) { List<TeamUsageInfo> usageInfoList = new ArrayList<>(); // get list of teamids HttpEntity<String> request = createHttpEntityHeaderOnly(); ResponseEntity userRespEntity = restTemplate.exchange(properties.getUser(userId), HttpMethod.GET, request, String.class); JSONObject object = new JSONObject(userRespEntity.getBody().toString()); JSONArray teamIdsJsonArray = object.getJSONArray("teams"); // get team info by team id for (int i = 0; i < teamIdsJsonArray.length(); i++) { String teamId = teamIdsJsonArray.get(i).toString(); HttpEntity<String> teamRequest = createHttpEntityHeaderOnly(); ResponseEntity teamResponse = restTemplate.exchange(properties.getTeamById(teamId), HttpMethod.GET, teamRequest, String.class); String teamResponseBody = teamResponse.getBody().toString(); if (!isMemberJoinRequestPending(userId, teamResponseBody)) { TeamUsageInfo usageInfo = new TeamUsageInfo(); usageInfo.setId(teamId); usageInfo.setName(new JSONObject(teamResponseBody).getString("name")); usageInfo.setUsage(getUsageStatisticsByTeamId(teamId)); usageInfoList.add(usageInfo); } } return usageInfoList; } private String getUsageStatisticsByTeamId(String id) { log.info("Getting usage statistics for team {}", id); HttpEntity<String> request = createHttpEntityHeaderOnly(); ResponseEntity response; try { response = restTemplate.exchange(properties.getUsageStatisticsByTeamId(id), HttpMethod.GET, request, String.class); } catch (RestClientException e) { log.warn("Error connecting to sio get usage statistics {}", e); return "?"; } return response.getBody().toString(); } }
src/main/java/sg/ncl/MainController.java
package sg.ncl; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import lombok.extern.slf4j.Slf4j; import org.apache.commons.io.IOUtils; import org.apache.tomcat.util.codec.binary.Base64; import org.json.JSONArray; import org.json.JSONObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.*; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.*; import org.springframework.web.client.ResourceAccessException; import org.springframework.web.client.RestClientException; import org.springframework.web.client.RestTemplate; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import org.springframework.web.servlet.support.RequestContextUtils; import sg.ncl.domain.*; import sg.ncl.exceptions.*; import sg.ncl.testbed_interface.*; import javax.inject.Inject; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import javax.validation.Valid; import javax.validation.constraints.NotNull; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.nio.charset.StandardCharsets; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.EnumMap; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Pattern; import static sg.ncl.domain.ExceptionState.*; /** * * Spring Controller * Direct the views to appropriate locations and invoke the respective REST API * * @author Cassie, Desmond, Te Ye, Vu */ @Controller @Slf4j public class MainController { public static final String CONTENT_DISPOSITION = "Content-Disposition"; public static final String APPLICATION_FORCE_DOWNLOAD = "application/force-download"; private static final String SESSION_LOGGED_IN_USER_ID = "loggedInUserId"; private TeamManager teamManager = TeamManager.getInstance(); // private UserManager userManager = UserManager.getInstance(); // private ExperimentManager experimentManager = ExperimentManager.getInstance(); // private DomainManager domainManager = DomainManager.getInstance(); // private DatasetManager datasetManager = DatasetManager.getInstance(); // private NodeManager nodeManager = NodeManager.getInstance(); private static final String CONTACT_EMAIL = "[email protected]"; private static final String UNKNOWN = "?"; private static final String MESSAGE = "message"; private static final String MESSAGE_SUCCESS = "messageSuccess"; private static final String EXPERIMENT_MESSAGE = "exp_message"; private static final String ERROR_PREFIX = "Error: "; // error messages private static final String ERR_SERVER_OVERLOAD = "There is a problem with your request. Please contact " + CONTACT_EMAIL; private static final String CONNECTION_ERROR = "Connection Error"; private final String permissionDeniedMessage = "Permission denied. If the error persists, please contact " + CONTACT_EMAIL; // for user dashboard hashmap key values private static final String USER_DASHBOARD_TEAMS = "teams"; private static final String USER_DASHBOARD_RUNNING_EXPERIMENTS = "runningExperiments"; private static final String USER_DASHBOARD_FREE_NODES = "freeNodes"; private static final String DETER_UID = "deterUid"; private static final Pattern VALID_EMAIL_ADDRESS_REGEX = Pattern.compile("(?:(?:\\r\\n)?[ \\t])*(?:(?:(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*))*@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*|(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)*\\<(?:(?:\\r\\n)?[ \\t])*(?:@(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*(?:,@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*)*:(?:(?:\\r\\n)?[ \\t])*)?(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*))*@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*\\>(?:(?:\\r\\n)?[ \\t])*)|(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)*:(?:(?:\\r\\n)?[ \\t])*(?:(?:(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*))*@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*|(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)*\\<(?:(?:\\r\\n)?[ \\t])*(?:@(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*(?:,@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*)*:(?:(?:\\r\\n)?[ \\t])*)?(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*))*@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*\\>(?:(?:\\r\\n)?[ \\t])*)(?:,\\s*(?:(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*))*@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*|(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)*\\<(?:(?:\\r\\n)?[ \\t])*(?:@(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*(?:,@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*)*:(?:(?:\\r\\n)?[ \\t])*)?(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*))*@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*\\>(?:(?:\\r\\n)?[ \\t])*))*)?;\\s*)"); private static final String FORGET_PSWD_PAGE = "password_reset_email"; private static final String FORGET_PSWD_NEW_PSWD_PAGE = "password_reset_new_password"; private static final String NO_PERMISSION_PAGE = "nopermission"; private static final String TEAM_NAME = "teamName"; private static final String NODE_ID = "nodeId"; private static final String PERMISSION_DENIED = "Permission denied"; private static final String TEAM_NOT_FOUND = "Team not found"; @Autowired protected RestTemplate restTemplate; @Inject protected ObjectMapper objectMapper; @Inject protected ConnectionProperties properties; @Inject protected WebProperties webProperties; @Inject protected HttpSession httpScopedSession; @RequestMapping("/") public String index() { return "index"; } @RequestMapping("/overview") public String overview() { return "overview"; } @RequestMapping("/community") public String community() { return "community"; } @RequestMapping("/about") public String about() { return "about"; } @RequestMapping("/event") public String event() { return "event"; } @RequestMapping("/plan") public String plan() { return "plan"; } // @RequestMapping("/futureplan") // public String futureplan() { // return "futureplan"; // } @RequestMapping("/pricing") public String pricing() { return "pricing"; } @RequestMapping("/resources1") public String resources1() { return "resources1"; } @RequestMapping("/resources") public String resources() { return "resources"; } @RequestMapping("/research") public String research() { return "research"; } @RequestMapping("/calendar") public String calendar() { return "calendar"; } @RequestMapping("/calendar1") public String calendar1() { return "calendar1"; } @RequestMapping("/tools") public String tools() { return "tools"; } @RequestMapping("/createaccount") public String createAccount() { return "createaccount"; } @RequestMapping("/createexperiment") public String createExperimentTutorial() { return "createexperiment"; } @RequestMapping("/applyteam") public String applyteam() { return "applyteam"; } @RequestMapping("/jointeam") public String jointeam() { return "jointeam"; } @RequestMapping("/error_openstack") public String error_openstack() { return "error_openstack"; } // @RequestMapping("/resource2") // public String resource2() { // return "resource2"; // } @RequestMapping("/accessexperiment") public String accessexperiment() { return "accessexperiment"; } @RequestMapping("/resource2") public String resource2() { return "resource2"; } // @RequestMapping("/admin2") // public String admin2() { // return "admin2"; // } @RequestMapping("/tutorials") public String tutorials() { return "tutorials"; } @RequestMapping("/maintainance") public String maintainance() { return "maintainance"; } @RequestMapping("/TestbedInformation") public String TestbedInformation() { return "TestbedInformation"; } // @RequestMapping(value="/futureplan/download", method=RequestMethod.GET) // public void futureplanDownload(HttpServletResponse response) throws FuturePlanDownloadException, IOException { // InputStream stream = null; // response.setContentType("application/pdf"); // try { // stream = getClass().getClassLoader().getResourceAsStream("downloads/future_plan.pdf"); // response.setContentType("application/force-download"); // response.setHeader("Content-Disposition", "attachment; filename=future_plan.pdf"); // IOUtils.copy(stream, response.getOutputStream()); // response.flushBuffer(); // } catch (Exception ex) { // logger.info("Error writing file to output stream."); // throw new FuturePlanDownloadException("IOError writing file to output stream"); // } finally { // if (stream != null) { // stream.close(); // } // } // } @RequestMapping(value = "/orderform/download", method = RequestMethod.GET) public void OrderForm_v1Download(HttpServletResponse response) throws OrderFormDownloadException, IOException { InputStream stream = null; response.setContentType(MediaType.APPLICATION_PDF_VALUE); try { stream = getClass().getClassLoader().getResourceAsStream("downloads/order_form.pdf"); response.setContentType(APPLICATION_FORCE_DOWNLOAD); response.setHeader(CONTENT_DISPOSITION, "attachment; filename=order_form.pdf"); IOUtils.copy(stream, response.getOutputStream()); response.flushBuffer(); } catch (IOException ex) { log.info("Error for download orderform."); throw new OrderFormDownloadException("Error for download orderform."); } finally { if (stream != null) { stream.close(); } } } @RequestMapping(value = "/SubscriptionAgreement/download", method = RequestMethod.GET) public void subscriptionAgreementDownload(HttpServletResponse response) throws MasterSubscriptionAgreementDownloadException, IOException { InputStream stream = null; response.setContentType(MediaType.APPLICATION_PDF_VALUE); try { stream = getClass().getClassLoader().getResourceAsStream("downloads/SubscriptionAgreement.pdf"); response.setContentType(APPLICATION_FORCE_DOWNLOAD); response.setHeader(CONTENT_DISPOSITION, "attachment; filename=SubscriptionAgreement.pdf"); IOUtils.copy(stream, response.getOutputStream()); response.flushBuffer(); } catch (IOException ex) { log.info("Error for subscription download." + ex.getMessage()); throw new MasterSubscriptionAgreementDownloadException("Error for subscription download."); } finally { if (stream != null) { stream.close(); } } } @RequestMapping(value = "/UsagePolicy/download", method = RequestMethod.GET) public void usagePolicyDownload(HttpServletResponse response) throws UsagePolicyDownloadException, IOException { InputStream stream = null; response.setContentType(MediaType.APPLICATION_PDF_VALUE); try { stream = getClass().getClassLoader().getResourceAsStream("downloads/UsagePolicy.pdf"); response.setContentType(APPLICATION_FORCE_DOWNLOAD); response.setHeader(CONTENT_DISPOSITION, "attachment; filename=UsagePolicy.pdf"); IOUtils.copy(stream, response.getOutputStream()); response.flushBuffer(); } catch (IOException ex) { log.info("Error for usage policy download." + ex.getMessage()); throw new UsagePolicyDownloadException("Error for usage policy download."); } finally { if (stream != null) { stream.close(); } } } @RequestMapping("/contactus") public String contactus() { return "contactus"; } @RequestMapping("/notfound") public String redirectNotFound(HttpSession session) { if (session.getAttribute("id") != null && !session.getAttribute("id").toString().isEmpty()) { // user is already logged on and has encountered an error // redirect to dashboard return "redirect:/dashboard"; } else { // user have not logged on before // redirect to home page return "redirect:/"; } } @RequestMapping(value = "/login", method = RequestMethod.GET) public String login(Model model) { model.addAttribute("loginForm", new LoginForm()); return "login"; } @RequestMapping(value = "/emailVerification", params = {"id", "email", "key"}) public String verifyEmail( @NotNull @RequestParam("id") final String id, @NotNull @RequestParam("email") final String emailBase64, @NotNull @RequestParam("key") final String key ) throws UnsupportedEncodingException { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); ObjectNode keyObject = objectMapper.createObjectNode(); keyObject.put("key", key); HttpEntity<String> request = new HttpEntity<>(keyObject.toString(), headers); restTemplate.setErrorHandler(new MyResponseErrorHandler()); final String link = properties.getSioUsersUrl() + id + "/emails/" + emailBase64; log.info("Activation link: {}, verification key {}", link, key); ResponseEntity response = restTemplate.exchange(link, HttpMethod.PUT, request, String.class); if (RestUtil.isError(response.getStatusCode())) { log.error("Activation of user {} failed.", id); return "email_validation_failed"; } else { log.info("Activation of user {} completed.", id); return "email_validation_ok"; } } @RequestMapping(value = "/login", method = RequestMethod.POST) public String loginSubmit( @Valid @ModelAttribute("loginForm") LoginForm loginForm, BindingResult bindingResult, Model model, HttpSession session, final RedirectAttributes redirectAttributes) throws WebServiceRuntimeException { if (bindingResult.hasErrors()) { loginForm.setErrorMsg("Login failed: Invalid email/password."); return "login"; } String inputEmail = loginForm.getLoginEmail(); String inputPwd = loginForm.getLoginPassword(); if (inputEmail.trim().isEmpty() || inputPwd.trim().isEmpty()) { loginForm.setErrorMsg("Email or Password cannot be empty!"); return "login"; } String plainCreds = inputEmail + ":" + inputPwd; byte[] plainCredsBytes = plainCreds.getBytes(); byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes); String base64Creds = new String(base64CredsBytes); ResponseEntity response; HttpHeaders headers = new HttpHeaders(); headers.set("Authorization", "Basic " + base64Creds); HttpEntity<String> request = new HttpEntity<>(headers); restTemplate.setErrorHandler(new MyResponseErrorHandler()); try { response = restTemplate.exchange(properties.getSioAuthUrl(), HttpMethod.POST, request, String.class); } catch (RestClientException e) { log.warn("Error connecting to sio authentication service: {}", e); loginForm.setErrorMsg(ERR_SERVER_OVERLOAD); return "login"; } String jwtTokenString = response.getBody().toString(); log.info("token string {}", jwtTokenString); if (jwtTokenString == null || jwtTokenString.isEmpty()) { log.warn("login failed for {}: unknown response code", loginForm.getLoginEmail()); loginForm.setErrorMsg("Login failed: Invalid email/password."); return "login"; } if (RestUtil.isError(response.getStatusCode())) { try { MyErrorResource error = objectMapper.readValue(jwtTokenString, MyErrorResource.class); ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError()); if (exceptionState == ExceptionState.CREDENTIALS_NOT_FOUND_EXCEPTION) { log.warn("login failed for {}: credentials not found", loginForm.getLoginEmail()); loginForm.setErrorMsg("Login failed: Account does not exist. Please register."); return "login"; } log.warn("login failed for {}: {}", loginForm.getLoginEmail(), error.getError()); loginForm.setErrorMsg("Login failed: Invalid email/password."); return "login"; } catch (IOException ioe) { log.warn("IOException {}", ioe); throw new WebServiceRuntimeException(ioe.getMessage()); } } JSONObject tokenObject = new JSONObject(jwtTokenString); String token = tokenObject.getString("token"); String id = tokenObject.getString("id"); String role = ""; if (tokenObject.getJSONArray("roles") != null) { role = tokenObject.getJSONArray("roles").get(0).toString(); } if (token.trim().isEmpty() || id.trim().isEmpty() || role.trim().isEmpty()) { log.warn("login failed for {}: empty id {} or token {} or role {}", loginForm.getLoginEmail(), id, token, role); loginForm.setErrorMsg("Login failed: Invalid email/password."); return "login"; } // now check user status to decide what to show to the user User2 user = invokeAndExtractUserInfo(id); try { String userStatus = user.getStatus(); boolean emailVerified = user.getEmailVerified(); if (UserStatus.FROZEN.toString().equals(userStatus)) { log.warn("User {} login failed: account has been frozen", id); loginForm.setErrorMsg("Login Failed: Account Frozen. Please contact " + CONTACT_EMAIL); return "login"; } else if (!emailVerified || (UserStatus.CREATED.toString()).equals(userStatus)) { redirectAttributes.addAttribute("statuschecklist", userStatus); log.info("User {} not validated, redirected to email verification page", id); return "redirect:/email_checklist"; } else if ((UserStatus.PENDING.toString()).equals(userStatus)) { redirectAttributes.addAttribute("statuschecklist", userStatus); log.info("User {} not approved, redirected to application pending page", id); return "redirect:/email_checklist"; } else if ((UserStatus.APPROVED.toString()).equals(userStatus)) { // set session variables setSessionVariables(session, loginForm.getLoginEmail(), id, user.getFirstName(), role, token); log.info("login success for {}, id: {}", loginForm.getLoginEmail(), id); return "redirect:/dashboard"; } else { log.warn("login failed for user {}: account is rejected or closed", id); loginForm.setErrorMsg("Login Failed: Account Rejected/Closed."); return "login"; } } catch (Exception e) { log.warn("Error parsing json object for user: {}", e.getMessage()); loginForm.setErrorMsg(ERR_SERVER_OVERLOAD); return "login"; } } // triggered when user clicks "Forget Password?" @RequestMapping("/password_reset_email") public String passwordResetEmail(Model model) { model.addAttribute("passwordResetRequestForm", new PasswordResetRequestForm()); return FORGET_PSWD_PAGE; } // triggered when user clicks "Send Reset Email" button @PostMapping("/password_reset_request") public String sendPasswordResetRequest( @ModelAttribute("passwordResetRequestForm") PasswordResetRequestForm passwordResetRequestForm ) throws WebServiceRuntimeException { String email = passwordResetRequestForm.getEmail(); if (!VALID_EMAIL_ADDRESS_REGEX.matcher(email).matches()) { passwordResetRequestForm.setErrMsg("Please provide a valid email address"); return FORGET_PSWD_PAGE; } JSONObject obj = new JSONObject(); obj.put("username", email); log.info("Connecting to sio for password reset email: {}", email); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); HttpEntity<String> request = new HttpEntity<>(obj.toString(), headers); restTemplate.setErrorHandler(new MyResponseErrorHandler()); ResponseEntity response = null; try { response = restTemplate.exchange(properties.getPasswordResetRequestURI(), HttpMethod.POST, request, String.class); } catch (RestClientException e) { log.warn("Cannot connect to sio for password reset email: {}", e); passwordResetRequestForm.setErrMsg("Cannot connect. Server may be down!"); return FORGET_PSWD_PAGE; } if (RestUtil.isError(response.getStatusCode())) { log.warn("Server responded error for password reset email: {}", response.getStatusCode()); passwordResetRequestForm.setErrMsg("Email not registered. Please use a different email address."); return FORGET_PSWD_PAGE; } log.info("Password reset email sent for {}", email); return "password_reset_email_sent"; } // triggered when user clicks password reset link in the email @RequestMapping(path = "/passwordReset", params = {"key"}) public String passwordResetNewPassword(@NotNull @RequestParam("key") final String key, Model model) { PasswordResetForm form = new PasswordResetForm(); form.setKey(key); model.addAttribute("passwordResetForm", form); // redirect to the page for user to enter new password return FORGET_PSWD_NEW_PSWD_PAGE; } // actual call to sio to reset password @RequestMapping(path = "/password_reset") public String resetPassword(@ModelAttribute("passwordResetForm") PasswordResetForm passwordResetForm) throws IOException { if (!passwordResetForm.isPasswordOk()) { return FORGET_PSWD_NEW_PSWD_PAGE; } JSONObject obj = new JSONObject(); obj.put("key", passwordResetForm.getKey()); obj.put("new", passwordResetForm.getPassword1()); log.info("Connecting to sio for password reset, key = {}", passwordResetForm.getKey()); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); HttpEntity<String> request = new HttpEntity<>(obj.toString(), headers); restTemplate.setErrorHandler(new MyResponseErrorHandler()); ResponseEntity response = null; try { response = restTemplate.exchange(properties.getPasswordResetURI(), HttpMethod.PUT, request, String.class); } catch (RestClientException e) { log.warn("Error connecting to sio for password reset! {}", e); passwordResetForm.setErrMsg("Cannot connect to server! Please try again later."); return FORGET_PSWD_NEW_PSWD_PAGE; } if (RestUtil.isError(response.getStatusCode())) { EnumMap<ExceptionState, String> exceptionMessageMap = new EnumMap<>(ExceptionState.class); exceptionMessageMap.put(PASSWORD_RESET_REQUEST_TIMEOUT_EXCEPTION, "Password reset request timed out. Please request a new reset email."); exceptionMessageMap.put(PASSWORD_RESET_REQUEST_NOT_FOUND_EXCEPTION, "Invalid password reset request. Please request a new reset email."); exceptionMessageMap.put(ADAPTER_CONNECTION_EXCEPTION, "Server-side error. Please contact " + CONTACT_EMAIL); MyErrorResource error = objectMapper.readValue(response.getBody().toString(), MyErrorResource.class); ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError()); final String errMsg = exceptionMessageMap.get(exceptionState) == null ? ERR_SERVER_OVERLOAD : exceptionMessageMap.get(exceptionState); passwordResetForm.setErrMsg(errMsg); log.warn("Server responded error for password reset: {}", exceptionState.toString()); return FORGET_PSWD_NEW_PSWD_PAGE; } log.info("Password was reset, key = {}", passwordResetForm.getKey()); return "password_reset_success"; } @RequestMapping("/dashboard") public String dashboard(Model model, HttpSession session) throws WebServiceRuntimeException { HttpEntity<String> request = createHttpEntityHeaderOnly(); restTemplate.setErrorHandler(new MyResponseErrorHandler()); ResponseEntity response = restTemplate.exchange(properties.getDeterUid(session.getAttribute(webProperties.getSessionUserId()).toString()), HttpMethod.GET, request, String.class); String responseBody = response.getBody().toString(); try { if (RestUtil.isError(response.getStatusCode())) { log.error("No user exists : {}", session.getAttribute(webProperties.getSessionUserId())); MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class); model.addAttribute(DETER_UID, CONNECTION_ERROR); } else { log.info("Show the deter user id: {}", responseBody); model.addAttribute(DETER_UID, responseBody); } } catch (IOException e) { throw new WebServiceRuntimeException(e.getMessage()); } // retrieve user dashboard stats Map<String, Integer> userDashboardMap = getUserDashboardStats(session.getAttribute(webProperties.getSessionUserId()).toString()); List<TeamUsageInfo> usageInfoList = getTeamsUsageStatisticsForUser(session.getAttribute(webProperties.getSessionUserId()).toString()); model.addAttribute("userDashboardMap", userDashboardMap); model.addAttribute("usageInfoList", usageInfoList); return "dashboard"; } @RequestMapping(value = "/logout", method = RequestMethod.GET) public String logout(HttpSession session) { removeSessionVariables(session); return "redirect:/"; } //--------------------------Sign Up Page-------------------------- @RequestMapping(value = "/signup2", method = RequestMethod.GET) public String signup2(Model model, HttpServletRequest request) { Map<String, ?> inputFlashMap = RequestContextUtils.getInputFlashMap(request); if (inputFlashMap != null) { log.debug((String) inputFlashMap.get(MESSAGE)); model.addAttribute("signUpMergedForm", (SignUpMergedForm) inputFlashMap.get("signUpMergedForm")); } else { log.debug("InputFlashMap is null"); model.addAttribute("signUpMergedForm", new SignUpMergedForm()); } return "signup2"; } @RequestMapping(value = "/signup2", method = RequestMethod.POST) public String validateDetails( @Valid @ModelAttribute("signUpMergedForm") SignUpMergedForm signUpMergedForm, BindingResult bindingResult, final RedirectAttributes redirectAttributes) throws WebServiceRuntimeException { if (bindingResult.hasErrors() || signUpMergedForm.getIsValid() == false) { log.warn("Register form has errors {}", signUpMergedForm.toString()); return "signup2"; } if (!signUpMergedForm.getHasAcceptTeamOwnerPolicy()) { signUpMergedForm.setErrorTeamOwnerPolicy("Please accept the team owner policy"); log.warn("Policy not accepted"); return "signup2"; } // get form fields // craft the registration json JSONObject mainObject = new JSONObject(); JSONObject credentialsFields = new JSONObject(); credentialsFields.put("username", signUpMergedForm.getEmail().trim()); credentialsFields.put("password", signUpMergedForm.getPassword()); // create the user JSON JSONObject userFields = new JSONObject(); JSONObject userDetails = new JSONObject(); JSONObject addressDetails = new JSONObject(); userDetails.put("firstName", signUpMergedForm.getFirstName().trim()); userDetails.put("lastName", signUpMergedForm.getLastName().trim()); userDetails.put("jobTitle", signUpMergedForm.getJobTitle().trim()); userDetails.put("email", signUpMergedForm.getEmail().trim()); userDetails.put("phone", signUpMergedForm.getPhone().trim()); userDetails.put("institution", signUpMergedForm.getInstitution().trim()); userDetails.put("institutionAbbreviation", signUpMergedForm.getInstitutionAbbreviation().trim()); userDetails.put("institutionWeb", signUpMergedForm.getWebsite().trim()); userDetails.put("address", addressDetails); addressDetails.put("address1", signUpMergedForm.getAddress1().trim()); addressDetails.put("address2", signUpMergedForm.getAddress2().trim()); addressDetails.put("country", signUpMergedForm.getCountry().trim()); addressDetails.put("region", signUpMergedForm.getProvince().trim()); addressDetails.put("city", signUpMergedForm.getCity().trim()); addressDetails.put("zipCode", signUpMergedForm.getPostalCode().trim()); userFields.put("userDetails", userDetails); userFields.put("applicationDate", ZonedDateTime.now()); JSONObject teamFields = new JSONObject(); // add all to main json mainObject.put("credentials", credentialsFields); mainObject.put("user", userFields); mainObject.put("team", teamFields); // check if user chose create new team or join existing team by checking team name String createNewTeamName = signUpMergedForm.getTeamName().trim(); String joinNewTeamName = signUpMergedForm.getJoinTeamName().trim(); if (createNewTeamName != null && !createNewTeamName.isEmpty()) { log.info("Signup new team name {}", createNewTeamName); boolean errorsFound = false; if (createNewTeamName.length() < 2 || createNewTeamName.length() > 12) { errorsFound = true; signUpMergedForm.setErrorTeamName("Team name must be 2 to 12 alphabetic/numeric characters"); } if (signUpMergedForm.getTeamDescription() == null || signUpMergedForm.getTeamDescription().isEmpty()) { errorsFound = true; signUpMergedForm.setErrorTeamDescription("Team description cannot be empty"); } if (signUpMergedForm.getTeamWebsite() == null || signUpMergedForm.getTeamWebsite().isEmpty()) { errorsFound = true; signUpMergedForm.setErrorTeamWebsite("Team website cannot be empty"); } if (errorsFound) { log.warn("Signup new team error {}", signUpMergedForm.toString()); // clear join team name first before submitting the form signUpMergedForm.setJoinTeamName(null); return "signup2"; } else { teamFields.put("name", signUpMergedForm.getTeamName().trim()); teamFields.put("description", signUpMergedForm.getTeamDescription().trim()); teamFields.put("website", signUpMergedForm.getTeamWebsite().trim()); teamFields.put("organisationType", signUpMergedForm.getTeamOrganizationType()); teamFields.put("visibility", signUpMergedForm.getIsPublic()); mainObject.put("isJoinTeam", false); try { registerUserToDeter(mainObject); } catch ( TeamNotFoundException | TeamNameAlreadyExistsException | UsernameAlreadyExistsException | EmailAlreadyExistsException | InvalidTeamNameException | InvalidPasswordException | DeterLabOperationFailedException e) { redirectAttributes.addFlashAttribute(MESSAGE, e.getMessage()); redirectAttributes.addFlashAttribute("signUpMergedForm", signUpMergedForm); return "redirect:/signup2"; } catch (Exception e) { redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD); redirectAttributes.addFlashAttribute("signUpMergedForm", signUpMergedForm); return "redirect:/signup2"; } log.info("Signup new team success"); return "redirect:/team_application_submitted"; } } else if (joinNewTeamName != null && !joinNewTeamName.isEmpty()) { log.info("Signup join team name {}", joinNewTeamName); // get the team JSON from team name Team2 joinTeamInfo; try { joinTeamInfo = getTeamIdByName(signUpMergedForm.getJoinTeamName().trim()); } catch (TeamNotFoundException | AdapterConnectionException e) { redirectAttributes.addFlashAttribute(MESSAGE, e.getMessage()); redirectAttributes.addFlashAttribute("signUpMergedForm", signUpMergedForm); return "redirect:/signup2"; } teamFields.put("id", joinTeamInfo.getId()); // set the flag to indicate to controller that it is joining an existing team mainObject.put("isJoinTeam", true); try { registerUserToDeter(mainObject); } catch ( TeamNotFoundException | AdapterConnectionException | TeamNameAlreadyExistsException | UsernameAlreadyExistsException | EmailAlreadyExistsException | InvalidTeamNameException | InvalidPasswordException | DeterLabOperationFailedException e) { redirectAttributes.addFlashAttribute(MESSAGE, e.getMessage()); redirectAttributes.addFlashAttribute("signUpMergedForm", signUpMergedForm); return "redirect:/signup2"; } catch (Exception e) { redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD); redirectAttributes.addFlashAttribute("signUpMergedForm", signUpMergedForm); return "redirect:/signup2"; } log.info("Signup join team success"); log.info("jointeam info: {}", joinTeamInfo); redirectAttributes.addFlashAttribute("team", joinTeamInfo); return "redirect:/join_application_submitted"; } else { log.warn("Signup unreachable statement"); // logic error not suppose to reach here // possible if user fill up create new team but without the team name redirectAttributes.addFlashAttribute("signupError", "There is a problem when submitting your form. Please re-enter and submit the details again."); redirectAttributes.addFlashAttribute("signUpMergedForm", signUpMergedForm); return "redirect:/signup2"; } } /** * Use when registering new accounts * * @param mainObject A JSONObject that contains user's credentials, personal details and team application details */ private void registerUserToDeter(JSONObject mainObject) throws WebServiceRuntimeException, TeamNotFoundException, AdapterConnectionException, TeamNameAlreadyExistsException, UsernameAlreadyExistsException, EmailAlreadyExistsException, InvalidTeamNameException, InvalidPasswordException, DeterLabOperationFailedException { HttpEntity<String> request = createHttpEntityWithBodyNoAuthHeader(mainObject.toString()); restTemplate.setErrorHandler(new MyResponseErrorHandler()); ResponseEntity response = restTemplate.exchange(properties.getSioRegUrl(), HttpMethod.POST, request, String.class); String responseBody = response.getBody().toString(); log.info("Register user to deter response: {}", responseBody); try { if (RestUtil.isError(response.getStatusCode())) { MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class); log.warn("Register user exception error: {}", error.getError()); ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError()); final String errorPrefix = "Error: "; switch (exceptionState) { case DETERLAB_OPERATION_FAILED_EXCEPTION: log.warn("Register new user failed on DeterLab: {}", error.getMessage()); throw new DeterLabOperationFailedException(errorPrefix + (error.getMessage().contains("unknown error") ? ERR_SERVER_OVERLOAD : error.getMessage())); case TEAM_NAME_ALREADY_EXISTS_EXCEPTION: log.warn("Register new users new team request : team name already exists"); throw new TeamNameAlreadyExistsException("Team name already exists"); case INVALID_TEAM_NAME_EXCEPTION: log.warn("Register new users new team request : team name invalid"); throw new InvalidTeamNameException("Invalid team name: must be 6-12 alphanumeric characters only"); case INVALID_PASSWORD_EXCEPTION: log.warn("Register new users new team request : invalid password"); throw new InvalidPasswordException("Password is too simple"); case USERNAME_ALREADY_EXISTS_EXCEPTION: // throw from user service { String email = mainObject.getJSONObject("user").getJSONObject("userDetails").getString("email"); log.warn("Register new users : email already exists: {}", email); throw new UsernameAlreadyExistsException(errorPrefix + email + " already in use."); } case EMAIL_ALREADY_EXISTS_EXCEPTION: // throw from adapter deterlab { String email = mainObject.getJSONObject("user").getJSONObject("userDetails").getString("email"); log.warn("Register new users : email already exists: {}", email); throw new EmailAlreadyExistsException(errorPrefix + email + " already in use."); } default: log.warn("Registration or adapter connection fail"); // possible sio or adapter connection fail throw new AdapterConnectionException(ERR_SERVER_OVERLOAD); } } else { // do nothing log.info("Not an error for status code: {}", response.getStatusCode()); } } catch (IOException e) { throw new WebServiceRuntimeException(e.getMessage()); } } /** * Use when users register a new account for joining existing team * * @param teamName The team name to join * @return the team id from sio */ private Team2 getTeamIdByName(String teamName) throws WebServiceRuntimeException, TeamNotFoundException, AdapterConnectionException { // FIXME check if team name exists // FIXME check for general exception? HttpEntity<String> request = createHttpEntityHeaderOnlyNoAuthHeader(); restTemplate.setErrorHandler(new MyResponseErrorHandler()); ResponseEntity response = restTemplate.exchange(properties.getTeamByName(teamName), HttpMethod.GET, request, String.class); String responseBody = response.getBody().toString(); try { if (RestUtil.isError(response.getStatusCode())) { MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class); ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError()); if (exceptionState == ExceptionState.TEAM_NOT_FOUND_EXCEPTION) { log.warn("Get team by name : team name error"); throw new TeamNotFoundException("Team name " + teamName + " does not exists"); } else { log.warn("Team service or adapter connection fail"); // possible sio or adapter connection fail throw new AdapterConnectionException(ERR_SERVER_OVERLOAD); } } else { return extractTeamInfo(responseBody); } } catch (IOException e) { throw new WebServiceRuntimeException(e.getMessage()); } } //--------------------------Account Settings Page-------------------------- @RequestMapping(value = "/account_settings", method = RequestMethod.GET) public String accountDetails(Model model, HttpSession session) throws WebServiceRuntimeException { String userId_uri = properties.getSioUsersUrl() + session.getAttribute("id"); HttpEntity<String> request = createHttpEntityHeaderOnly(); restTemplate.setErrorHandler(new MyResponseErrorHandler()); ResponseEntity response = restTemplate.exchange(userId_uri, HttpMethod.GET, request, String.class); String responseBody = response.getBody().toString(); try { if (RestUtil.isError(response.getStatusCode())) { log.error("No user to edit : {}", session.getAttribute("id")); MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class); throw new RestClientException("[" + error.getError() + "] "); } else { User2 user2 = extractUserInfo(responseBody); // need to do this so that we can compare after submitting the form session.setAttribute(webProperties.getSessionUserAccount(), user2); model.addAttribute("editUser", user2); return "account_settings"; } } catch (IOException e) { throw new WebServiceRuntimeException(e.getMessage()); } } @RequestMapping(value = "/account_settings", method = RequestMethod.POST) public String editAccountDetails( @ModelAttribute("editUser") User2 editUser, final RedirectAttributes redirectAttributes, HttpSession session) throws WebServiceRuntimeException { boolean errorsFound = false; String editPhrase = "editPhrase"; // check fields first if (errorsFound == false && editUser.getFirstName().isEmpty()) { redirectAttributes.addFlashAttribute("editFirstName", "fail"); errorsFound = true; } if (errorsFound == false && editUser.getLastName().isEmpty()) { redirectAttributes.addFlashAttribute("editLastName", "fail"); errorsFound = true; } if (errorsFound == false && editUser.getPhone().isEmpty()) { redirectAttributes.addFlashAttribute("editPhone", "fail"); errorsFound = true; } if (errorsFound == false && (editUser.getPhone().matches("(.*)[a-zA-Z](.*)") || editUser.getPhone().length() < 6)) { // previously already check if phone is empty // now check phone must contain only digits redirectAttributes.addFlashAttribute("editPhone", "fail"); errorsFound = true; } if (errorsFound == false && !editUser.getConfirmPassword().isEmpty() && !editUser.isPasswordValid()) { redirectAttributes.addFlashAttribute(editPhrase, "invalid"); errorsFound = true; } if (errorsFound == false && editUser.getJobTitle().isEmpty()) { redirectAttributes.addFlashAttribute("editJobTitle", "fail"); errorsFound = true; } if (errorsFound == false && editUser.getInstitution().isEmpty()) { redirectAttributes.addFlashAttribute("editInstitution", "fail"); errorsFound = true; } if (errorsFound == false && editUser.getCountry().isEmpty()) { redirectAttributes.addFlashAttribute("editCountry", "fail"); errorsFound = true; } if (errorsFound) { session.removeAttribute(webProperties.getSessionUserAccount()); return "redirect:/account_settings"; } else { // used to compare original and edited User2 objects User2 originalUser = (User2) session.getAttribute(webProperties.getSessionUserAccount()); JSONObject userObject = new JSONObject(); JSONObject userDetails = new JSONObject(); JSONObject address = new JSONObject(); userDetails.put("firstName", editUser.getFirstName()); userDetails.put("lastName", editUser.getLastName()); userDetails.put("email", editUser.getEmail()); userDetails.put("phone", editUser.getPhone()); userDetails.put("jobTitle", editUser.getJobTitle()); userDetails.put("address", address); userDetails.put("institution", editUser.getInstitution()); userDetails.put("institutionAbbreviation", originalUser.getInstitutionAbbreviation()); userDetails.put("institutionWeb", originalUser.getInstitutionWeb()); address.put("address1", originalUser.getAddress1()); address.put("address2", originalUser.getAddress2()); address.put("country", editUser.getCountry()); address.put("city", originalUser.getCity()); address.put("region", originalUser.getRegion()); address.put("zipCode", originalUser.getPostalCode()); userObject.put("userDetails", userDetails); String userId_uri = properties.getSioUsersUrl() + session.getAttribute(webProperties.getSessionUserId()); HttpEntity<String> request = createHttpEntityWithBody(userObject.toString()); restTemplate.exchange(userId_uri, HttpMethod.PUT, request, String.class); if (!originalUser.getFirstName().equals(editUser.getFirstName())) { redirectAttributes.addFlashAttribute("editFirstName", "success"); } if (!originalUser.getLastName().equals(editUser.getLastName())) { redirectAttributes.addFlashAttribute("editLastName", "success"); } if (!originalUser.getPhone().equals(editUser.getPhone())) { redirectAttributes.addFlashAttribute("editPhone", "success"); } if (!originalUser.getJobTitle().equals(editUser.getJobTitle())) { redirectAttributes.addFlashAttribute("editJobTitle", "success"); } if (!originalUser.getInstitution().equals(editUser.getInstitution())) { redirectAttributes.addFlashAttribute("editInstitution", "success"); } if (!originalUser.getCountry().equals(editUser.getCountry())) { redirectAttributes.addFlashAttribute("editCountry", "success"); } // credential service change password if (editUser.isPasswordMatch()) { JSONObject credObject = new JSONObject(); credObject.put("password", editUser.getPassword()); HttpEntity<String> credRequest = createHttpEntityWithBody(credObject.toString()); restTemplate.setErrorHandler(new MyResponseErrorHandler()); ResponseEntity response = restTemplate.exchange(properties.getUpdateCredentials(session.getAttribute("id").toString()), HttpMethod.PUT, credRequest, String.class); String responseBody = response.getBody().toString(); try { if (RestUtil.isError(response.getStatusCode())) { MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class); redirectAttributes.addFlashAttribute(editPhrase, "fail"); } else { redirectAttributes.addFlashAttribute(editPhrase, "success"); } } catch (IOException e) { throw new WebServiceRuntimeException(e.getMessage()); } finally { session.removeAttribute(webProperties.getSessionUserAccount()); } } } return "redirect:/account_settings"; } //--------------------User Side Approve Members Page------------ @RequestMapping("/approve_new_user") public String approveNewUser(Model model, HttpSession session) throws Exception { // HashMap<Integer, Team> rv = new HashMap<Integer, Team>(); // rv = teamManager.getTeamMapByTeamOwner(getSessionIdOfLoggedInUser(session)); // boolean userHasAnyJoinRequest = hasAnyJoinRequest(rv); // model.addAttribute("teamMapOwnedByUser", rv); // model.addAttribute("userHasAnyJoinRequest", userHasAnyJoinRequest); List<JoinRequestApproval> rv = new ArrayList<>(); List<JoinRequestApproval> temp; // get list of teamids HttpEntity<String> request = createHttpEntityHeaderOnly(); ResponseEntity response = restTemplate.exchange(properties.getUser(session.getAttribute("id").toString()), HttpMethod.GET, request, String.class); String responseBody = response.getBody().toString(); JSONObject object = new JSONObject(responseBody); JSONArray teamIdsJsonArray = object.getJSONArray("teams"); for (int i = 0; i < teamIdsJsonArray.length(); i++) { String teamId = teamIdsJsonArray.get(i).toString(); HttpEntity<String> teamRequest = createHttpEntityHeaderOnly(); ResponseEntity teamResponse = restTemplate.exchange(properties.getTeamById(teamId), HttpMethod.GET, teamRequest, String.class); String teamResponseBody = teamResponse.getBody().toString(); Team2 team2 = new Team2(); JSONObject teamObject = new JSONObject(teamResponseBody); JSONArray membersArray = teamObject.getJSONArray("members"); team2.setId(teamObject.getString("id")); team2.setName(teamObject.getString("name")); boolean isTeamLeader = false; temp = new ArrayList<>(); for (int j = 0; j < membersArray.length(); j++) { JSONObject memberObject = membersArray.getJSONObject(j); String userId = memberObject.getString("userId"); String teamMemberType = memberObject.getString("memberType"); String teamMemberStatus = memberObject.getString("memberStatus"); String teamJoinedDate = formatZonedDateTime(memberObject.get("joinedDate").toString()); JoinRequestApproval joinRequestApproval = new JoinRequestApproval(); if (userId.equals(session.getAttribute("id").toString()) && teamMemberType.equals(MemberType.OWNER.toString())) { isTeamLeader = true; } if (teamMemberStatus.equals(MemberStatus.PENDING.toString()) && teamMemberType.equals(MemberType.MEMBER.toString())) { User2 myUser = invokeAndExtractUserInfo(userId); joinRequestApproval.setUserId(myUser.getId()); joinRequestApproval.setUserEmail(myUser.getEmail()); joinRequestApproval.setUserName(myUser.getFirstName() + " " + myUser.getLastName()); joinRequestApproval.setApplicationDate(teamJoinedDate); joinRequestApproval.setTeamId(team2.getId()); joinRequestApproval.setTeamName(team2.getName()); temp.add(joinRequestApproval); log.info("Join request: UserId: {}, UserEmail: {}", myUser.getId(), myUser.getEmail()); } } if (isTeamLeader) { if (!temp.isEmpty()) { rv.addAll(temp); } } } model.addAttribute("joinApprovalList", rv); return "approve_new_user"; } @RequestMapping("/approve_new_user/accept/{teamId}/{userId}") public String userSideAcceptJoinRequest( @PathVariable String teamId, @PathVariable String userId, HttpSession session, RedirectAttributes redirectAttributes) throws WebServiceRuntimeException { log.info("Approve join request: User {}, Team {}, Approver {}", userId, teamId, session.getAttribute("id").toString()); JSONObject mainObject = new JSONObject(); JSONObject userFields = new JSONObject(); userFields.put("id", session.getAttribute("id").toString()); mainObject.put("user", userFields); HttpEntity<String> request = createHttpEntityWithBody(mainObject.toString()); ResponseEntity response; try { response = restTemplate.exchange(properties.getApproveJoinRequest(teamId, userId), HttpMethod.POST, request, String.class); } catch (RestClientException e) { log.warn("Error connecting to sio team service: {}", e); redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD); return "redirect:/approve_new_user"; } String responseBody = response.getBody().toString(); if (RestUtil.isError(response.getStatusCode())) { try { MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class); ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError()); switch (exceptionState) { case DETERLAB_OPERATION_FAILED_EXCEPTION: log.warn("Approve join request: User {}, Team {} fail", userId, teamId); redirectAttributes.addFlashAttribute(MESSAGE, "Approve join request fail"); break; default: log.warn("Server side error: {}", error.getError()); redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD); break; } return "redirect:/approve_new_user"; } catch (IOException ioe) { log.warn("IOException {}", ioe); throw new WebServiceRuntimeException(ioe.getMessage()); } } // everything looks OK? log.info("Join request has been APPROVED, User {}, Team {}", userId, teamId); redirectAttributes.addFlashAttribute(MESSAGE_SUCCESS, "Join request has been APPROVED."); return "redirect:/approve_new_user"; } @RequestMapping("/approve_new_user/reject/{teamId}/{userId}") public String userSideRejectJoinRequest( @PathVariable String teamId, @PathVariable String userId, HttpSession session, RedirectAttributes redirectAttributes) throws WebServiceRuntimeException { log.info("Reject join request: User {}, Team {}, Approver {}", userId, teamId, session.getAttribute("id").toString()); JSONObject mainObject = new JSONObject(); JSONObject userFields = new JSONObject(); userFields.put("id", session.getAttribute("id").toString()); mainObject.put("user", userFields); HttpEntity<String> request = createHttpEntityWithBody(mainObject.toString()); ResponseEntity response; try { response = restTemplate.exchange(properties.getRejectJoinRequest(teamId, userId), HttpMethod.DELETE, request, String.class); } catch (RestClientException e) { log.warn("Error connecting to sio team service: {}", e); redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD); return "redirect:/approve_new_user"; } String responseBody = response.getBody().toString(); if (RestUtil.isError(response.getStatusCode())) { try { MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class); ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError()); switch (exceptionState) { case DETERLAB_OPERATION_FAILED_EXCEPTION: log.warn("Reject join request: User {}, Team {} fail", userId, teamId); redirectAttributes.addFlashAttribute(MESSAGE, "Reject join request fail"); break; default: log.warn("Server side error: {}", error.getError()); redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD); break; } return "redirect:/approve_new_user"; } catch (IOException ioe) { log.warn("IOException {}", ioe); throw new WebServiceRuntimeException(ioe.getMessage()); } } // everything looks OK? log.info("Join request has been REJECTED, User {}, Team {}", userId, teamId); redirectAttributes.addFlashAttribute(MESSAGE, "Join request has been REJECTED."); return "redirect:/approve_new_user"; } //--------------------------Teams Page-------------------------- @RequestMapping("/public_teams") public String publicTeamsBeforeLogin(Model model) { TeamManager2 teamManager2 = new TeamManager2(); // get public teams HttpEntity<String> teamRequest = createHttpEntityHeaderOnlyNoAuthHeader(); ResponseEntity teamResponse = restTemplate.exchange(properties.getTeamsByVisibility(TeamVisibility.PUBLIC.toString()), HttpMethod.GET, teamRequest, String.class); String teamResponseBody = teamResponse.getBody().toString(); JSONArray teamPublicJsonArray = new JSONArray(teamResponseBody); for (int i = 0; i < teamPublicJsonArray.length(); i++) { JSONObject teamInfoObject = teamPublicJsonArray.getJSONObject(i); Team2 team2 = extractTeamInfo(teamInfoObject.toString()); teamManager2.addTeamToPublicTeamMap(team2); } model.addAttribute("publicTeamMap2", teamManager2.getPublicTeamMap()); return "public_teams"; } @RequestMapping("/teams") public String teams(Model model, HttpSession session) { // int currentLoggedInUserId = getSessionIdOfLoggedInUser(session); // model.addAttribute("infoMsg", teamManager.getInfoMsg()); // model.addAttribute("currentLoggedInUserId", currentLoggedInUserId); // model.addAttribute("teamMap", teamManager.getTeamMap(currentLoggedInUserId)); // model.addAttribute("publicTeamMap", teamManager.getPublicTeamMap()); // model.addAttribute("invitedToParticipateMap2", teamManager.getInvitedToParticipateMap2(currentLoggedInUserId)); // model.addAttribute("joinRequestMap2", teamManager.getJoinRequestTeamMap2(currentLoggedInUserId)); TeamManager2 teamManager2 = new TeamManager2(); // stores the list of images created or in progress of creation by teams // e.g. teamNameA : "created" : [imageA, imageB], "inProgress" : [imageC, imageD] Map<String, Map<String, List<Image>>> imageMap = new HashMap<>(); // get list of teamids HttpEntity<String> request = createHttpEntityHeaderOnly(); ResponseEntity response = restTemplate.exchange(properties.getUser(session.getAttribute("id").toString()), HttpMethod.GET, request, String.class); String responseBody = response.getBody().toString(); JSONObject object = new JSONObject(responseBody); JSONArray teamIdsJsonArray = object.getJSONArray("teams"); String userEmail = object.getJSONObject("userDetails").getString("email"); for (int i = 0; i < teamIdsJsonArray.length(); i++) { String teamId = teamIdsJsonArray.get(i).toString(); HttpEntity<String> teamRequest = createHttpEntityHeaderOnly(); ResponseEntity teamResponse = restTemplate.exchange(properties.getTeamById(teamId), HttpMethod.GET, teamRequest, String.class); String teamResponseBody = teamResponse.getBody().toString(); Team2 team2 = extractTeamInfo(teamResponseBody); teamManager2.addTeamToTeamMap(team2); Team2 joinRequestTeam = extractTeamInfoUserJoinRequest(session.getAttribute("id").toString(), teamResponseBody); if (joinRequestTeam != null) { teamManager2.addTeamToUserJoinRequestTeamMap(joinRequestTeam); } imageMap.put(team2.getName(), invokeAndGetImageList(teamId)); } // check if inner image map is empty, have to do it via this manner // returns true if the team contains an image list boolean isInnerImageMapPresent = imageMap.values().stream().filter(perTeamImageMap -> !perTeamImageMap.isEmpty()).findFirst().isPresent(); model.addAttribute("userEmail", userEmail); model.addAttribute("teamMap2", teamManager2.getTeamMap()); model.addAttribute("userJoinRequestMap", teamManager2.getUserJoinRequestMap()); model.addAttribute("isInnerImageMapPresent", isInnerImageMapPresent); model.addAttribute("imageMap", imageMap); return "teams"; } /** * Exectues the service-image and returns a Map containing the list of images in two partitions. * One partition contains the list of already created images. * The other partition contains the list of currently saving in progress images. * * @param teamId The ncl team id to retrieve the list of images from. * @return Returns a Map containing the list of images in two partitions. */ private Map<String, List<Image>> invokeAndGetImageList(String teamId) { log.info("Getting list of saved images for team {}", teamId); Map<String, List<Image>> resultMap = new HashMap<>(); List<Image> createdImageList = new ArrayList<>(); List<Image> inProgressImageList = new ArrayList<>(); HttpEntity<String> imageRequest = createHttpEntityHeaderOnly(); ResponseEntity imageResponse; try { imageResponse = restTemplate.exchange(properties.getTeamSavedImages(teamId), HttpMethod.GET, imageRequest, String.class); } catch (ResourceAccessException e) { log.warn("Error connecting to image service: {}", e); return new HashMap<>(); } String imageResponseBody = imageResponse.getBody().toString(); String osImageList = new JSONObject(imageResponseBody).getString(teamId); JSONObject osImageObject = new JSONObject(osImageList); log.debug("osImageList: {}", osImageList); log.debug("osImageObject: {}", osImageObject); if (osImageObject == JSONObject.NULL || osImageObject.length() == 0) { log.info("List of saved images for team {} is empty.", teamId); return resultMap; } for (int k = 0; k < osImageObject.names().length(); k++) { String imageName = osImageObject.names().getString(k); String imageStatus = osImageObject.getString(imageName); log.info("Image list for team {}: image name {}, status {}", teamId, imageName, imageStatus); Image image = new Image(); image.setImageName(imageName); image.setDescription("-"); image.setTeamId(teamId); if ("created".equals(imageStatus)) { createdImageList.add(image); } else if ("notfound".equals(imageStatus)) { inProgressImageList.add(image); } } resultMap.put("created", createdImageList); resultMap.put("inProgress", inProgressImageList); return resultMap; } // @RequestMapping("/accept_participation/{teamId}") // public String acceptParticipationRequest(@PathVariable Integer teamId, Model model, HttpSession session) { // int currentLoggedInUserId = getSessionIdOfLoggedInUser(session); // // get user's participation request list // // add this user id to the requested list // teamManager.acceptParticipationRequest(currentLoggedInUserId, teamId); // // remove participation request since accepted // teamManager.removeParticipationRequest(currentLoggedInUserId, teamId); // // // must get team name // String teamName = teamManager.getTeamNameByTeamId(teamId); // teamManager.setInfoMsg("You have just joined Team " + teamName + " !"); // // return "redirect:/teams"; // } // @RequestMapping("/ignore_participation/{teamId}") // public String ignoreParticipationRequest(@PathVariable Integer teamId, Model model, HttpSession session) { // // get user's participation request list // // remove this user id from the requested list // String teamName = teamManager.getTeamNameByTeamId(teamId); // teamManager.ignoreParticipationRequest2(getSessionIdOfLoggedInUser(session), teamId); // teamManager.setInfoMsg("You have just ignored a team request from Team " + teamName + " !"); // // return "redirect:/teams"; // } // @RequestMapping("/withdraw/{teamId}") public String withdrawnJoinRequest(@PathVariable Integer teamId, HttpSession session) { // get user team request // remove this user id from the user's request list String teamName = teamManager.getTeamNameByTeamId(teamId); teamManager.removeUserJoinRequest2(getSessionIdOfLoggedInUser(session), teamId); teamManager.setInfoMsg("You have withdrawn your join request for Team " + teamName); return "redirect:/teams"; } // @RequestMapping(value="/teams/invite_members/{teamId}", method=RequestMethod.GET) // public String inviteMember(@PathVariable Integer teamId, Model model) { // model.addAttribute("teamIdVar", teamId); // model.addAttribute("teamPageInviteMemberForm", new TeamPageInviteMemberForm()); // return "team_page_invite_members"; // } // @RequestMapping(value="/teams/invite_members/{teamId}", method=RequestMethod.POST) // public String sendInvitation(@PathVariable Integer teamId, @ModelAttribute TeamPageInviteMemberForm teamPageInviteMemberForm,Model model) { // int userId = userManager.getUserIdByEmail(teamPageInviteMemberForm.getInviteUserEmail()); // teamManager.addInvitedToParticipateMap(userId, teamId); // return "redirect:/teams"; // } @RequestMapping(value = "/teams/members_approval/{teamId}", method = RequestMethod.GET) public String membersApproval(@PathVariable Integer teamId, Model model) { model.addAttribute("team", teamManager.getTeamByTeamId(teamId)); return "team_page_approve_members"; } @RequestMapping("/teams/members_approval/accept/{teamId}/{userId}") public String acceptJoinRequest(@PathVariable Integer teamId, @PathVariable Integer userId) { teamManager.acceptJoinRequest(userId, teamId); return "redirect:/teams/members_approval/{teamId}"; } @RequestMapping("/teams/members_approval/reject/{teamId}/{userId}") public String rejectJoinRequest(@PathVariable Integer teamId, @PathVariable Integer userId) { teamManager.rejectJoinRequest(userId, teamId); return "redirect:/teams/members_approval/{teamId}"; } //--------------------------Team Profile Page-------------------------- @RequestMapping(value = "/team_profile/{teamId}", method = RequestMethod.GET) public String teamProfile(@PathVariable String teamId, Model model, HttpSession session) { HttpEntity<String> request = createHttpEntityHeaderOnly(); ResponseEntity response = restTemplate.exchange(properties.getTeamById(teamId), HttpMethod.GET, request, String.class); String responseBody = response.getBody().toString(); Team2 team = extractTeamInfo(responseBody); model.addAttribute("team", team); model.addAttribute("owner", team.getOwner()); model.addAttribute("membersList", team.getMembersList()); session.setAttribute("originalTeam", team); request = createHttpEntityHeaderOnly(); response = restTemplate.exchange(properties.getExpListByTeamId(teamId), HttpMethod.GET, request, String.class); JSONArray experimentsArray = new JSONArray(response.getBody().toString()); List<Experiment2> experimentList = new ArrayList<>(); Map<Long, Realization> realizationMap = new HashMap<>(); for (int k = 0; k < experimentsArray.length(); k++) { Experiment2 experiment2 = extractExperiment(experimentsArray.getJSONObject(k).toString()); Realization realization = invokeAndExtractRealization(experiment2.getTeamName(), experiment2.getId()); realizationMap.put(experiment2.getId(), realization); experimentList.add(experiment2); } model.addAttribute("experimentList", experimentList); model.addAttribute("realizationMap", realizationMap); return "team_profile"; } @RequestMapping(value = "/team_profile/{teamId}", method = RequestMethod.POST) public String editTeamProfile( @PathVariable String teamId, @ModelAttribute("team") Team2 editTeam, final RedirectAttributes redirectAttributes, HttpSession session) { boolean errorsFound = false; if (editTeam.getDescription().isEmpty()) { errorsFound = true; redirectAttributes.addFlashAttribute("editDesc", "fail"); } if (errorsFound) { // safer to remove session.removeAttribute("originalTeam"); return "redirect:/team_profile/" + editTeam.getId(); } // can edit team description and team website for now JSONObject teamfields = new JSONObject(); teamfields.put("id", teamId); teamfields.put("name", editTeam.getName()); teamfields.put("description", editTeam.getDescription()); teamfields.put("website", "http://default.com"); teamfields.put("organisationType", editTeam.getOrganisationType()); teamfields.put("privacy", "OPEN"); teamfields.put("status", editTeam.getStatus()); teamfields.put("members", editTeam.getMembersList()); HttpEntity<String> request = createHttpEntityWithBody(teamfields.toString()); ResponseEntity response = restTemplate.exchange(properties.getTeamById(teamId), HttpMethod.PUT, request, String.class); Team2 originalTeam = (Team2) session.getAttribute("originalTeam"); if (!originalTeam.getDescription().equals(editTeam.getDescription())) { redirectAttributes.addFlashAttribute("editDesc", "success"); } // safer to remove session.removeAttribute("originalTeam"); return "redirect:/team_profile/" + teamId; } @RequestMapping("/remove_member/{teamId}/{userId}") public String removeMember(@PathVariable Integer teamId, @PathVariable Integer userId, Model model) { // TODO check if user is indeed in the team // TODO what happens to active experiments of the user? // remove member from the team // reduce the team count teamManager.removeMembers(userId, teamId); return "redirect:/team_profile/{teamId}"; } // @RequestMapping("/team_profile/{teamId}/start_experiment/{expId}") // public String startExperimentFromTeamProfile(@PathVariable Integer teamId, @PathVariable Integer expId, Model model, HttpSession session) { // // start experiment // // ensure experiment is stopped first before starting // experimentManager.startExperiment(getSessionIdOfLoggedInUser(session), expId); // return "redirect:/team_profile/{teamId}"; // } // @RequestMapping("/team_profile/{teamId}/stop_experiment/{expId}") // public String stopExperimentFromTeamProfile(@PathVariable Integer teamId, @PathVariable Integer expId, Model model, HttpSession session) { // // stop experiment // // ensure experiment is in ready mode before stopping // experimentManager.stopExperiment(getSessionIdOfLoggedInUser(session), expId); // return "redirect:/team_profile/{teamId}"; // } // @RequestMapping("/team_profile/{teamId}/remove_experiment/{expId}") // public String removeExperimentFromTeamProfile(@PathVariable Integer teamId, @PathVariable Integer expId, Model model, HttpSession session) { // // remove experiment // // TODO check userid is indeed the experiment owner or team owner // // ensure experiment is stopped first // if (experimentManager.removeExperiment(getSessionIdOfLoggedInUser(session), expId) == true) { // // decrease exp count to be display on Teams page // teamManager.decrementExperimentCount(teamId); // } // model.addAttribute("experimentList", experimentManager.getExperimentListByExperimentOwner(getSessionIdOfLoggedInUser(session))); // return "redirect:/team_profile/{teamId}"; // } // @RequestMapping(value="/team_profile/invite_user/{teamId}", method=RequestMethod.GET) // public String inviteUserFromTeamProfile(@PathVariable Integer teamId, Model model) { // model.addAttribute("teamIdVar", teamId); // model.addAttribute("teamPageInviteMemberForm", new TeamPageInviteMemberForm()); // return "team_profile_invite_members"; // } // @RequestMapping(value="/team_profile/invite_user/{teamId}", method=RequestMethod.POST) // public String sendInvitationFromTeamProfile(@PathVariable Integer teamId, @ModelAttribute TeamPageInviteMemberForm teamPageInviteMemberForm, Model model) { // int userId = userManager.getUserIdByEmail(teamPageInviteMemberForm.getInviteUserEmail()); // teamManager.addInvitedToParticipateMap(userId, teamId); // return "redirect:/team_profile/{teamId}"; // } //--------------------------Apply for New Team Page-------------------------- @RequestMapping(value = "/teams/apply_team", method = RequestMethod.GET) public String teamPageApplyTeam(Model model) { model.addAttribute("teamPageApplyTeamForm", new TeamPageApplyTeamForm()); return "team_page_apply_team"; } @RequestMapping(value = "/teams/apply_team", method = RequestMethod.POST) public String checkApplyTeamInfo( @Valid TeamPageApplyTeamForm teamPageApplyTeamForm, BindingResult bindingResult, HttpSession session, final RedirectAttributes redirectAttributes) throws WebServiceRuntimeException { final String logPrefix = "Existing user apply for new team: {}"; if (bindingResult.hasErrors()) { log.warn(logPrefix, "Application form error " + teamPageApplyTeamForm.toString()); return "team_page_apply_team"; } // log data to ensure data has been parsed log.debug(logPrefix, properties.getRegisterRequestToApplyTeam(session.getAttribute("id").toString())); log.info(logPrefix, teamPageApplyTeamForm.toString()); JSONObject mainObject = new JSONObject(); JSONObject teamFields = new JSONObject(); mainObject.put("team", teamFields); teamFields.put("name", teamPageApplyTeamForm.getTeamName()); teamFields.put("description", teamPageApplyTeamForm.getTeamDescription()); teamFields.put("website", teamPageApplyTeamForm.getTeamWebsite()); teamFields.put("organisationType", teamPageApplyTeamForm.getTeamOrganizationType()); teamFields.put("visibility", teamPageApplyTeamForm.getIsPublic()); String nclUserId = session.getAttribute("id").toString(); HttpEntity<String> request = createHttpEntityWithBody(mainObject.toString()); ResponseEntity response; try { response = restTemplate.exchange(properties.getRegisterRequestToApplyTeam(nclUserId), HttpMethod.POST, request, String.class); String responseBody = response.getBody().toString(); if (RestUtil.isError(response.getStatusCode())) { // prepare the exception mapping EnumMap<ExceptionState, String> exceptionMessageMap = new EnumMap<>(ExceptionState.class); exceptionMessageMap.put(USER_ID_NULL_OR_EMPTY_EXCEPTION, "User id is null or empty "); exceptionMessageMap.put(TEAM_NAME_NULL_OR_EMPTY_EXCEPTION, "Team name is null or empty "); exceptionMessageMap.put(USER_NOT_FOUND_EXCEPTION, "User not found"); exceptionMessageMap.put(TEAM_NAME_ALREADY_EXISTS_EXCEPTION, "Team name already exists"); exceptionMessageMap.put(INVALID_TEAM_NAME_EXCEPTION, "Team name contains invalid characters"); exceptionMessageMap.put(TEAM_MEMBER_ALREADY_EXISTS_EXCEPTION, "Team member already exists"); exceptionMessageMap.put(ADAPTER_CONNECTION_EXCEPTION, "Connection to adapter failed"); exceptionMessageMap.put(ADAPTER_INTERNAL_ERROR_EXCEPTION, "Internal server error on adapter"); exceptionMessageMap.put(DETERLAB_OPERATION_FAILED_EXCEPTION, "Operation failed on DeterLab"); MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class); ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError()); final String errorMessage = exceptionMessageMap.containsKey(exceptionState) ? error.getMessage() : ERR_SERVER_OVERLOAD; log.warn(logPrefix, responseBody); redirectAttributes.addFlashAttribute("message", errorMessage); return "redirect:/teams/apply_team"; } else { // no errors, everything ok log.info (logPrefix, "Application for team " + teamPageApplyTeamForm.getTeamName() + " submitted"); return "redirect:/teams/team_application_submitted"; } } catch (ResourceAccessException | IOException e) { log.error(logPrefix, e); throw new WebServiceRuntimeException(e.getMessage()); } } @RequestMapping(value = "/acceptable_usage_policy", method = RequestMethod.GET) public String teamOwnerPolicy() { return "acceptable_usage_policy"; } @RequestMapping(value = "/terms_and_conditions", method = RequestMethod.GET) public String termsAndConditions() { return "terms_and_conditions"; } //--------------------------Join Team Page-------------------------- @RequestMapping(value = "/teams/join_team", method = RequestMethod.GET) public String teamPageJoinTeam(Model model) { model.addAttribute("teamPageJoinTeamForm", new TeamPageJoinTeamForm()); return "team_page_join_team"; } @RequestMapping(value = "/teams/join_team", method = RequestMethod.POST) public String checkJoinTeamInfo( @Valid TeamPageJoinTeamForm teamPageJoinForm, BindingResult bindingResult, Model model, HttpSession session, final RedirectAttributes redirectAttributes) throws WebServiceRuntimeException { final String logPrefix = "Existing user join team: {}"; if (bindingResult.hasErrors()) { log.warn(logPrefix, "Application form error " + teamPageJoinForm.toString()); return "team_page_join_team"; } JSONObject mainObject = new JSONObject(); JSONObject teamFields = new JSONObject(); JSONObject userFields = new JSONObject(); mainObject.put("team", teamFields); mainObject.put("user", userFields); userFields.put("id", session.getAttribute("id")); // ncl-id teamFields.put("name", teamPageJoinForm.getTeamName()); log.info(logPrefix, "User " + session.getAttribute("id") + ", team " + teamPageJoinForm.getTeamName()); HttpEntity<String> request = createHttpEntityWithBody(mainObject.toString()); ResponseEntity response; try { restTemplate.setErrorHandler(new MyResponseErrorHandler()); response = restTemplate.exchange(properties.getJoinRequestExistingUser(), HttpMethod.POST, request, String.class); String responseBody = response.getBody().toString(); if (RestUtil.isError(response.getStatusCode())) { // prepare the exception mapping EnumMap<ExceptionState, String> exceptionMessageMap = new EnumMap<>(ExceptionState.class); exceptionMessageMap.put(USER_NOT_FOUND_EXCEPTION, "User not found"); exceptionMessageMap.put(USER_ID_NULL_OR_EMPTY_EXCEPTION, "User id is null or empty"); exceptionMessageMap.put(TEAM_NOT_FOUND_EXCEPTION, "Team name not found"); exceptionMessageMap.put(TEAM_NAME_NULL_OR_EMPTY_EXCEPTION, "Team name is null or empty"); exceptionMessageMap.put(USER_ALREADY_IN_TEAM_EXCEPTION, "User already in team"); exceptionMessageMap.put(TEAM_MEMBER_ALREADY_EXISTS_EXCEPTION, "Team member already exists"); exceptionMessageMap.put(ADAPTER_CONNECTION_EXCEPTION, "Connection to adapter failed"); exceptionMessageMap.put(ADAPTER_INTERNAL_ERROR_EXCEPTION, "Internal server error on adapter"); exceptionMessageMap.put(DETERLAB_OPERATION_FAILED_EXCEPTION, "Operation failed on DeterLab"); MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class); ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError()); final String errorMessage = exceptionMessageMap.containsKey(exceptionState) ? error.getMessage() : ERR_SERVER_OVERLOAD; log.warn(logPrefix, responseBody); redirectAttributes.addFlashAttribute("message", errorMessage); return "redirect:/teams/join_team"; } else { log.info(logPrefix, "Application for join team " + teamPageJoinForm.getTeamName()+ " submitted"); return "redirect:/teams/join_application_submitted/" + teamPageJoinForm.getTeamName(); } } catch (ResourceAccessException | IOException e) { throw new WebServiceRuntimeException(e.getMessage()); } } //--------------------------Experiment Page-------------------------- @RequestMapping(value = "/experiments", method = RequestMethod.GET) public String experiments(Model model, HttpSession session) throws WebServiceRuntimeException { // long start = System.currentTimeMillis(); List<Experiment2> experimentList = new ArrayList<>(); Map<Long, Realization> realizationMap = new HashMap<>(); HttpEntity<String> request = createHttpEntityHeaderOnly(); restTemplate.setErrorHandler(new MyResponseErrorHandler()); ResponseEntity response = restTemplate.exchange(properties.getDeterUid(session.getAttribute("id").toString()), HttpMethod.GET, request, String.class); String responseBody = response.getBody().toString(); try { if (RestUtil.isError(response.getStatusCode())) { log.error("No user to get experiment: {}", session.getAttribute("id")); MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class); log.info("experiment error: {} - {} - {} - user token:{}", error.getError(), error.getMessage(), error.getLocalizedMessage(), httpScopedSession.getAttribute(webProperties.getSessionJwtToken())); model.addAttribute(DETER_UID, CONNECTION_ERROR); } else { log.info("Show the deter user id: {}", responseBody); model.addAttribute(DETER_UID, responseBody); } } catch (IOException e) { throw new WebServiceRuntimeException(e.getMessage()); } // get list of teamids ResponseEntity userRespEntity = restTemplate.exchange(properties.getUser(session.getAttribute("id").toString()), HttpMethod.GET, request, String.class); JSONObject object = new JSONObject(userRespEntity.getBody().toString()); JSONArray teamIdsJsonArray = object.getJSONArray("teams"); for (int i = 0; i < teamIdsJsonArray.length(); i++) { String teamId = teamIdsJsonArray.get(i).toString(); HttpEntity<String> teamRequest = createHttpEntityHeaderOnly(); ResponseEntity teamResponse = restTemplate.exchange(properties.getTeamById(teamId), HttpMethod.GET, teamRequest, String.class); String teamResponseBody = teamResponse.getBody().toString(); if (!isMemberJoinRequestPending(session.getAttribute("id").toString(), teamResponseBody)) { // get experiments lists of the teams HttpEntity<String> expRequest = createHttpEntityHeaderOnly(); ResponseEntity expRespEntity = restTemplate.exchange(properties.getExpListByTeamId(teamId), HttpMethod.GET, expRequest, String.class); JSONArray experimentsArray = new JSONArray(expRespEntity.getBody().toString()); for (int k = 0; k < experimentsArray.length(); k++) { Experiment2 experiment2 = extractExperiment(experimentsArray.getJSONObject(k).toString()); Realization realization = invokeAndExtractRealization(experiment2.getTeamName(), experiment2.getId()); realizationMap.put(experiment2.getId(), realization); experimentList.add(experiment2); } } } model.addAttribute("experimentList", experimentList); model.addAttribute("realizationMap", realizationMap); // System.out.println("Elapsed time to get experiment page:" + (System.currentTimeMillis() - start)); return "experiments"; } @RequestMapping(value = "/experiments/create", method = RequestMethod.GET) public String createExperiment(Model model, HttpSession session) throws WebServiceRuntimeException { log.info("Loading create experiment page"); // a list of teams that the logged in user is in List<String> scenarioFileNameList = getScenarioFileNameList(); List<Team2> userTeamsList = new ArrayList<>(); // get list of teamids HttpEntity<String> request = createHttpEntityHeaderOnly(); ResponseEntity response = restTemplate.exchange(properties.getUser(session.getAttribute("id").toString()), HttpMethod.GET, request, String.class); String responseBody = response.getBody().toString(); JSONObject object = new JSONObject(responseBody); JSONArray teamIdsJsonArray = object.getJSONArray("teams"); for (int i = 0; i < teamIdsJsonArray.length(); i++) { String teamId = teamIdsJsonArray.get(i).toString(); HttpEntity<String> teamRequest = createHttpEntityHeaderOnly(); ResponseEntity teamResponse = restTemplate.exchange(properties.getTeamById(teamId), HttpMethod.GET, teamRequest, String.class); String teamResponseBody = teamResponse.getBody().toString(); Team2 team2 = extractTeamInfo(teamResponseBody); userTeamsList.add(team2); } model.addAttribute("scenarioFileNameList", scenarioFileNameList); model.addAttribute("experimentForm", new ExperimentForm()); model.addAttribute("userTeamsList", userTeamsList); return "experiment_page_create_experiment"; } @RequestMapping(value = "/experiments/create", method = RequestMethod.POST) public String validateExperiment( @ModelAttribute("experimentForm") ExperimentForm experimentForm, HttpSession session, BindingResult bindingResult, final RedirectAttributes redirectAttributes) throws WebServiceRuntimeException { if (bindingResult.hasErrors()) { log.info("Create experiment - form has errors"); return "redirect:/experiments/create"; } if (experimentForm.getName() == null || experimentForm.getName().isEmpty()) { redirectAttributes.addFlashAttribute(MESSAGE, "Experiment Name cannot be empty"); return "redirect:/experiments/create"; } if (experimentForm.getDescription() == null || experimentForm.getDescription().isEmpty()) { redirectAttributes.addFlashAttribute(MESSAGE, "Description cannot be empty"); return "redirect:/experiments/create"; } experimentForm.setScenarioContents(getScenarioContentsFromFile(experimentForm.getScenarioFileName())); JSONObject experimentObject = new JSONObject(); experimentObject.put("userId", session.getAttribute("id").toString()); experimentObject.put("teamId", experimentForm.getTeamId()); experimentObject.put(TEAM_NAME, experimentForm.getTeamName()); experimentObject.put("name", experimentForm.getName().replaceAll("\\s+", "")); // truncate whitespaces and non-visible characters like \n experimentObject.put("description", experimentForm.getDescription()); experimentObject.put("nsFile", "file"); experimentObject.put("nsFileContent", experimentForm.getNsFileContent()); experimentObject.put("idleSwap", "240"); experimentObject.put("maxDuration", "960"); log.info("Calling service to create experiment"); HttpEntity<String> request = createHttpEntityWithBody(experimentObject.toString()); restTemplate.setErrorHandler(new MyResponseErrorHandler()); ResponseEntity response = restTemplate.exchange(properties.getSioExpUrl(), HttpMethod.POST, request, String.class); String responseBody = response.getBody().toString(); try { if (RestUtil.isError(response.getStatusCode())) { MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class); ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError()); switch (exceptionState) { case NS_FILE_PARSE_EXCEPTION: log.warn("Ns file error"); redirectAttributes.addFlashAttribute(MESSAGE, "There is an error when parsing the NS File."); break; case EXPERIMENT_NAME_ALREADY_EXISTS_EXCEPTION: log.warn("Exp name already exists"); redirectAttributes.addFlashAttribute(MESSAGE, "Experiment name already exists."); break; default: log.warn("Exp service or adapter fail"); // possible sio or adapter connection fail redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD); break; } log.info("Experiment {} created", experimentForm); return "redirect:/experiments/create"; } } catch (IOException e) { throw new WebServiceRuntimeException(e.getMessage()); } // // TODO Uploaded function for network configuration and optional dataset // if (!networkFile.isEmpty()) { // try { // String networkFileName = getSessionIdOfLoggedInUser(session) + "-networkconfig-" + networkFile.getOriginalFilename(); // BufferedOutputStream stream = new BufferedOutputStream( // new FileOutputStream(new File(App.EXP_CONFIG_DIR + "/" + networkFileName))); // FileCopyUtils.copy(networkFile.getInputStream(), stream); // stream.close(); // redirectAttributes.addFlashAttribute(MESSAGE, // "You successfully uploaded " + networkFile.getOriginalFilename() + "!"); // // remember network file name here // } // catch (Exception e) { // redirectAttributes.addFlashAttribute(MESSAGE, // "You failed to upload " + networkFile.getOriginalFilename() + " => " + e.getMessage()); // return "redirect:/experiments/create"; // } // } // // if (!dataFile.isEmpty()) { // try { // String dataFileName = getSessionIdOfLoggedInUser(session) + "-data-" + dataFile.getOriginalFilename(); // BufferedOutputStream stream = new BufferedOutputStream( // new FileOutputStream(new File(App.EXP_CONFIG_DIR + "/" + dataFileName))); // FileCopyUtils.copy(dataFile.getInputStream(), stream); // stream.close(); // redirectAttributes.addFlashAttribute("message2", // "You successfully uploaded " + dataFile.getOriginalFilename() + "!"); // // remember data file name here // } // catch (Exception e) { // redirectAttributes.addFlashAttribute("message2", // "You failed to upload " + dataFile.getOriginalFilename() + " => " + e.getMessage()); // } // } // // // add current experiment to experiment manager // experimentManager.addExperiment(getSessionIdOfLoggedInUser(session), experiment); // // increase exp count to be display on Teams page // teamManager.incrementExperimentCount(experiment.getTeamId()); return "redirect:/experiments"; } @RequestMapping(value = "/experiments/save_image/{teamId}/{expId}/{nodeId}", method = RequestMethod.GET) public String saveExperimentImage(@PathVariable String teamId, @PathVariable String expId, @PathVariable String nodeId, Model model) { Map<String, Map<String, String>> singleNodeInfoMap = new HashMap<>(); Image saveImageForm = new Image(); String teamName = invokeAndExtractTeamInfo(teamId).getName(); Realization realization = invokeAndExtractRealization(teamName, Long.parseLong(expId)); // experiment may have many nodes // extract just the particular node details to display for (Map.Entry<String, Map<String, String>> nodesInfo : realization.getNodesInfoMap().entrySet()) { String nodeName = nodesInfo.getKey(); Map<String, String> singleNodeDetailsMap = nodesInfo.getValue(); if (singleNodeDetailsMap.get(NODE_ID).equals(nodeId)) { singleNodeInfoMap.put(nodeName, singleNodeDetailsMap); // store the current os of the node into the form also // have to pass the the services saveImageForm.setCurrentOS(singleNodeDetailsMap.get("os")); } } saveImageForm.setTeamId(teamId); saveImageForm.setNodeId(nodeId); model.addAttribute("teamName", teamName); model.addAttribute("singleNodeInfoMap", singleNodeInfoMap); model.addAttribute("pathTeamId", teamId); model.addAttribute("pathExperimentId", expId); model.addAttribute("pathNodeId", nodeId); model.addAttribute("experimentName", realization.getExperimentName()); model.addAttribute("saveImageForm", saveImageForm); return "save_experiment_image"; } // bindingResult is required in the method signature to perform the JSR303 validation for Image object @RequestMapping(value = "/experiments/save_image/{teamId}/{expId}/{nodeId}", method = RequestMethod.POST) public String saveExperimentImage( @Valid @ModelAttribute("saveImageForm") Image saveImageForm, BindingResult bindingResult, RedirectAttributes redirectAttributes, @PathVariable String teamId, @PathVariable String expId, @PathVariable String nodeId) throws IOException { if (saveImageForm.getImageName().length() < 2) { log.warn("Save image form has errors {}", saveImageForm); redirectAttributes.addFlashAttribute("message", "Image name too short, minimum 2 characters"); return "redirect:/experiments/save_image/" + teamId + "/" + expId + "/" + nodeId; } log.info("Saving image: team {}, experiment {}, node {}", teamId, expId, nodeId); ObjectMapper mapper = new ObjectMapper(); HttpEntity<String> request = createHttpEntityWithBody(mapper.writeValueAsString(saveImageForm)); restTemplate.setErrorHandler(new MyResponseErrorHandler()); ResponseEntity response = restTemplate.exchange(properties.saveImage(), HttpMethod.POST, request, String.class); String responseBody = response.getBody().toString(); if (RestUtil.isError(response.getStatusCode())) { MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class); ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError()); log.warn("Save image: error with exception {}", exceptionState); switch (exceptionState) { case DETERLAB_OPERATION_FAILED_EXCEPTION: log.warn("Save image: error, operation failed on DeterLab"); redirectAttributes.addFlashAttribute("message", error.getMessage()); break; case ADAPTER_CONNECTION_EXCEPTION: log.warn("Save image: error, cannot connect to adapter"); redirectAttributes.addFlashAttribute("message", "connection to adapter failed"); break; case ADAPTER_INTERNAL_ERROR_EXCEPTION: log.warn("Save image: error, adapter internal server error"); redirectAttributes.addFlashAttribute("message", "internal error was found on the adapter"); break; default: log.warn("Save image: other error"); redirectAttributes.addFlashAttribute("message", ERR_SERVER_OVERLOAD); } return "redirect:/experiments/save_image/" + teamId + "/" + expId + "/" + nodeId; } // everything looks ok log.info("Save image in progress: team {}, experiment {}, node {}, image {}", teamId, expId, nodeId, saveImageForm.getImageName()); return "redirect:/experiments"; } /* private String processSaveImageRequest(@Valid @ModelAttribute("saveImageForm") Image saveImageForm, RedirectAttributes redirectAttributes, @PathVariable String teamId, @PathVariable String expId, @PathVariable String nodeId, ResponseEntity response, String responseBody) throws IOException { if (RestUtil.isError(response.getStatusCode())) { MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class); ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError()); log.warn("Save image exception: {}", exceptionState); switch (exceptionState) { case DETERLAB_OPERATION_FAILED_EXCEPTION: log.warn("adapter deterlab operation failed exception"); redirectAttributes.addFlashAttribute("message", error.getMessage()); break; default: log.warn("Image service or adapter fail"); // possible sio or adapter connection fail redirectAttributes.addFlashAttribute("message", ERR_SERVER_OVERLOAD); break; } return "redirect:/experiments/save_image/" + teamId + "/" + expId + "/" + nodeId; } else { // everything ok log.info("Image service in progress for Team: {}, Exp: {}, Node: {}, Image: {}", teamId, expId, nodeId, saveImageForm.getImageName()); return "redirect:/experiments"; } } */ // @RequestMapping("/experiments/configuration/{expId}") // public String viewExperimentConfiguration(@PathVariable Integer expId, Model model) { // // get experiment from expid // // retrieve the scenario contents to be displayed // Experiment currExp = experimentManager.getExperimentByExpId(expId); // model.addAttribute("scenarioContents", currExp.getScenarioContents()); // return "experiment_scenario_contents"; // } @RequestMapping("/remove_experiment/{teamName}/{teamId}/{expId}") public String removeExperiment(@PathVariable String teamName, @PathVariable String teamId, @PathVariable String expId, final RedirectAttributes redirectAttributes, HttpSession session) throws WebServiceRuntimeException { // TODO check userid is indeed the experiment owner or team owner // ensure experiment is stopped first Realization realization = invokeAndExtractRealization(teamName, Long.parseLong(expId)); // check valid authentication to remove experiments if (!validateIfAdmin(session) && !realization.getUserId().equals(session.getAttribute("id").toString())) { log.warn("Permission denied when remove Team:{}, Experiment: {} with User: {}, Role:{}", teamId, expId, session.getAttribute("id"), session.getAttribute(webProperties.getSessionRoles())); redirectAttributes.addFlashAttribute(MESSAGE, "An error occurred while trying to remove experiment;" + permissionDeniedMessage); return "redirect:/experiments"; } if (!realization.getState().equals(RealizationState.NOT_RUNNING.toString())) { log.warn("Trying to remove Team: {}, Experiment: {} with State: {} that is still in progress?", teamId, expId, realization.getState()); redirectAttributes.addFlashAttribute(MESSAGE, "An error occurred while trying to remove Exp: " + realization.getExperimentName() + ". Please refresh the page again. If the error persists, please contact " + CONTACT_EMAIL); return "redirect:/experiments"; } log.info("Removing experiment: at " + properties.getDeleteExperiment(teamId, expId)); HttpEntity<String> request = createHttpEntityHeaderOnly(); restTemplate.setErrorHandler(new MyResponseErrorHandler()); ResponseEntity response; try { response = restTemplate.exchange(properties.getDeleteExperiment(teamId, expId), HttpMethod.DELETE, request, String.class); } catch (Exception e) { log.warn("Error connecting to experiment service to remove experiment", e.getMessage()); redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD); return "redirect:/experiments"; } String responseBody = response.getBody().toString(); try { if (RestUtil.isError(response.getStatusCode())) { MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class); ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError()); switch (exceptionState) { case EXPERIMENT_DELETE_EXCEPTION: case FORBIDDEN_EXCEPTION: log.warn("remove experiment failed for Team: {}, Exp: {}", teamId, expId); redirectAttributes.addFlashAttribute(MESSAGE, error.getMessage()); break; case OBJECT_OPTIMISTIC_LOCKING_FAILURE_EXCEPTION: // do nothing log.info("remove experiment database locking failure"); break; default: // do nothing break; } return "redirect:/experiments"; } else { // everything ok log.info("remove experiment success for Team: {}, Exp: {}", teamId, expId); redirectAttributes.addFlashAttribute("exp_remove_message", "Team: " + teamName + " has removed Exp: " + realization.getExperimentName()); return "redirect:/experiments"; } } catch (IOException e) { throw new WebServiceRuntimeException(e.getMessage()); } } @RequestMapping("/start_experiment/{teamName}/{expId}") public String startExperiment( @PathVariable String teamName, @PathVariable String expId, final RedirectAttributes redirectAttributes, Model model, HttpSession session) throws WebServiceRuntimeException { // ensure experiment is stopped first before starting Realization realization = invokeAndExtractRealization(teamName, Long.parseLong(expId)); if (!checkPermissionRealizeExperiment(realization, session)) { log.warn("Permission denied to start experiment: {} for team: {}", realization.getExperimentName(), teamName); redirectAttributes.addFlashAttribute(MESSAGE, permissionDeniedMessage); return "redirect:/experiments"; } String teamStatus = getTeamStatus(realization.getTeamId()); if (!teamStatus.equals(TeamStatus.APPROVED.name())) { log.warn("Error: trying to realize an experiment {} on team {} with status {}", realization.getExperimentName(), realization.getTeamId(), teamStatus); redirectAttributes.addFlashAttribute(MESSAGE, teamName + " is in " + teamStatus + " status and does not have permission to start experiment. Please contact " + CONTACT_EMAIL); return "redirect:/experiments"; } if (!realization.getState().equals(RealizationState.NOT_RUNNING.toString())) { log.warn("Trying to start Team: {}, Experiment: {} with State: {} that is not running?", teamName, expId, realization.getState()); redirectAttributes.addFlashAttribute(MESSAGE, "An error occurred while trying to start Exp: " + realization.getExperimentName() + ". Please refresh the page again. If the error persists, please contact " + CONTACT_EMAIL); return "redirect:/experiments"; } log.info("Starting experiment: at " + properties.getStartExperiment(teamName, expId)); HttpEntity<String> request = createHttpEntityHeaderOnly(); restTemplate.setErrorHandler(new MyResponseErrorHandler()); ResponseEntity response; try { response = restTemplate.exchange(properties.getStartExperiment(teamName, expId), HttpMethod.POST, request, String.class); } catch (Exception e) { log.warn("Error connecting to experiment service to start experiment", e.getMessage()); redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD); return "redirect:/experiments"; } String responseBody = response.getBody().toString(); try { if (RestUtil.isError(response.getStatusCode())) { MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class); ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError()); switch (exceptionState) { case EXPERIMENT_START_EXCEPTION: case FORBIDDEN_EXCEPTION: log.warn("start experiment failed for Team: {}, Exp: {}", teamName, expId); redirectAttributes.addFlashAttribute(MESSAGE, error.getMessage()); return "redirect:/experiments"; case OBJECT_OPTIMISTIC_LOCKING_FAILURE_EXCEPTION: // do nothing log.info("start experiment database locking failure"); break; default: // do nothing break; } log.warn("start experiment some other error occurred exception: {}", exceptionState); // possible for it to be error but experiment has started up finish // if user clicks on start but reloads the page // model.addAttribute(EXPERIMENT_MESSAGE, "Team: " + teamName + " has started Exp: " + realization.getExperimentName()); return "experiments"; } else { // everything ok log.info("start experiment success for Team: {}, Exp: {}", teamName, expId); redirectAttributes.addFlashAttribute(EXPERIMENT_MESSAGE, "Experiment " + realization.getExperimentName() + " in team " + teamName + " is starting. This may take up to 10 minutes depending on the scale of your experiment. Please refresh this page later."); return "redirect:/experiments"; } } catch (IOException e) { log.warn("start experiment error: {]", e.getMessage()); throw new WebServiceRuntimeException(e.getMessage()); } } @RequestMapping("/stop_experiment/{teamName}/{expId}") public String stopExperiment(@PathVariable String teamName, @PathVariable String expId, Model model, final RedirectAttributes redirectAttributes, HttpSession session) throws WebServiceRuntimeException { // ensure experiment is active first before stopping Realization realization = invokeAndExtractRealization(teamName, Long.parseLong(expId)); if (isNotAdminAndNotInTeam(session, realization)) { log.warn("Permission denied to stop experiment: {} for team: {}", realization.getExperimentName(), teamName); redirectAttributes.addFlashAttribute(MESSAGE, permissionDeniedMessage); return "redirect:/experiments"; } if (!realization.getState().equals(RealizationState.RUNNING.toString())) { log.warn("Trying to stop Team: {}, Experiment: {} with State: {} that is still in progress?", teamName, expId, realization.getState()); redirectAttributes.addFlashAttribute(MESSAGE, "An error occurred while trying to stop Exp: " + realization.getExperimentName() + ". Please refresh the page again. If the error persists, please contact " + CONTACT_EMAIL); return "redirect:/experiments"; } log.info("Stopping experiment: at " + properties.getStopExperiment(teamName, expId)); HttpEntity<String> request = createHttpEntityHeaderOnly(); restTemplate.setErrorHandler(new MyResponseErrorHandler()); ResponseEntity response; return abc(teamName, expId, redirectAttributes, realization, request); } @RequestMapping("/get_topology/{teamName}/{expId}") @ResponseBody public String getTopology(@PathVariable String teamName, @PathVariable String expId) { try { HttpEntity<String> request = createHttpEntityHeaderOnly(); ResponseEntity response = restTemplate.exchange(properties.getTopology(teamName, expId), HttpMethod.GET, request, String.class); log.info("Retrieve experiment topo success"); return "data:image/png;base64," + response.getBody(); } catch (Exception e) { log.error("Error getting topology thumbnail", e.getMessage()); return ""; } } private String abc(@PathVariable String teamName, @PathVariable String expId, RedirectAttributes redirectAttributes, Realization realization, HttpEntity<String> request) throws WebServiceRuntimeException { ResponseEntity response; try { response = restTemplate.exchange(properties.getStopExperiment(teamName, expId), HttpMethod.POST, request, String.class); } catch (Exception e) { log.warn("Error connecting to experiment service to stop experiment", e.getMessage()); redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD); return "redirect:/experiments"; } String responseBody = response.getBody().toString(); try { if (RestUtil.isError(response.getStatusCode())) { MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class); ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError()); if (exceptionState == ExceptionState.FORBIDDEN_EXCEPTION) { log.warn("Permission denied to stop experiment: {} for team: {}", realization.getExperimentName(), teamName); redirectAttributes.addFlashAttribute(MESSAGE, permissionDeniedMessage); } if (exceptionState == ExceptionState.OBJECT_OPTIMISTIC_LOCKING_FAILURE_EXCEPTION) { log.info("stop experiment database locking failure"); } } else { // everything ok log.info("stop experiment success for Team: {}, Exp: {}", teamName, expId); redirectAttributes.addFlashAttribute(EXPERIMENT_MESSAGE, "Experiment " + realization.getExperimentName() + " in team " + teamName + " is stopping. Please refresh this page in a few minutes."); } return "redirect:/experiments"; } catch (IOException e) { throw new WebServiceRuntimeException(e.getMessage()); } } private boolean isNotAdminAndNotInTeam(HttpSession session, Realization realization) { return !validateIfAdmin(session) && !checkPermissionRealizeExperiment(realization, session); } //---------------------------------Dataset Page-------------------------- // @RequestMapping("/data/public/request_access/{dataOwnerId}") // public String requestAccessForDataset(@PathVariable Integer dataOwnerId, Model model) { // // TODO // // send reuqest to team owner // // show feedback to users // User rv = userManager.getUserById(dataOwnerId); // model.addAttribute("ownerName", rv.getError()); // model.addAttribute("ownerEmail", rv.getEmail()); // return "data_request_access"; // } //----------------------------------------------------------------------- //--------------------------Admin Revamp--------------------------------- //----------------------------------------------------------------------- //---------------------------------Admin--------------------------------- @RequestMapping("/admin") public String admin(Model model, HttpSession session) { if (!validateIfAdmin(session)) { return NO_PERMISSION_PAGE; } TeamManager2 teamManager2 = new TeamManager2(); Map<String, List<String>> userToTeamMap = new HashMap<>(); // userId : list of team names List<Team2> pendingApprovalTeamsList = new ArrayList<>(); //------------------------------------ // get list of teams // get list of teams pending for approval //------------------------------------ HttpEntity<String> request = createHttpEntityHeaderOnly(); ResponseEntity responseEntity = restTemplate.exchange(properties.getSioTeamsUrl(), HttpMethod.GET, request, String.class); JSONArray jsonArray = new JSONArray(responseEntity.getBody().toString()); for (int i = 0; i < jsonArray.length(); i++) { JSONObject jsonObject = jsonArray.getJSONObject(i); Team2 one = extractTeamInfo(jsonObject.toString()); teamManager2.addTeamToTeamMap(one); if (one.getStatus().equals(TeamStatus.PENDING.name())) { pendingApprovalTeamsList.add(one); } } //------------------------------------ // get list of users //------------------------------------ ResponseEntity response2 = restTemplate.exchange(properties.getSioUsersUrl(), HttpMethod.GET, request, String.class); String responseBody2 = response2.getBody().toString(); JSONArray jsonUserArray = new JSONArray(responseBody2); List<User2> usersList = new ArrayList<>(); for (int i = 0; i < jsonUserArray.length(); i++) { JSONObject userObject = jsonUserArray.getJSONObject(i); User2 user = extractUserInfo(userObject.toString()); usersList.add(user); // get list of teams' names for each user List<String> perUserTeamList = new ArrayList<>(); if (userObject.get("teams") != null) { JSONArray teamJsonArray = userObject.getJSONArray("teams"); for (int k = 0; k < teamJsonArray.length(); k++) { Team2 team = invokeAndExtractTeamInfo(teamJsonArray.get(k).toString()); perUserTeamList.add(team.getName()); } userToTeamMap.put(user.getId(), perUserTeamList); } } //------------------------------------ // get list of datasets //------------------------------------ ResponseEntity response3 = restTemplate.exchange(properties.getData(), HttpMethod.GET, request, String.class); String responseBody3 = response3.getBody().toString(); List<Dataset> datasetsList = new ArrayList<>(); JSONArray dataJsonArray = new JSONArray(responseBody3); for (int i = 0; i < dataJsonArray.length(); i++) { JSONObject dataInfoObject = dataJsonArray.getJSONObject(i); Dataset dataset = extractDataInfo(dataInfoObject.toString()); datasetsList.add(dataset); } model.addAttribute("teamsMap", teamManager2.getTeamMap()); model.addAttribute("pendingApprovalTeamsList", pendingApprovalTeamsList); model.addAttribute("usersList", usersList); model.addAttribute("userToTeamMap", userToTeamMap); model.addAttribute("dataList", datasetsList); return "admin2"; } @RequestMapping("/admin/experiments") public String adminExperimentsManagement(Model model, HttpSession session) { if (!validateIfAdmin(session)) { return NO_PERMISSION_PAGE; } //------------------------------------ // get list of experiments //------------------------------------ HttpEntity<String> expRequest = createHttpEntityHeaderOnly(); ResponseEntity expResponseEntity = restTemplate.exchange(properties.getAllExperiment(), HttpMethod.GET, expRequest, String.class); JSONArray jsonExpArray = new JSONArray(expResponseEntity.getBody().toString()); List<Experiment2> experimentList = new ArrayList<>(); Map<Long, Realization> realizationMap = new HashMap<>(); for (int i = 0; i < jsonExpArray.length(); i++) { Experiment2 experiment2 = extractExperiment(jsonExpArray.getJSONObject(i).toString()); Realization realization = invokeAndExtractRealization(experiment2.getTeamName(), experiment2.getId()); realizationMap.put(experiment2.getId(), realization); experimentList.add(experiment2); } model.addAttribute("adminExpList", experimentList); model.addAttribute("adminRealizationMap", realizationMap); return "experiment_dashboard"; } @RequestMapping(value = "/admin/{teamId}", method = RequestMethod.GET) public String admin(@PathVariable String teamId, Model model, HttpSession session) { HttpEntity<String> exprequest = createHttpEntityHeaderOnly(); ResponseEntity expresponse = restTemplate.exchange(properties.getTeamById(teamId), HttpMethod.GET, exprequest, String.class); exprequest = createHttpEntityHeaderOnly(); expresponse = restTemplate.exchange(properties.getExpListByTeamId(teamId), HttpMethod.GET, exprequest, String.class); JSONArray experimentsArray = new JSONArray(expresponse.getBody().toString()); List<Experiment2> experimentList = new ArrayList<>(); Map<Long, Realization> realizationMap = new HashMap<>(); for (int k = 0; k < experimentsArray.length(); k++) { Experiment2 experiment2 = extractExperiment(experimentsArray.getJSONObject(k).toString()); Realization realization = invokeAndExtractRealization(experiment2.getTeamName(), experiment2.getId()); realizationMap.put(experiment2.getId(), realization); experimentList.add(experiment2); } model.addAttribute("experimentList", experimentList); model.addAttribute("realizationMap", realizationMap); return "admin2"; } // @RequestMapping(value="/admin/domains/add", method=RequestMethod.POST) // public String addDomain(@Valid Domain domain, BindingResult bindingResult) { // if (bindingResult.hasErrors()) { // return "redirect:/admin"; // } else { // domainManager.addDomains(domain.getDomainName()); // } // return "redirect:/admin"; // } // @RequestMapping("/admin/domains/remove/{domainKey}") // public String removeDomain(@PathVariable String domainKey) { // domainManager.removeDomains(domainKey); // return "redirect:/admin"; // } @RequestMapping("/admin/teams/accept/{teamId}/{teamOwnerId}") public String approveTeam( @PathVariable String teamId, @PathVariable String teamOwnerId, final RedirectAttributes redirectAttributes, HttpSession session ) throws WebServiceRuntimeException { if (!validateIfAdmin(session)) { return NO_PERMISSION_PAGE; } //FIXME require approver info log.info("Approving new team {}, team owner {}", teamId, teamOwnerId); HttpEntity<String> request = createHttpEntityHeaderOnly(); restTemplate.setErrorHandler(new MyResponseErrorHandler()); ResponseEntity response = restTemplate.exchange( properties.getApproveTeam(teamId, teamOwnerId, TeamStatus.APPROVED), HttpMethod.POST, request, String.class); String responseBody = response.getBody().toString(); if (RestUtil.isError(response.getStatusCode())) { MyErrorResource error; try { error = objectMapper.readValue(responseBody, MyErrorResource.class); } catch (IOException e) { throw new WebServiceRuntimeException(e.getMessage()); } ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError()); switch (exceptionState) { case TEAM_ID_NULL_OR_EMPTY_EXCEPTION: log.warn("Approve team: TeamId cannot be null or empty: {}", teamId); redirectAttributes.addFlashAttribute(MESSAGE, "TeamId cannot be null or empty"); break; case USER_ID_NULL_OR_EMPTY_EXCEPTION: log.warn("Approve team: UserId cannot be null or empty: {}", teamOwnerId); redirectAttributes.addFlashAttribute(MESSAGE, "UserId cannot be null or empty"); break; case INVALID_TEAM_STATUS_EXCEPTION: log.warn("Approve team: TeamStatus is invalid"); redirectAttributes.addFlashAttribute(MESSAGE, "Team status is invalid"); break; case TEAM_NOT_FOUND_EXCEPTION: log.warn("Approve team: Team {} not found", teamId); redirectAttributes.addFlashAttribute(MESSAGE, "Team does not exist"); break; case DETERLAB_OPERATION_FAILED_EXCEPTION: log.warn("Approve team: Team {} fail", teamId); redirectAttributes.addFlashAttribute(MESSAGE, "Approve team request fail on Deterlab"); break; default: log.warn("Approve team : sio or deterlab adapter connection error"); // possible sio or adapter connection fail redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD); break; } return "redirect:/admin"; } // http status code is OK, then need to check the response message String msg = new JSONObject(responseBody).getString("msg"); if ("approve project OK".equals(msg)) { log.info("Approve team {} OK", teamId); } else { log.warn("Approve team {} FAIL", teamId); redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD); } return "redirect:/admin"; } @RequestMapping("/admin/teams/reject/{teamId}/{teamOwnerId}") public String rejectTeam( @PathVariable String teamId, @PathVariable String teamOwnerId, final RedirectAttributes redirectAttributes, HttpSession session ) throws WebServiceRuntimeException { if (!validateIfAdmin(session)) { return NO_PERMISSION_PAGE; } //FIXME require approver info log.info("Rejecting new team {}, team owner {}", teamId, teamOwnerId); HttpEntity<String> request = createHttpEntityHeaderOnly(); restTemplate.setErrorHandler(new MyResponseErrorHandler()); ResponseEntity response = restTemplate.exchange( properties.getApproveTeam(teamId, teamOwnerId, TeamStatus.REJECTED), HttpMethod.POST, request, String.class); String responseBody = response.getBody().toString(); if (RestUtil.isError(response.getStatusCode())) { MyErrorResource error; try { error = objectMapper.readValue(responseBody, MyErrorResource.class); } catch (IOException e) { throw new WebServiceRuntimeException(e.getMessage()); } ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError()); switch (exceptionState) { case TEAM_ID_NULL_OR_EMPTY_EXCEPTION: log.warn("Reject team: TeamId cannot be null or empty: {}", teamId); redirectAttributes.addFlashAttribute(MESSAGE, "TeamId cannot be null or empty"); break; case USER_ID_NULL_OR_EMPTY_EXCEPTION: log.warn("Reject team: UserId cannot be null or empty: {}", teamOwnerId); redirectAttributes.addFlashAttribute(MESSAGE, "UserId cannot be null or empty"); break; case INVALID_TEAM_STATUS_EXCEPTION: log.warn("Reject team: TeamStatus is invalid"); redirectAttributes.addFlashAttribute(MESSAGE, "Team status is invalid"); break; case TEAM_NOT_FOUND_EXCEPTION: log.warn("Reject team: Team {} not found", teamId); redirectAttributes.addFlashAttribute(MESSAGE, "Team does not exist"); break; case DETERLAB_OPERATION_FAILED_EXCEPTION: log.warn("Reject team: Team {} fail", teamId); redirectAttributes.addFlashAttribute(MESSAGE, "Reject team request fail on Deterlab"); break; default: log.warn("Reject team : sio or deterlab adapter connection error"); // possible sio or adapter connection fail redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD); break; } return "redirect:/admin"; } // http status code is OK, then need to check the response message String msg = new JSONObject(responseBody).getString("msg"); if ("reject project OK".equals(msg)) { log.info("Reject team {} OK", teamId); } else { log.warn("Reject team {} FAIL", teamId); redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD); } return "redirect:/admin"; } @RequestMapping("/admin/teams/{teamId}") public String setupTeamRestriction( @PathVariable final String teamId, @RequestParam(value = "action", required=true) final String action, final RedirectAttributes redirectAttributes, HttpSession session) throws IOException { final String logMessage = "Updating restriction settings for team {}: {}"; // check if admin if (!validateIfAdmin(session)) { log.warn(logMessage, teamId, PERMISSION_DENIED); return NO_PERMISSION_PAGE; } Team2 team = invokeAndExtractTeamInfo(teamId); // check if team is approved before restricted if ("restrict".equals(action) && team.getStatus().equals(TeamStatus.APPROVED.name())) { return restrictTeam(team, redirectAttributes); } // check if team is restricted before freeing it back to approved else if ("free".equals(action) && team.getStatus().equals(TeamStatus.RESTRICTED.name())) { return freeTeam(team, redirectAttributes); } else { log.warn(logMessage, teamId, "Cannot " + action + " team with status " + team.getStatus()); redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + "Cannot " + action + " team " + team.getName() + " with status " + team.getStatus()); return "redirect:/admin"; } } private String restrictTeam(final Team2 team, RedirectAttributes redirectAttributes) throws IOException { log.info("Restricting team {}", team.getId()); HttpEntity<String> request = createHttpEntityHeaderOnly(); ResponseEntity response = restTemplate.exchange( properties.getSioTeamsStatusUrl(team.getId(), TeamStatus.RESTRICTED), HttpMethod.PUT, request, String.class); String responseBody = response.getBody().toString(); if (RestUtil.isError(response.getStatusCode())) { MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class); ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError()); String logMessage = "Failed to restrict team {}: {}"; switch (exceptionState) { case TEAM_NOT_FOUND_EXCEPTION: log.warn(logMessage, team.getId(), TEAM_NOT_FOUND); redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + TEAM_NOT_FOUND); break; case INVALID_STATUS_TRANSITION_EXCEPTION: log.warn(logMessage, team.getId(), error.getMessage()); redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + error.getMessage()); break; case INVALID_TEAM_STATUS_EXCEPTION: log.warn(logMessage, team.getId(), error.getMessage()); redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + error.getMessage()); break; case FORBIDDEN_EXCEPTION: log.warn(logMessage, team.getId(), PERMISSION_DENIED); redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + PERMISSION_DENIED); break; default: log.warn(logMessage, team.getId(), exceptionState.getExceptionName()); redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD); } return "redirect:/admin"; } else { // good log.info("Team {} has been restricted", team.getId()); redirectAttributes.addFlashAttribute(MESSAGE_SUCCESS, "Team " + team.getName() + " status has been changed to " + TeamStatus.RESTRICTED.name()); return "redirect:/admin"; } } private String freeTeam(final Team2 team, RedirectAttributes redirectAttributes) throws IOException { log.info("Freeing team {}", team.getId()); HttpEntity<String> request = createHttpEntityHeaderOnly(); ResponseEntity response = restTemplate.exchange( properties.getSioTeamsStatusUrl(team.getId(), TeamStatus.APPROVED), HttpMethod.PUT, request, String.class); String responseBody = response.getBody().toString(); if (RestUtil.isError(response.getStatusCode())) { MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class); ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError()); String logMessage = "Failed to free team {}: {}"; switch (exceptionState) { case TEAM_NOT_FOUND_EXCEPTION: log.warn(logMessage, team.getId(), TEAM_NOT_FOUND); redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + TEAM_NOT_FOUND); break; case INVALID_STATUS_TRANSITION_EXCEPTION: log.warn(logMessage, team.getId(), error.getMessage()); redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + error.getMessage()); break; case INVALID_TEAM_STATUS_EXCEPTION: log.warn(logMessage, team.getId(), error.getMessage()); redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + error.getMessage()); break; case FORBIDDEN_EXCEPTION: log.warn(logMessage, team.getId(), PERMISSION_DENIED); redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + PERMISSION_DENIED); break; default: log.warn(logMessage, team.getId(), exceptionState.getExceptionName()); redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD); } return "redirect:/admin"; } else { // good log.info("Team {} has been freed", team.getId()); redirectAttributes.addFlashAttribute(MESSAGE_SUCCESS, "Team " + team.getName() + " status has been changed to " + TeamStatus.APPROVED.name()); return "redirect:/admin"; } } @RequestMapping("/admin/users/{userId}") public String freezeUnfreezeUsers( @PathVariable final String userId, @RequestParam(value = "action", required = true) final String action, final RedirectAttributes redirectAttributes, HttpSession session) throws IOException { User2 user = invokeAndExtractUserInfo(userId); // check if admin if (!validateIfAdmin(session)) { log.warn("Access denied when trying to freeze/unfreeze user {}: must be admin!", userId); return NO_PERMISSION_PAGE; } // check if user status is approved before freeze if ("freeze".equals(action) && user.getStatus().equals(UserStatus.APPROVED.toString())) { return freezeUser(user, redirectAttributes); } // check if user status is frozen before unfreeze else if ("unfreeze".equals(action) && user.getStatus().equals(UserStatus.FROZEN.toString())) { return unfreezeUser(user, redirectAttributes); } else { log.warn("Error in freeze/unfreeze user {}: failed to {} user with status {}", userId, action, user.getStatus()); redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + "failed to " + action + " user " + user.getEmail() + " with status " + user.getStatus()); return "redirect:/admin"; } } private String freezeUser(final User2 user, RedirectAttributes redirectAttributes) throws IOException { log.info("Freezing user {}, email {}", user.getId(), user.getEmail()); HttpEntity<String> request = createHttpEntityHeaderOnly(); ResponseEntity response = restTemplate.exchange( properties.getSioUsersStatusUrl(user.getId(), UserStatus.FROZEN.toString()), HttpMethod.PUT, request, String.class); String responseBody = response.getBody().toString(); if (RestUtil.isError(response.getStatusCode())) { MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class); ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError()); switch (exceptionState) { case USER_NOT_FOUND_EXCEPTION: log.warn("Failed to freeze user {}: user not found", user.getId()); redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + " user " + user.getEmail() + " not found."); break; case INVALID_STATUS_TRANSITION_EXCEPTION: log.warn("Failed to freeze user {}: invalid status transition {}", user.getId(), error.getMessage()); redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + error.getMessage() + " is not allowed."); break; case INVALID_USER_STATUS_EXCEPTION: log.warn("Failed to freeze user {}: invalid user status {}", user.getId(), error.getMessage()); redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + error.getMessage() + " is not a valid status."); break; case FORBIDDEN_EXCEPTION: log.warn("Failed to freeze user {}: must be an Admin", user.getId()); redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + " permission denied."); break; default: log.warn("Failed to freeze user {}: {}", user.getId(), exceptionState.getExceptionName()); redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD); break; } return "redirect:/admin"; } else { // good log.info("User {} has been frozen", user.getId()); redirectAttributes.addFlashAttribute(MESSAGE_SUCCESS, "User " + user.getEmail() + " has been banned."); return "redirect:/admin"; } } private String unfreezeUser(final User2 user, RedirectAttributes redirectAttributes) throws IOException { log.info("Unfreezing user {}, email {}", user.getId(), user.getEmail()); HttpEntity<String> request = createHttpEntityHeaderOnly(); ResponseEntity response = restTemplate.exchange( properties.getSioUsersStatusUrl(user.getId(), UserStatus.APPROVED.toString()), HttpMethod.PUT, request, String.class); String responseBody = response.getBody().toString(); if (RestUtil.isError(response.getStatusCode())) { MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class); ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError()); switch (exceptionState) { case USER_NOT_FOUND_EXCEPTION: log.warn("Failed to unfreeze user {}: user not found", user.getId()); redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + " user " + user.getEmail() + " not found."); break; case INVALID_STATUS_TRANSITION_EXCEPTION: log.warn("Failed to unfreeze user {}: invalid status transition {}", user.getId(), error.getMessage()); redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + error.getMessage() + " is not allowed."); break; case INVALID_USER_STATUS_EXCEPTION: log.warn("Failed to unfreeze user {}: invalid user status {}", user.getId(), error.getMessage()); redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + error.getMessage() + " is not a valid status."); break; case FORBIDDEN_EXCEPTION: log.warn("Failed to unfreeze user {}: must be an Admin", user.getId()); redirectAttributes.addFlashAttribute(MESSAGE, ERROR_PREFIX + " permission denied."); break; default: log.warn("Failed to unfreeze user {}: {}", user.getId(), exceptionState.getExceptionName()); redirectAttributes.addFlashAttribute(MESSAGE, ERR_SERVER_OVERLOAD); break; } return "redirect:/admin"; } else { // good log.info("User {} has been unfrozen", user.getId()); redirectAttributes.addFlashAttribute(MESSAGE_SUCCESS, "User " + user.getEmail() + " has been unbanned."); return "redirect:/admin"; } } // @RequestMapping("/admin/experiments/remove/{expId}") // public String adminRemoveExp(@PathVariable Integer expId) { // int teamId = experimentManager.getExperimentByExpId(expId).getTeamId(); // experimentManager.adminRemoveExperiment(expId); // // // decrease exp count to be display on Teams page // teamManager.decrementExperimentCount(teamId); // return "redirect:/admin"; // } // @RequestMapping(value="/admin/data/contribute", method=RequestMethod.GET) // public String adminContributeDataset(Model model) { // model.addAttribute("dataset", new Dataset()); // // File rootFolder = new File(App.ROOT); // List<String> fileNames = Arrays.stream(rootFolder.listFiles()) // .map(f -> f.getError()) // .collect(Collectors.toList()); // // model.addAttribute("files", // Arrays.stream(rootFolder.listFiles()) // .sorted(Comparator.comparingLong(f -> -1 * f.lastModified())) // .map(f -> f.getError()) // .collect(Collectors.toList()) // ); // // return "admin_contribute_data"; // } // @RequestMapping(value="/admin/data/contribute", method=RequestMethod.POST) // public String validateAdminContributeDataset(@ModelAttribute("dataset") Dataset dataset, HttpSession session, @RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes) throws IOException { // BufferedOutputStream stream = null; // FileOutputStream fileOutputStream = null; // // TODO // // validation // // get file from user upload to server // if (!file.isEmpty()) { // try { // String fileName = getSessionIdOfLoggedInUser(session) + "-" + file.getOriginalFilename(); // fileOutputStream = new FileOutputStream(new File(App.ROOT + "/" + fileName)); // stream = new BufferedOutputStream(fileOutputStream); // FileCopyUtils.copy(file.getInputStream(), stream); // redirectAttributes.addFlashAttribute(MESSAGE, // "You successfully uploaded " + file.getOriginalFilename() + "!"); // datasetManager.addDataset(getSessionIdOfLoggedInUser(session), dataset, file.getOriginalFilename()); // } // catch (Exception e) { // redirectAttributes.addFlashAttribute(MESSAGE, // "You failed to upload " + file.getOriginalFilename() + " => " + e.getMessage()); // } finally { // if (stream != null) { // stream.close(); // } // if (fileOutputStream != null) { // fileOutputStream.close(); // } // } // } // else { // redirectAttributes.addFlashAttribute(MESSAGE, // "You failed to upload " + file.getOriginalFilename() + " because the file was empty"); // } // return "redirect:/admin"; // } // @RequestMapping("/admin/data/remove/{datasetId}") // public String adminRemoveDataset(@PathVariable Integer datasetId) { // datasetManager.removeDataset(datasetId); // return "redirect:/admin"; // } // @RequestMapping(value="/admin/node/add", method=RequestMethod.GET) // public String adminAddNode(Model model) { // model.addAttribute("node", new Node()); // return "admin_add_node"; // } // @RequestMapping(value="/admin/node/add", method=RequestMethod.POST) // public String adminAddNode(@ModelAttribute("node") Node node) { // // TODO // // validate fields, eg should be integer // nodeManager.addNode(node); // return "redirect:/admin"; // } //--------------------------Static pages for teams-------------------------- @RequestMapping("/teams/team_application_submitted") public String teamAppSubmitFromTeamsPage() { return "team_page_application_submitted"; } @RequestMapping("/teams/join_application_submitted/{teamName}") public String teamAppJoinFromTeamsPage(@PathVariable String teamName, Model model) throws WebServiceRuntimeException { log.info("Redirecting to join application submitted page"); HttpEntity<String> request = createHttpEntityHeaderOnly(); restTemplate.setErrorHandler(new MyResponseErrorHandler()); ResponseEntity response = restTemplate.exchange(properties.getTeamByName(teamName), HttpMethod.GET, request, String.class); String responseBody = response.getBody().toString(); try { if (RestUtil.isError(response.getStatusCode())) { MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class); ExceptionState exceptionState = ExceptionState.parseExceptionState(error.getError()); switch (exceptionState) { case TEAM_NOT_FOUND_EXCEPTION: log.warn("submitted join team request : team name error"); break; default: log.warn("submitted join team request : some other failure"); // possible sio or adapter connection fail break; } return "redirect:/teams/join_team"; } } catch (IOException e) { throw new WebServiceRuntimeException(e.getMessage()); } Team2 one = extractTeamInfo(responseBody); model.addAttribute("team", one); return "team_page_join_application_submitted"; } //--------------------------Static pages for sign up-------------------------- @RequestMapping("/team_application_submitted") public String teamAppSubmit() { return "team_application_submitted"; } /** * A page to show new users has successfully registered to apply to join an existing team * The page contains the team owner information which the users requested to join * * @param model The model which is passed from signup * @return A success page otherwise an error page if the user tries to access this page directly */ @RequestMapping("/join_application_submitted") public String joinTeamAppSubmit(Model model) { // model attribute should be passed from /signup2 // team is required to display the team owner details if (model.containsAttribute("team")) { return "join_team_application_submitted"; } return "error"; } @RequestMapping("/email_not_validated") public String emailNotValidated() { return "email_not_validated"; } @RequestMapping("/team_application_under_review") public String teamAppUnderReview() { return "team_application_under_review"; } // model attribute name come from /login @RequestMapping("/email_checklist") public String emailChecklist(@ModelAttribute("statuschecklist") String status) { return "email_checklist"; } @RequestMapping("/join_application_awaiting_approval") public String joinTeamAppAwaitingApproval(Model model) { model.addAttribute("loginForm", new LoginForm()); model.addAttribute("signUpMergedForm", new SignUpMergedForm()); return "join_team_application_awaiting_approval"; } //--------------------------Get List of scenarios filenames-------------------------- private List<String> getScenarioFileNameList() throws WebServiceRuntimeException { log.info("Retrieving scenario file names"); // List<String> scenarioFileNameList = null; // try { // scenarioFileNameList = IOUtils.readLines(getClass().getClassLoader().getResourceAsStream("scenarios"), StandardCharsets.UTF_8); // } catch (IOException e) { // throw new WebServiceRuntimeException(e.getMessage()); // } // File folder = null; // try { // folder = new ClassPathResource("scenarios").getFile(); // } catch (IOException e) { // throw new WebServiceRuntimeException(e.getMessage()); // } // List<String> scenarioFileNameList = new ArrayList<>(); // File[] files = folder.listFiles(); // for (File file : files) { // if (file.isFile()) { // scenarioFileNameList.add(file.getError()); // } // } // FIXME: hardcode list of filenames for now List<String> scenarioFileNameList = new ArrayList<>(); scenarioFileNameList.add("Scenario 1 - Experiment with a single node"); scenarioFileNameList.add("Scenario 2 - Experiment with 2 nodes and 10Gb link"); scenarioFileNameList.add("Scenario 3 - Experiment with 3 nodes in a LAN"); scenarioFileNameList.add("Scenario 4 - Experiment with 2 nodes and customized link property"); // scenarioFileNameList.add("Scenario 4 - Two nodes linked with a 10Gbps SDN switch"); // scenarioFileNameList.add("Scenario 5 - Three nodes with Blockchain capabilities"); log.info("Scenario file list: {}", scenarioFileNameList); return scenarioFileNameList; } private String getScenarioContentsFromFile(String scenarioFileName) throws WebServiceRuntimeException { // FIXME: switch to better way of referencing scenario descriptions to actual filenames String actualScenarioFileName; if (scenarioFileName.contains("Scenario 1")) { actualScenarioFileName = "basic1.ns"; } else if (scenarioFileName.contains("Scenario 2")) { actualScenarioFileName = "basic2.ns"; } else if (scenarioFileName.contains("Scenario 3")) { actualScenarioFileName = "basic3.ns"; } else if (scenarioFileName.contains("Scenario 4")) { actualScenarioFileName = "basic4.ns"; } else { // defaults to basic single node actualScenarioFileName = "basic1.ns"; } try { log.info("Retrieving scenario files {}", getClass().getClassLoader().getResourceAsStream("scenarios/" + actualScenarioFileName)); List<String> lines = IOUtils.readLines(getClass().getClassLoader().getResourceAsStream("scenarios/" + actualScenarioFileName), StandardCharsets.UTF_8); StringBuilder sb = new StringBuilder(); for (String line : lines) { sb.append(line); sb.append(System.getProperty("line.separator")); } log.info("Experiment ns file contents: {}", sb); return sb.toString(); } catch (IOException e) { throw new WebServiceRuntimeException(e.getMessage()); } } //---Check if user is a team owner and has any join request waiting for approval---- private boolean hasAnyJoinRequest(HashMap<Integer, Team> teamMapOwnedByUser) { for (Map.Entry<Integer, Team> entry : teamMapOwnedByUser.entrySet()) { Team currTeam = entry.getValue(); if (currTeam.isUserJoinRequestEmpty() == false) { // at least one team has join user request return true; } } // loop through all teams but never return a single true // therefore, user's controlled teams has no join request return false; } //--------------------------MISC-------------------------- private int getSessionIdOfLoggedInUser(HttpSession session) { return Integer.parseInt(session.getAttribute(SESSION_LOGGED_IN_USER_ID).toString()); } private User2 extractUserInfo(String userJson) { User2 user2 = new User2(); if (userJson == null) { // return empty user return user2; } JSONObject object = new JSONObject(userJson); JSONObject userDetails = object.getJSONObject("userDetails"); JSONObject address = userDetails.getJSONObject("address"); user2.setId(object.getString("id")); user2.setFirstName(getJSONStr(userDetails.getString("firstName"))); user2.setLastName(getJSONStr(userDetails.getString("lastName"))); user2.setJobTitle(userDetails.getString("jobTitle")); user2.setEmail(userDetails.getString("email")); user2.setPhone(userDetails.getString("phone")); user2.setAddress1(address.getString("address1")); user2.setAddress2(address.getString("address2")); user2.setCountry(address.getString("country")); user2.setRegion(address.getString("region")); user2.setPostalCode(address.getString("zipCode")); user2.setCity(address.getString("city")); user2.setInstitution(userDetails.getString("institution")); user2.setInstitutionAbbreviation(userDetails.getString("institutionAbbreviation")); user2.setInstitutionWeb(userDetails.getString("institutionWeb")); user2.setStatus(object.getString("status")); user2.setEmailVerified(object.getBoolean("emailVerified")); return user2; } private Team2 extractTeamInfo(String json) { Team2 team2 = new Team2(); JSONObject object = new JSONObject(json); JSONArray membersArray = object.getJSONArray("members"); try { team2.setCreatedDate(formatZonedDateTime(object.get("applicationDate").toString())); } catch (Exception e) { log.warn("Error getting team application date {}", e); team2.setCreatedDate(UNKNOWN); } team2.setId(object.getString("id")); team2.setName(object.getString("name")); team2.setDescription(object.getString("description")); team2.setWebsite(object.getString("website")); team2.setOrganisationType(object.getString("organisationType")); team2.setStatus(object.getString("status")); team2.setVisibility(object.getString("visibility")); for (int i = 0; i < membersArray.length(); i++) { JSONObject memberObject = membersArray.getJSONObject(i); String userId = memberObject.getString("userId"); String teamMemberType = memberObject.getString("memberType"); String teamMemberStatus = memberObject.getString("memberStatus"); User2 myUser = invokeAndExtractUserInfo(userId); if (teamMemberType.equals(MemberType.MEMBER.toString())) { team2.addMembers(myUser); // add to pending members list for Members Awaiting Approval function if (teamMemberStatus.equals(MemberStatus.PENDING.toString())) { team2.addPendingMembers(myUser); } } else if (teamMemberType.equals(MemberType.OWNER.toString())) { // explicit safer check team2.setOwner(myUser); } } team2.setMembersCount(membersArray.length()); return team2; } // use to extract JSON Strings from services // in the case where the JSON Strings are null, return "Connection Error" private String getJSONStr(String jsonString) { if (jsonString == null || jsonString.isEmpty()) { return CONNECTION_ERROR; } return jsonString; } /** * Checks if user is pending for join request approval from team leader * Use for fixing bug for view experiment page where users previously can view the experiments just by issuing a join request * * @param json the response body after calling team service * @param loginUserId the current logged in user id * @return True if the user is anything but APPROVED, false otherwise */ private boolean isMemberJoinRequestPending(String loginUserId, String json) { if (json == null) { return true; } JSONObject object = new JSONObject(json); JSONArray membersArray = object.getJSONArray("members"); for (int i = 0; i < membersArray.length(); i++) { JSONObject memberObject = membersArray.getJSONObject(i); String userId = memberObject.getString("userId"); String teamMemberStatus = memberObject.getString("memberStatus"); if (userId.equals(loginUserId) && !teamMemberStatus.equals(MemberStatus.APPROVED.toString())) { return true; } } log.info("User: {} is viewing experiment page", loginUserId); return false; } private Team2 extractTeamInfoUserJoinRequest(String userId, String json) { Team2 team2 = new Team2(); JSONObject object = new JSONObject(json); JSONArray membersArray = object.getJSONArray("members"); for (int i = 0; i < membersArray.length(); i++) { JSONObject memberObject = membersArray.getJSONObject(i); String uid = memberObject.getString("userId"); String teamMemberStatus = memberObject.getString("memberStatus"); if (uid.equals(userId) && teamMemberStatus.equals(MemberStatus.PENDING.toString())) { team2.setId(object.getString("id")); team2.setName(object.getString("name")); team2.setDescription(object.getString("description")); team2.setWebsite(object.getString("website")); team2.setOrganisationType(object.getString("organisationType")); team2.setStatus(object.getString("status")); team2.setVisibility(object.getString("visibility")); team2.setMembersCount(membersArray.length()); return team2; } } // no such member in the team found return null; } protected Dataset extractDataInfo(String json) { log.debug(json); JSONObject object = new JSONObject(json); Dataset dataset = new Dataset(); dataset.setId(object.getInt("id")); dataset.setName(object.getString("name")); dataset.setDescription(object.getString("description")); dataset.setContributorId(object.getString("contributorId")); dataset.addVisibility(object.getString("visibility")); dataset.addAccessibility(object.getString("accessibility")); try { dataset.setReleasedDate(getZonedDateTime(object.get("releasedDate").toString())); } catch (IOException e) { log.warn("Error getting released date {}", e); dataset.setReleasedDate(null); } dataset.setContributor(invokeAndExtractUserInfo(dataset.getContributorId())); JSONArray resources = object.getJSONArray("resources"); for (int i = 0; i < resources.length(); i++) { JSONObject resource = resources.getJSONObject(i); DataResource dataResource = new DataResource(); dataResource.setId(resource.getLong("id")); dataResource.setUri(resource.getString("uri")); dataset.addResource(dataResource); } JSONArray approvedUsers = object.getJSONArray("approvedUsers"); for (int i =0; i < approvedUsers.length(); i++) { dataset.addApprovedUser(approvedUsers.getString(0)); } return dataset; } protected User2 invokeAndExtractUserInfo(String userId) { HttpEntity<String> request = createHttpEntityHeaderOnlyNoAuthHeader(); ResponseEntity response; try { response = restTemplate.exchange(properties.getUser(userId), HttpMethod.GET, request, String.class); } catch (Exception e) { log.warn("User service not available to retrieve User: {}", userId); return new User2(); } return extractUserInfo(response.getBody().toString()); } private Team2 invokeAndExtractTeamInfo(String teamId) { HttpEntity<String> request = createHttpEntityHeaderOnly(); ResponseEntity responseEntity = restTemplate.exchange(properties.getTeamById(teamId), HttpMethod.GET, request, String.class); return extractTeamInfo(responseEntity.getBody().toString()); } private Experiment2 extractExperiment(String experimentJson) { Experiment2 experiment2 = new Experiment2(); JSONObject object = new JSONObject(experimentJson); experiment2.setId(object.getLong("id")); experiment2.setUserId(object.getString("userId")); experiment2.setTeamId(object.getString("teamId")); experiment2.setTeamName(object.getString(TEAM_NAME)); experiment2.setName(object.getString("name")); experiment2.setDescription(object.getString("description")); experiment2.setNsFile(object.getString("nsFile")); experiment2.setNsFileContent(object.getString("nsFileContent")); experiment2.setIdleSwap(object.getInt("idleSwap")); experiment2.setMaxDuration(object.getInt("maxDuration")); return experiment2; } private Realization invokeAndExtractRealization(String teamName, Long id) { HttpEntity<String> request = createHttpEntityHeaderOnly(); restTemplate.setErrorHandler(new MyResponseErrorHandler()); ResponseEntity response = null; try { log.info("retrieving the latest exp status: {}", properties.getRealizationByTeam(teamName, id.toString())); response = restTemplate.exchange(properties.getRealizationByTeam(teamName, id.toString()), HttpMethod.GET, request, String.class); } catch (Exception e) { return getCleanRealization(); } String responseBody; if (response.getBody() == null) { return getCleanRealization(); } else { responseBody = response.getBody().toString(); } try { if (RestUtil.isError(response.getStatusCode())) { MyErrorResource error = objectMapper.readValue(responseBody, MyErrorResource.class); log.warn("error in retrieving realization for team: {}, realization: {}", teamName, id); return getCleanRealization(); } else { return extractRealization(responseBody); } } catch (IOException e) { return getCleanRealization(); } } private Realization extractRealization(String json) { log.info("extracting realization: {}", json); Realization realization = new Realization(); JSONObject object = new JSONObject(json); realization.setExperimentId(object.getLong("experimentId")); realization.setExperimentName(object.getString("experimentName")); realization.setUserId(object.getString("userId")); realization.setTeamId(object.getString("teamId")); realization.setState(object.getString("state")); String exp_report = ""; Object expDetailsObject = object.get("details"); log.info("exp detail object: {}", expDetailsObject); if (expDetailsObject == JSONObject.NULL || expDetailsObject.toString().isEmpty()) { log.info("set details empty"); realization.setDetails(""); realization.setNumberOfNodes(0); } else { log.info("exp report to string: {}", expDetailsObject.toString()); exp_report = expDetailsObject.toString(); realization.setDetails(exp_report); JSONObject nodesInfoObject = new JSONObject(expDetailsObject.toString()); for (Object key : nodesInfoObject.keySet()) { Map<String, String> nodeDetails = new HashMap<>(); String nodeName = (String) key; JSONObject nodeDetailsJson = new JSONObject(nodesInfoObject.get(nodeName).toString()); nodeDetails.put("os", nodeDetailsJson.getString("os")); nodeDetails.put("qualifiedName", nodeDetailsJson.getString("qualifiedName")); nodeDetails.put(NODE_ID, nodeDetailsJson.getString(NODE_ID)); realization.addNodeDetails(nodeName, nodeDetails); } log.info("nodes info object: {}", nodesInfoObject); realization.setNumberOfNodes(nodesInfoObject.keySet().size()); } return realization; } /** * @param zonedDateTimeJSON JSON string * @return a date in the format MMM-d-yyyy */ protected String formatZonedDateTime(String zonedDateTimeJSON) throws Exception { ZonedDateTime zonedDateTime = getZonedDateTime(zonedDateTimeJSON); DateTimeFormatter format = DateTimeFormatter.ofPattern("MMM-d-yyyy"); return zonedDateTime.format(format); } protected ZonedDateTime getZonedDateTime(String zonedDateTimeJSON) throws IOException { ObjectMapper mapper = new ObjectMapper(); mapper.registerModule(new JavaTimeModule()); return mapper.readValue(zonedDateTimeJSON, ZonedDateTime.class); } /** * Creates a HttpEntity with a request body and header but no authorization header * To solve the expired jwt token * * @param jsonString The JSON request converted to string * @return A HttpEntity request * @see HttpEntity createHttpEntityHeaderOnly() for request with only header */ protected HttpEntity<String> createHttpEntityWithBodyNoAuthHeader(String jsonString) { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); return new HttpEntity<>(jsonString, headers); } /** * Creates a HttpEntity that contains only a header and empty body but no authorization header * To solve the expired jwt token * * @return A HttpEntity request * @see HttpEntity createHttpEntityWithBody() for request with both body and header */ protected HttpEntity<String> createHttpEntityHeaderOnlyNoAuthHeader() { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); return new HttpEntity<>(headers); } /** * Creates a HttpEntity with a request body and header * * @param jsonString The JSON request converted to string * @return A HttpEntity request * @implNote Authorization header must be set to the JwTToken in the format [Bearer: TOKEN_ID] * @see HttpEntity createHttpEntityHeaderOnly() for request with only header */ protected HttpEntity<String> createHttpEntityWithBody(String jsonString) { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); headers.set("Authorization", httpScopedSession.getAttribute(webProperties.getSessionJwtToken()).toString()); return new HttpEntity<>(jsonString, headers); } /** * Creates a HttpEntity that contains only a header and empty body * * @return A HttpEntity request * @implNote Authorization header must be set to the JwTToken in the format [Bearer: TOKEN_ID] * @see HttpEntity createHttpEntityWithBody() for request with both body and header */ protected HttpEntity<String> createHttpEntityHeaderOnly() { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); headers.set("Authorization", httpScopedSession.getAttribute(webProperties.getSessionJwtToken()).toString()); return new HttpEntity<>(headers); } private void setSessionVariables(HttpSession session, String loginEmail, String id, String firstName, String userRoles, String token) { User2 user = invokeAndExtractUserInfo(id); session.setAttribute(webProperties.getSessionEmail(), loginEmail); session.setAttribute(webProperties.getSessionUserId(), id); session.setAttribute(webProperties.getSessionUserFirstName(), firstName); session.setAttribute(webProperties.getSessionRoles(), userRoles); session.setAttribute(webProperties.getSessionJwtToken(), "Bearer " + token); log.info("Session variables - sessionLoggedEmail: {}, id: {}, name: {}, roles: {}, token: {}", loginEmail, id, user.getFirstName(), userRoles, token); } private void removeSessionVariables(HttpSession session) { log.info("removing session variables: email: {}, userid: {}, user first name: {}", session.getAttribute(webProperties.getSessionEmail()), session.getAttribute(webProperties.getSessionUserId()), session.getAttribute(webProperties.getSessionUserFirstName())); session.removeAttribute(webProperties.getSessionEmail()); session.removeAttribute(webProperties.getSessionUserId()); session.removeAttribute(webProperties.getSessionUserFirstName()); session.removeAttribute(webProperties.getSessionRoles()); session.removeAttribute(webProperties.getSessionJwtToken()); session.invalidate(); } protected boolean validateIfAdmin(HttpSession session) { //log.info("User: {} is logged on as: {}", session.getAttribute(webProperties.getSessionEmail()), session.getAttribute(webProperties.getSessionRoles())); return session.getAttribute(webProperties.getSessionRoles()).equals(UserType.ADMIN.toString()); } /** * Ensure that only users of the team can realize or un-realize experiment * A pre-condition is that the users must be approved. * Teams must also be approved. * * @return the main experiment page */ private boolean checkPermissionRealizeExperiment(Realization realization, HttpSession session) { // get list of teamids HttpEntity<String> request = createHttpEntityHeaderOnly(); ResponseEntity userRespEntity = restTemplate.exchange(properties.getUser(session.getAttribute("id").toString()), HttpMethod.GET, request, String.class); JSONObject object = new JSONObject(userRespEntity.getBody().toString()); JSONArray teamIdsJsonArray = object.getJSONArray("teams"); for (int i = 0; i < teamIdsJsonArray.length(); i++) { String teamId = teamIdsJsonArray.get(i).toString(); if (teamId.equals(realization.getTeamId())) { return true; } } return false; } private String getTeamStatus(String teamId) { Team2 team = invokeAndExtractTeamInfo(teamId); return team.getStatus(); } private Realization getCleanRealization() { Realization realization = new Realization(); realization.setExperimentId(0L); realization.setExperimentName(""); realization.setUserId(""); realization.setTeamId(""); realization.setState(RealizationState.ERROR.toString()); realization.setDetails(""); realization.setNumberOfNodes(0); return realization; } /** * Computes the number of teams that the user is in and the number of running experiments to populate data for the user dashboard * * @return a map in the form teams: numberOfTeams, experiments: numberOfExperiments */ private Map<String, Integer> getUserDashboardStats(String userId) { int numberOfRunningExperiments = 0; Map<String, Integer> userDashboardStats = new HashMap<>(); // get list of teamids HttpEntity<String> request = createHttpEntityHeaderOnly(); ResponseEntity userRespEntity = restTemplate.exchange(properties.getUser(userId), HttpMethod.GET, request, String.class); JSONObject object = new JSONObject(userRespEntity.getBody().toString()); JSONArray teamIdsJsonArray = object.getJSONArray("teams"); for (int i = 0; i < teamIdsJsonArray.length(); i++) { String teamId = teamIdsJsonArray.get(i).toString(); HttpEntity<String> teamRequest = createHttpEntityHeaderOnly(); ResponseEntity teamResponse = restTemplate.exchange(properties.getTeamById(teamId), HttpMethod.GET, teamRequest, String.class); String teamResponseBody = teamResponse.getBody().toString(); if (!isMemberJoinRequestPending(userId, teamResponseBody)) { // get experiments lists of the teams HttpEntity<String> expRequest = createHttpEntityHeaderOnly(); ResponseEntity expRespEntity = restTemplate.exchange(properties.getExpListByTeamId(teamId), HttpMethod.GET, expRequest, String.class); JSONArray experimentsArray = new JSONArray(expRespEntity.getBody().toString()); numberOfRunningExperiments = getNumberOfRunningExperiments(numberOfRunningExperiments, experimentsArray); } } userDashboardStats.put(USER_DASHBOARD_TEAMS, teamIdsJsonArray.length()); userDashboardStats.put(USER_DASHBOARD_RUNNING_EXPERIMENTS, numberOfRunningExperiments); userDashboardStats.put(USER_DASHBOARD_FREE_NODES, getNumberOfFreeNodes()); return userDashboardStats; } private int getNumberOfRunningExperiments(int numberOfRunningExperiments, JSONArray experimentsArray) { for (int k = 0; k < experimentsArray.length(); k++) { Experiment2 experiment2 = extractExperiment(experimentsArray.getJSONObject(k).toString()); Realization realization = invokeAndExtractRealization(experiment2.getTeamName(), experiment2.getId()); if (realization.getState().equals(RealizationState.RUNNING.toString())) { numberOfRunningExperiments++; } } return numberOfRunningExperiments; } private int getNumberOfFreeNodes() { String freeNodes; log.info("Retrieving number of free nodes from: {}", properties.getFreeNodes()); try { String jsonResult = restTemplate.getForObject(properties.getFreeNodes(), String.class); JSONObject object = new JSONObject(jsonResult); freeNodes = object.getString("numberOfFreeNodes"); } catch (RestClientException e) { log.warn("Error connecting to service-telemetry: {}", e); freeNodes = "0"; } return Integer.parseInt(freeNodes); } private List<TeamUsageInfo> getTeamsUsageStatisticsForUser(String userId) { List<TeamUsageInfo> usageInfoList = new ArrayList<>(); // get list of teamids HttpEntity<String> request = createHttpEntityHeaderOnly(); ResponseEntity userRespEntity = restTemplate.exchange(properties.getUser(userId), HttpMethod.GET, request, String.class); JSONObject object = new JSONObject(userRespEntity.getBody().toString()); JSONArray teamIdsJsonArray = object.getJSONArray("teams"); // get team info by team id for (int i = 0; i < teamIdsJsonArray.length(); i++) { String teamId = teamIdsJsonArray.get(i).toString(); HttpEntity<String> teamRequest = createHttpEntityHeaderOnly(); ResponseEntity teamResponse = restTemplate.exchange(properties.getTeamById(teamId), HttpMethod.GET, teamRequest, String.class); String teamResponseBody = teamResponse.getBody().toString(); if (!isMemberJoinRequestPending(userId, teamResponseBody)) { TeamUsageInfo usageInfo = new TeamUsageInfo(); usageInfo.setId(teamId); usageInfo.setName(new JSONObject(teamResponseBody).getString("name")); usageInfo.setUsage(getUsageStatisticsByTeamId(teamId)); usageInfoList.add(usageInfo); } } return usageInfoList; } private String getUsageStatisticsByTeamId(String id) { log.info("Getting usage statistics for team {}", id); HttpEntity<String> request = createHttpEntityHeaderOnly(); ResponseEntity response; try { response = restTemplate.exchange(properties.getUsageStatisticsByTeamId(id), HttpMethod.GET, request, String.class); } catch (RestClientException e) { log.warn("Error connecting to sio get usage statistics {}", e); return "?"; } return response.getBody().toString(); } }
DEV-863 fix sonar errors
src/main/java/sg/ncl/MainController.java
DEV-863 fix sonar errors
Java
apache-2.0
0ca5650d5071035b0e6fbf668a4e5d6ab463d5a7
0
Hurence/log-island,Hurence/log-island
/** * Copyright (C) 2016 Hurence ([email protected]) * * 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.hurence.logisland.service.elasticsearch; import com.hurence.logisland.classloading.PluginProxy; import com.hurence.logisland.component.InitializationException; import com.hurence.logisland.component.PropertyDescriptor; import com.hurence.logisland.controller.ControllerServiceInitializationContext; import com.hurence.logisland.processor.ProcessException; import com.hurence.logisland.record.FieldType; import com.hurence.logisland.record.Record; import com.hurence.logisland.record.StandardRecord; import com.hurence.logisland.service.datastore.InvalidMultiGetQueryRecordException; import com.hurence.logisland.service.datastore.MultiGetQueryRecord; import com.hurence.logisland.service.datastore.MultiGetResponseRecord; import com.hurence.logisland.util.runner.TestRunner; import com.hurence.logisland.util.runner.TestRunners; import org.elasticsearch.action.ActionListener; import org.elasticsearch.action.admin.cluster.health.ClusterHealthRequest; import org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse; import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest; import org.elasticsearch.action.admin.indices.get.GetIndexRequest; import org.elasticsearch.action.bulk.BulkItemResponse; import org.elasticsearch.action.bulk.BulkProcessor; import org.elasticsearch.action.bulk.BulkRequest; import org.elasticsearch.action.bulk.BulkResponse; import org.elasticsearch.client.RequestOptions; import org.elasticsearch.cluster.metadata.IndexMetaData; import org.elasticsearch.common.unit.ByteSizeUnit; import org.elasticsearch.common.unit.ByteSizeValue; import org.elasticsearch.common.unit.TimeValue; import org.junit.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.*; import java.util.function.BiConsumer; public class Elasticsearch_6_6_2_ClientServiceIT { private static final String MAPPING1 = "{'properties':{'name':{'type': 'text'},'val':{'type':'integer'}}}"; private static final String MAPPING2 = "{'properties':{'name':{'type': 'text'},'val':{'type': 'text'}}}"; private static final String MAPPING3 = "{'dynamic':'strict','properties':{'name':{'type': 'text'},'xyz':{'type': 'text'}}}"; private static Logger logger = LoggerFactory.getLogger(Elasticsearch_6_6_2_ClientServiceIT.class); @ClassRule public static final ESRule esRule = new ESRule(); @Before public void clean() throws IOException { ClusterHealthRequest clHealtRequest = new ClusterHealthRequest(); ClusterHealthResponse response = esRule.getClient().cluster().health(clHealtRequest, RequestOptions.DEFAULT); Set<String> indices = response.getIndices().keySet(); if (!indices.isEmpty()) { DeleteIndexRequest deleteRequest = new DeleteIndexRequest(indices.toArray(new String[0])); Assert.assertTrue(esRule.getClient().indices().delete(deleteRequest).isAcknowledged()); } } private class MockElasticsearchClientService extends Elasticsearch_6_6_2_ClientService { @Override protected void createElasticsearchClient(ControllerServiceInitializationContext context) throws ProcessException { if (esClient != null) { return; } esClient = esRule.getClient(); } @Override protected void createBulkProcessor(ControllerServiceInitializationContext context) { if (bulkProcessor != null) { return; } // create the bulk processor BulkProcessor.Listener listener = new BulkProcessor.Listener() { @Override public void beforeBulk(long l, BulkRequest bulkRequest) { getLogger().debug("Going to execute bulk [id:{}] composed of {} actions", new Object[]{l, bulkRequest.numberOfActions()}); } @Override public void afterBulk(long l, BulkRequest bulkRequest, BulkResponse bulkResponse) { getLogger().debug("Executed bulk [id:{}] composed of {} actions", new Object[]{l, bulkRequest.numberOfActions()}); if (bulkResponse.hasFailures()) { getLogger().warn("There was failures while executing bulk [id:{}]," + " done bulk request in {} ms with failure = {}", new Object[]{l, bulkResponse.getTook().getMillis(), bulkResponse.buildFailureMessage()}); for (BulkItemResponse item : bulkResponse.getItems()) { if (item.isFailed()) { errors.put(item.getId(), item.getFailureMessage()); } } } } @Override public void afterBulk(long l, BulkRequest bulkRequest, Throwable throwable) { getLogger().error("something went wrong while bulk loading events to es : {}", new Object[]{throwable.getMessage()}); } }; BiConsumer<BulkRequest, ActionListener<BulkResponse>> bulkConsumer = (request, bulkListener) -> esClient.bulkAsync(request, RequestOptions.DEFAULT, bulkListener); bulkProcessor = BulkProcessor.builder(bulkConsumer, listener) .setBulkActions(1000) .setBulkSize(new ByteSizeValue(10, ByteSizeUnit.MB)) .setFlushInterval(TimeValue.timeValueSeconds(1)) .setConcurrentRequests(2) //.setBackoffPolicy(getBackOffPolicy(context)) .build(); } @Override public List<PropertyDescriptor> getSupportedPropertyDescriptors() { List<PropertyDescriptor> props = new ArrayList<>(); return Collections.unmodifiableList(props); } } private ElasticsearchClientService configureElasticsearchClientService(final TestRunner runner) throws InitializationException { final MockElasticsearchClientService elasticsearchClientService = new MockElasticsearchClientService(); runner.addControllerService("elasticsearchClient", elasticsearchClientService); runner.enableControllerService(elasticsearchClientService); runner.setProperty(TestProcessor.ELASTICSEARCH_CLIENT_SERVICE, "elasticsearchClient"); runner.assertValid(elasticsearchClientService); // TODO : is this necessary ? final ElasticsearchClientService service = PluginProxy.unwrap(runner.getProcessContext().getPropertyValue(TestProcessor.ELASTICSEARCH_CLIENT_SERVICE).asControllerService()); return service; } @Test public void testBasics() throws Exception { Map<String, Object> document1 = new HashMap<>(); document1.put("name", "fred"); document1.put("val", 33); boolean result; final TestRunner runner = TestRunners.newTestRunner(new TestProcessor()); final ElasticsearchClientService elasticsearchClientService = configureElasticsearchClientService(runner); // Verify the index does not exist Assert.assertEquals(false, elasticsearchClientService.existsCollection("foo")); // Define the index elasticsearchClientService.createCollection("foo", 2, 1); Assert.assertEquals(true, elasticsearchClientService.existsCollection("foo")); // Define another index elasticsearchClientService.createCollection("bar", 2, 1); Assert.assertEquals(true, elasticsearchClientService.existsCollection("foo")); // Add a mapping to foo result = elasticsearchClientService.putMapping("foo", "type1", MAPPING1.replace('\'', '"')); Assert.assertEquals(true, result); // Add the same mapping again result = elasticsearchClientService.putMapping("foo", "type1", MAPPING1.replace('\'', '"')); Assert.assertEquals(true, result); // Update a mapping with an incompatible mapping -- should fail // result = elasticsearchClientService.putMapping("foo", "type2", MAPPING2.replace('\'', '"')); // Assert.assertEquals(false, result); // create alias elasticsearchClientService.createAlias("foo", "aliasFoo"); Assert.assertEquals(true, elasticsearchClientService.existsCollection("aliasFoo")); // Insert a record into foo and count foo Assert.assertEquals(0, elasticsearchClientService.countCollection("foo")); elasticsearchClientService.saveSync("foo", "type1", document1); Assert.assertEquals(1, elasticsearchClientService.countCollection("foo")); // copy index foo to bar - should work Assert.assertEquals(0, elasticsearchClientService.countCollection("bar")); elasticsearchClientService.copyCollection(TimeValue.timeValueMinutes(2).toString(), "foo", "bar"); elasticsearchClientService.bulkFlush(); Thread.sleep(2000); elasticsearchClientService.refreshCollection("bar"); Assert.assertEquals(1, elasticsearchClientService.countCollection("bar")); // Define incompatible mappings for the same doctype in two different indexes, then try to copy - should fail // as a document registered with doctype=type1 in index foo cannot be written as doctype=type1 in index baz. // // Note: MAPPING2 cannot be added to index foo or bar at all, even under a different doctype, as ES (lucene) // does not allow two types for the same field-name in different mappings of the same index. However if // MAPPING2 is added to index baz, then the copyCollection succeeds - because by default ES automatically converts // integers into strings when necessary. Interestingly, this means MAPPING1 and MAPPING2 are not compatible // at the "put mapping" level, but are compatible at the "reindex" level.. // // The document (doc1) of type "type1" already in index "foo" cannot be inserted into index "baz" as type1 // because that means applying its source to MAPPING3 - but MAPPING3 is strict and does not define property // "val", so the insert fails. elasticsearchClientService.createCollection("baz",2, 1); elasticsearchClientService.putMapping("baz", "type1", MAPPING3.replace('\'', '"')); /* try { elasticsearchClientService.copyCollection(TimeValue.timeValueMinutes(2), "foo", "baz"); Assert.fail("Exception not thrown when expected"); } catch(IOException e) { Assert.assertTrue(e.getMessage().contains("Reindex failed")); }*/ elasticsearchClientService.refreshCollection("baz"); Assert.assertEquals(0, elasticsearchClientService.countCollection("baz")); // Drop index foo elasticsearchClientService.dropCollection("foo"); Assert.assertEquals(false, elasticsearchClientService.existsCollection("foo")); Assert.assertEquals(false, elasticsearchClientService.existsCollection("aliasFoo")); // alias for foo disappears too Assert.assertEquals(true, elasticsearchClientService.existsCollection("bar")); } @Test public void testBulkPut() throws InitializationException, IOException, InterruptedException { final String index = "foo"; final String type = "type1"; final String docId = "id1"; final String nameKey = "name"; final String nameValue = "fred"; final String ageKey = "age"; final int ageValue = 33; Map<String, Object> document1 = new HashMap<>(); document1.put(nameKey, nameValue); document1.put(ageKey, ageValue); final TestRunner runner = TestRunners.newTestRunner(new TestProcessor()); // create the controller service and link it to the test processor : final ElasticsearchClientService elasticsearchClientService = configureElasticsearchClientService(runner); // Verify the index does not exist Assert.assertEquals(false, elasticsearchClientService.existsCollection(index)); // Create the index elasticsearchClientService.createCollection(index,2, 1); Assert.assertEquals(true, elasticsearchClientService.existsCollection(index)); // Put a document in the bulk processor : elasticsearchClientService.bulkPut(index, type, document1, Optional.of(docId)); // Flush the bulk processor : elasticsearchClientService.bulkFlush(); Thread.sleep(2000); try { // Refresh the index : elasticsearchClientService.refreshCollection(index); } catch (Exception e) { logger.error("Error while refreshing the index : " + e.toString()); } long documentsNumber = 0; try { documentsNumber = elasticsearchClientService.countCollection(index); } catch (Exception e) { logger.error("Error while counting the number of documents in the index : " + e.toString()); } Assert.assertEquals(1, documentsNumber); try { elasticsearchClientService.saveSync(index, type, document1); } catch (Exception e) { logger.error("Error while saving the document in the index : " + e.toString()); } try { documentsNumber = elasticsearchClientService.countCollection(index); } catch (Exception e) { logger.error("Error while counting the number of documents in the index : " + e.toString()); } Assert.assertEquals(2, documentsNumber); long numberOfHits = elasticsearchClientService.searchNumberOfHits(index, type, nameKey, nameValue); Assert.assertEquals(2, numberOfHits); } @Test public void testBulkPutGeopoint() throws InitializationException, IOException, InterruptedException { final String index = "future_factory"; final String type = "factory"; final String docId = "modane_factory"; Record record = new StandardRecord("factory") .setId(docId) .setStringField("address", "rue du Frejus") .setField("latitude", FieldType.FLOAT, 45.4f) .setField("longitude", FieldType.FLOAT, 45.4f); final TestRunner runner = TestRunners.newTestRunner(new TestProcessor()); // create the controller service and link it to the test processor : final ElasticsearchClientService elasticsearchClientService = configureElasticsearchClientService(runner); // Verify the index does not exist Assert.assertEquals(false, elasticsearchClientService.existsCollection(index)); // Create the index elasticsearchClientService.createCollection(index, 2, 1); Assert.assertEquals(true, elasticsearchClientService.existsCollection(index)); // Put a document in the bulk processor : String document1 = ElasticsearchRecordConverter.convertToString(record); elasticsearchClientService.bulkPut(index, type, document1, Optional.of(docId)); // Flush the bulk processor : elasticsearchClientService.bulkFlush(); Thread.sleep(2000); try { // Refresh the index : elasticsearchClientService.refreshCollection(index); } catch (Exception e) { logger.error("Error while refreshing the index : " + e.toString()); } long documentsNumber = 0; try { documentsNumber = elasticsearchClientService.countCollection(index); } catch (Exception e) { logger.error("Error while counting the number of documents in the index : " + e.toString()); } Assert.assertEquals(1, documentsNumber); List<MultiGetQueryRecord> multiGetQueryRecords = new ArrayList<>(); ArrayList<String> documentIds = new ArrayList<>(); List<MultiGetResponseRecord> multiGetResponseRecords = new ArrayList<>(); // Make sure a dummy query returns no result : documentIds.add(docId); try { multiGetQueryRecords.add(new MultiGetQueryRecord(index, type, new String[]{"location", "id"}, new String[]{}, documentIds)); } catch (InvalidMultiGetQueryRecordException e) { e.printStackTrace(); } multiGetResponseRecords = elasticsearchClientService.multiGet(multiGetQueryRecords); Assert.assertEquals(1, multiGetResponseRecords.size()); // number of documents retrieved } @Test public void testMultiGet() throws InitializationException, IOException, InterruptedException, InvalidMultiGetQueryRecordException { final String index1 = "index1"; final String index2 = "index2"; final String type1 = "type1"; Map<String, Object> document1 = new HashMap<>(); final String docId1 = "id1"; document1.put("field_beg_1", "field_beg_1_document1_value"); document1.put("field_beg_2", "field_beg_2_document1_value"); document1.put("field_beg_3", "field_beg_3_document1_value"); document1.put("field_fin_1", "field_fin_1_document1_value"); document1.put("field_fin_2", "field_fin_2_document1_value"); Map<String, Object> document2 = new HashMap<>(); final String docId2 = "id2"; document2.put("field_beg_1", "field_beg_1_document2_value"); document2.put("field_beg_2", "field_beg_2_document2_value"); document2.put("field_beg_3", "field_beg_3_document2_value"); document2.put("field_fin_1", "field_fin_1_document2_value"); document2.put("field_fin_2", "field_fin_2_document2_value"); Map<String, Object> document3 = new HashMap<>(); final String docId3 = "id3"; document3.put("field_beg_1", "field_beg_1_document3_value"); document3.put("field_beg_2", "field_beg_2_document3_value"); // this 3rd field is intentionally removed : // document3.put("field_beg_3", "field_beg_3_document3_value"); document3.put("field_fin_1", "field_fin_1_document3_value"); document3.put("field_fin_2", "field_fin_2_document3_value"); final TestRunner runner = TestRunners.newTestRunner(new TestProcessor()); // create the controller service and link it to the test processor : final ElasticsearchClientService elasticsearchClientService = configureElasticsearchClientService(runner); // Verify the indexes do not exist Assert.assertEquals(false, elasticsearchClientService.existsCollection(index1)); Assert.assertEquals(false, elasticsearchClientService.existsCollection(index2)); // Create the indexes elasticsearchClientService.createCollection(index1, 2, 1); elasticsearchClientService.createCollection(index2, 2, 1); Assert.assertEquals(true, elasticsearchClientService.existsCollection(index1)); Assert.assertEquals(true, elasticsearchClientService.existsCollection(index2)); // Put documents in the bulk processor : elasticsearchClientService.bulkPut(index1, type1, document1, Optional.of(docId1)); elasticsearchClientService.bulkPut(index1, type1, document2, Optional.of(docId2)); elasticsearchClientService.bulkPut(index1, type1, document3, Optional.of(docId3)); elasticsearchClientService.bulkPut(index2, type1, document1, Optional.of(docId1)); elasticsearchClientService.bulkPut(index2, type1, document2, Optional.of(docId2)); elasticsearchClientService.bulkPut(index2, type1, document3, Optional.of(docId3)); // Flush the bulk processor : elasticsearchClientService.bulkFlush(); Thread.sleep(2000); try { // Refresh the indexes : elasticsearchClientService.refreshCollection(index1); elasticsearchClientService.refreshCollection(index2); } catch (Exception e) { logger.error("Error while refreshing the indexes : " + e.toString()); } long countIndex1 = 0; long countIndex2 = 0; try { countIndex1 = elasticsearchClientService.countCollection(index1); countIndex2 = elasticsearchClientService.countCollection(index2); } catch (Exception e) { logger.error("Error while counting the number of documents in the index : " + e.toString()); } Assert.assertEquals(3, countIndex1); Assert.assertEquals(3, countIndex2); List<MultiGetQueryRecord> multiGetQueryRecords = new ArrayList<>(); ArrayList<String> documentIds = new ArrayList<>(); ArrayList<String> documentIds_2 = new ArrayList<>(); List<MultiGetResponseRecord> multiGetResponseRecords; String[] fieldsToInclude = {"field_b*", "field*1"}; String[] fieldsToExclude = {"field_*2"}; // Make sure a dummy query returns no result : documentIds.add(docId1); multiGetQueryRecords.add(new MultiGetQueryRecord("dummy", "", new String[]{"dummy"}, new String[]{}, documentIds)); multiGetResponseRecords = elasticsearchClientService.multiGet(multiGetQueryRecords); Assert.assertEquals(0, multiGetResponseRecords.size()); // number of documents retrieved multiGetQueryRecords.clear(); documentIds.clear(); multiGetResponseRecords.clear(); // Test : 1 MultiGetQueryRecord record, with 1 index, 1 type, 1 id, WITHOUT includes, WITHOUT excludes : documentIds.add(docId1); multiGetQueryRecords.add(new MultiGetQueryRecord(index1, type1, documentIds)); multiGetResponseRecords = elasticsearchClientService.multiGet(multiGetQueryRecords); Assert.assertEquals(1, multiGetResponseRecords.size()); // number of documents retrieved Assert.assertEquals(index1, multiGetResponseRecords.get(0).getCollectionName()); Assert.assertEquals(type1, multiGetResponseRecords.get(0).getTypeName()); Assert.assertEquals(docId1, multiGetResponseRecords.get(0).getDocumentId()); Assert.assertEquals(5, multiGetResponseRecords.get(0).getRetrievedFields().size()); // number of fields retrieved for the document multiGetResponseRecords.get(0).getRetrievedFields().forEach((k, v) -> document1.get(k).equals(v.toString())); multiGetQueryRecords.clear(); documentIds.clear(); multiGetResponseRecords.clear(); // Test : 1 MultiGetQueryRecord record, with 1 index, 0 type, 3 ids, WITH include, WITH exclude : documentIds.add(docId1); documentIds.add(docId2); documentIds.add(docId3); multiGetQueryRecords.add(new MultiGetQueryRecord(index1, null, fieldsToInclude, fieldsToExclude, documentIds)); multiGetResponseRecords = elasticsearchClientService.multiGet(multiGetQueryRecords); Assert.assertEquals(3, multiGetResponseRecords.size()); // verify that 3 documents has been retrieved multiGetResponseRecords.forEach(responseRecord -> Assert.assertEquals(index1, responseRecord.getCollectionName())); // verify that all retrieved are in index1 multiGetResponseRecords.forEach(responseRecord -> Assert.assertEquals(type1, responseRecord.getTypeName())); // verify that the type of all retrieved documents is type1 multiGetResponseRecords.forEach(responseRecord -> { if (responseRecord.getDocumentId() == docId1) { Assert.assertEquals(3, responseRecord.getRetrievedFields().size()); // for document1, verify that 3 fields has been retrieved // verify that the 3 retrieved fields are the correct ones : Assert.assertEquals(true, responseRecord.getRetrievedFields().containsKey("field_beg_1")); Assert.assertEquals(true, responseRecord.getRetrievedFields().containsKey("field_beg_3")); Assert.assertEquals(true, responseRecord.getRetrievedFields().containsKey("field_fin_1")); // verify that the values of the 3 retrieved fields are the correct ones : Assert.assertEquals("field_beg_1_document1_value", responseRecord.getRetrievedFields().get("field_beg_1").toString()); Assert.assertEquals("field_beg_3_document1_value", responseRecord.getRetrievedFields().get("field_beg_3").toString()); Assert.assertEquals("field_fin_1_document1_value", responseRecord.getRetrievedFields().get("field_fin_1").toString()); } if (responseRecord.getDocumentId() == docId2) Assert.assertEquals(3, responseRecord.getRetrievedFields().size()); // for document2, verify that 3 fields has been retrieved if (responseRecord.getDocumentId() == docId3) Assert.assertEquals(2, responseRecord.getRetrievedFields().size()); // for document3, verify that 2 fields has been retrieved }); multiGetQueryRecords.clear(); documentIds.clear(); multiGetResponseRecords.clear(); // Test : 2 MultiGetQueryRecord records : // - 1st : 1 index (index1), 1 type, 2 ids, WITH include, WITH exclude --> expecting : 2 docs retrieved (from index1), 3 fields each (except doc3 : 2 fields) // - 2nd : 1 index (index2), 0 type, 3 ids, WITH include, WITHOUT exclude --> expecting : 3 docs retrieved (from index2), 4 fields each (except doc3 : 3 fields) documentIds.add(docId1); documentIds.add(docId2); multiGetQueryRecords.add(new MultiGetQueryRecord(index1, type1, fieldsToInclude, fieldsToExclude, documentIds)); documentIds_2.add(docId1); documentIds_2.add(docId1); documentIds_2.add(docId1); multiGetQueryRecords.add(new MultiGetQueryRecord(index2, null, fieldsToInclude, null, documentIds_2)); multiGetResponseRecords = elasticsearchClientService.multiGet(multiGetQueryRecords); Assert.assertEquals(5, multiGetResponseRecords.size()); // verify that 5 documents has been retrieved multiGetResponseRecords.forEach(responseRecord -> { if (responseRecord.getCollectionName() == index1 && !responseRecord.getDocumentId().equals(docId3)) Assert.assertEquals(3, responseRecord.getRetrievedFields().size()); // for documents from index1 (except doc3), verify that 3 fields has been retrieved if (responseRecord.getCollectionName() == index1 && responseRecord.getDocumentId().equals(docId3)) Assert.assertEquals(2, responseRecord.getRetrievedFields().size()); // for document3 from index1, verify that 2 fields has been retrieved if (responseRecord.getDocumentId() == index2 && !responseRecord.getDocumentId().equals(docId3)) Assert.assertEquals(4, responseRecord.getRetrievedFields().size()); // for documents from index2 (except doc3), verify that 4 fields has been retrieved if (responseRecord.getDocumentId() == index2 && responseRecord.getDocumentId().equals(docId3)) Assert.assertEquals(3, responseRecord.getRetrievedFields().size()); // for document3 from index2, verify that 3 fields has been retrieved }); } @Test public void testMultiGetInvalidRecords() throws InitializationException, IOException, InterruptedException, InvalidMultiGetQueryRecordException { List<MultiGetQueryRecord> multiGetQueryRecords = new ArrayList<>(); String errorMessage = ""; // Validate null index behaviour : try { multiGetQueryRecords.add(new MultiGetQueryRecord(null, null, null, null, null)); } catch (InvalidMultiGetQueryRecordException e) { errorMessage = e.getMessage(); } Assert.assertEquals(errorMessage, "The index name cannot be null"); // Validate empty index behaviour : try { multiGetQueryRecords.add(new MultiGetQueryRecord("", null, null, null, null)); } catch (InvalidMultiGetQueryRecordException e) { errorMessage = e.getMessage(); } Assert.assertEquals(errorMessage, "The index name cannot be empty"); // Validate null documentIds behaviour : try { multiGetQueryRecords.add(new MultiGetQueryRecord("dummy", null, null, null, null)); } catch (InvalidMultiGetQueryRecordException e) { errorMessage = e.getMessage(); } Assert.assertEquals(errorMessage, "The list of document ids cannot be null"); // Make sure no invalid MultiGetQueryRecord has been added to multiGetQueryRecords list : Assert.assertEquals(0, multiGetQueryRecords.size()); } }
logisland-components/logisland-services/logisland-service-elasticsearch/logisland-service-elasticsearch_6_6_2-client/src/integration-test/java/com/hurence/logisland/service/elasticsearch/Elasticsearch_6_6_2_ClientServiceIT.java
/** * Copyright (C) 2016 Hurence ([email protected]) * * 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.hurence.logisland.service.elasticsearch; import com.hurence.logisland.classloading.PluginProxy; import com.hurence.logisland.component.InitializationException; import com.hurence.logisland.component.PropertyDescriptor; import com.hurence.logisland.controller.ControllerServiceInitializationContext; import com.hurence.logisland.processor.ProcessException; import com.hurence.logisland.record.FieldType; import com.hurence.logisland.record.Record; import com.hurence.logisland.record.StandardRecord; import com.hurence.logisland.service.datastore.InvalidMultiGetQueryRecordException; import com.hurence.logisland.service.datastore.MultiGetQueryRecord; import com.hurence.logisland.service.datastore.MultiGetResponseRecord; import com.hurence.logisland.util.runner.TestRunner; import com.hurence.logisland.util.runner.TestRunners; import org.elasticsearch.action.ActionListener; import org.elasticsearch.action.bulk.BulkItemResponse; import org.elasticsearch.action.bulk.BulkProcessor; import org.elasticsearch.action.bulk.BulkRequest; import org.elasticsearch.action.bulk.BulkResponse; import org.elasticsearch.client.RequestOptions; import org.elasticsearch.common.unit.ByteSizeUnit; import org.elasticsearch.common.unit.ByteSizeValue; import org.elasticsearch.common.unit.TimeValue; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.*; import java.util.function.BiConsumer; public class Elasticsearch_6_6_2_ClientServiceIT { private static final String MAPPING1 = "{'properties':{'name':{'type': 'text'},'val':{'type':'integer'}}}"; private static final String MAPPING2 = "{'properties':{'name':{'type': 'text'},'val':{'type': 'text'}}}"; private static final String MAPPING3 = "{'dynamic':'strict','properties':{'name':{'type': 'text'},'xyz':{'type': 'text'}}}"; private static Logger logger = LoggerFactory.getLogger(Elasticsearch_6_6_2_ClientServiceIT.class); @Rule public final ESRule esRule = new ESRule(); private class MockElasticsearchClientService extends Elasticsearch_6_6_2_ClientService { @Override protected void createElasticsearchClient(ControllerServiceInitializationContext context) throws ProcessException { if (esClient != null) { return; } esClient = esRule.getClient(); } @Override protected void createBulkProcessor(ControllerServiceInitializationContext context) { if (bulkProcessor != null) { return; } // create the bulk processor BulkProcessor.Listener listener = new BulkProcessor.Listener() { @Override public void beforeBulk(long l, BulkRequest bulkRequest) { getLogger().debug("Going to execute bulk [id:{}] composed of {} actions", new Object[]{l, bulkRequest.numberOfActions()}); } @Override public void afterBulk(long l, BulkRequest bulkRequest, BulkResponse bulkResponse) { getLogger().debug("Executed bulk [id:{}] composed of {} actions", new Object[]{l, bulkRequest.numberOfActions()}); if (bulkResponse.hasFailures()) { getLogger().warn("There was failures while executing bulk [id:{}]," + " done bulk request in {} ms with failure = {}", new Object[]{l, bulkResponse.getTook().getMillis(), bulkResponse.buildFailureMessage()}); for (BulkItemResponse item : bulkResponse.getItems()) { if (item.isFailed()) { errors.put(item.getId(), item.getFailureMessage()); } } } } @Override public void afterBulk(long l, BulkRequest bulkRequest, Throwable throwable) { getLogger().error("something went wrong while bulk loading events to es : {}", new Object[]{throwable.getMessage()}); } }; BiConsumer<BulkRequest, ActionListener<BulkResponse>> bulkConsumer = (request, bulkListener) -> esClient.bulkAsync(request, RequestOptions.DEFAULT, bulkListener); bulkProcessor = BulkProcessor.builder(bulkConsumer, listener) .setBulkActions(1000) .setBulkSize(new ByteSizeValue(10, ByteSizeUnit.MB)) .setFlushInterval(TimeValue.timeValueSeconds(1)) .setConcurrentRequests(2) //.setBackoffPolicy(getBackOffPolicy(context)) .build(); } @Override public List<PropertyDescriptor> getSupportedPropertyDescriptors() { List<PropertyDescriptor> props = new ArrayList<>(); return Collections.unmodifiableList(props); } } private ElasticsearchClientService configureElasticsearchClientService(final TestRunner runner) throws InitializationException { final MockElasticsearchClientService elasticsearchClientService = new MockElasticsearchClientService(); runner.addControllerService("elasticsearchClient", elasticsearchClientService); runner.enableControllerService(elasticsearchClientService); runner.setProperty(TestProcessor.ELASTICSEARCH_CLIENT_SERVICE, "elasticsearchClient"); runner.assertValid(elasticsearchClientService); // TODO : is this necessary ? final ElasticsearchClientService service = PluginProxy.unwrap(runner.getProcessContext().getPropertyValue(TestProcessor.ELASTICSEARCH_CLIENT_SERVICE).asControllerService()); return service; } @Test public void testBasics() throws Exception { Map<String, Object> document1 = new HashMap<>(); document1.put("name", "fred"); document1.put("val", 33); boolean result; final TestRunner runner = TestRunners.newTestRunner(new TestProcessor()); final ElasticsearchClientService elasticsearchClientService = configureElasticsearchClientService(runner); // Verify the index does not exist Assert.assertEquals(false, elasticsearchClientService.existsCollection("foo")); // Define the index elasticsearchClientService.createCollection("foo", 2, 1); Assert.assertEquals(true, elasticsearchClientService.existsCollection("foo")); // Define another index elasticsearchClientService.createCollection("bar", 2, 1); Assert.assertEquals(true, elasticsearchClientService.existsCollection("foo")); // Add a mapping to foo result = elasticsearchClientService.putMapping("foo", "type1", MAPPING1.replace('\'', '"')); Assert.assertEquals(true, result); // Add the same mapping again result = elasticsearchClientService.putMapping("foo", "type1", MAPPING1.replace('\'', '"')); Assert.assertEquals(true, result); // Update a mapping with an incompatible mapping -- should fail // result = elasticsearchClientService.putMapping("foo", "type2", MAPPING2.replace('\'', '"')); // Assert.assertEquals(false, result); // create alias elasticsearchClientService.createAlias("foo", "aliasFoo"); Assert.assertEquals(true, elasticsearchClientService.existsCollection("aliasFoo")); // Insert a record into foo and count foo Assert.assertEquals(0, elasticsearchClientService.countCollection("foo")); elasticsearchClientService.saveSync("foo", "type1", document1); Assert.assertEquals(1, elasticsearchClientService.countCollection("foo")); // copy index foo to bar - should work Assert.assertEquals(0, elasticsearchClientService.countCollection("bar")); elasticsearchClientService.copyCollection(TimeValue.timeValueMinutes(2).toString(), "foo", "bar"); elasticsearchClientService.bulkFlush(); Thread.sleep(2000); elasticsearchClientService.refreshCollection("bar"); Assert.assertEquals(1, elasticsearchClientService.countCollection("bar")); // Define incompatible mappings for the same doctype in two different indexes, then try to copy - should fail // as a document registered with doctype=type1 in index foo cannot be written as doctype=type1 in index baz. // // Note: MAPPING2 cannot be added to index foo or bar at all, even under a different doctype, as ES (lucene) // does not allow two types for the same field-name in different mappings of the same index. However if // MAPPING2 is added to index baz, then the copyCollection succeeds - because by default ES automatically converts // integers into strings when necessary. Interestingly, this means MAPPING1 and MAPPING2 are not compatible // at the "put mapping" level, but are compatible at the "reindex" level.. // // The document (doc1) of type "type1" already in index "foo" cannot be inserted into index "baz" as type1 // because that means applying its source to MAPPING3 - but MAPPING3 is strict and does not define property // "val", so the insert fails. elasticsearchClientService.createCollection("baz",2, 1); elasticsearchClientService.putMapping("baz", "type1", MAPPING3.replace('\'', '"')); /* try { elasticsearchClientService.copyCollection(TimeValue.timeValueMinutes(2), "foo", "baz"); Assert.fail("Exception not thrown when expected"); } catch(IOException e) { Assert.assertTrue(e.getMessage().contains("Reindex failed")); }*/ elasticsearchClientService.refreshCollection("baz"); Assert.assertEquals(0, elasticsearchClientService.countCollection("baz")); // Drop index foo elasticsearchClientService.dropCollection("foo"); Assert.assertEquals(false, elasticsearchClientService.existsCollection("foo")); Assert.assertEquals(false, elasticsearchClientService.existsCollection("aliasFoo")); // alias for foo disappears too Assert.assertEquals(true, elasticsearchClientService.existsCollection("bar")); } @Test public void testBulkPut() throws InitializationException, IOException, InterruptedException { final String index = "foo"; final String type = "type1"; final String docId = "id1"; final String nameKey = "name"; final String nameValue = "fred"; final String ageKey = "age"; final int ageValue = 33; Map<String, Object> document1 = new HashMap<>(); document1.put(nameKey, nameValue); document1.put(ageKey, ageValue); final TestRunner runner = TestRunners.newTestRunner(new TestProcessor()); // create the controller service and link it to the test processor : final ElasticsearchClientService elasticsearchClientService = configureElasticsearchClientService(runner); // Verify the index does not exist Assert.assertEquals(false, elasticsearchClientService.existsCollection(index)); // Create the index elasticsearchClientService.createCollection(index,2, 1); Assert.assertEquals(true, elasticsearchClientService.existsCollection(index)); // Put a document in the bulk processor : elasticsearchClientService.bulkPut(index, type, document1, Optional.of(docId)); // Flush the bulk processor : elasticsearchClientService.bulkFlush(); Thread.sleep(2000); try { // Refresh the index : elasticsearchClientService.refreshCollection(index); } catch (Exception e) { logger.error("Error while refreshing the index : " + e.toString()); } long documentsNumber = 0; try { documentsNumber = elasticsearchClientService.countCollection(index); } catch (Exception e) { logger.error("Error while counting the number of documents in the index : " + e.toString()); } Assert.assertEquals(1, documentsNumber); try { elasticsearchClientService.saveSync(index, type, document1); } catch (Exception e) { logger.error("Error while saving the document in the index : " + e.toString()); } try { documentsNumber = elasticsearchClientService.countCollection(index); } catch (Exception e) { logger.error("Error while counting the number of documents in the index : " + e.toString()); } Assert.assertEquals(2, documentsNumber); long numberOfHits = elasticsearchClientService.searchNumberOfHits(index, type, nameKey, nameValue); Assert.assertEquals(2, numberOfHits); } @Test public void testBulkPutGeopoint() throws InitializationException, IOException, InterruptedException { final String index = "future_factory"; final String type = "factory"; final String docId = "modane_factory"; Record record = new StandardRecord("factory") .setId(docId) .setStringField("address", "rue du Frejus") .setField("latitude", FieldType.FLOAT, 45.4f) .setField("longitude", FieldType.FLOAT, 45.4f); final TestRunner runner = TestRunners.newTestRunner(new TestProcessor()); // create the controller service and link it to the test processor : final ElasticsearchClientService elasticsearchClientService = configureElasticsearchClientService(runner); // Verify the index does not exist Assert.assertEquals(false, elasticsearchClientService.existsCollection(index)); // Create the index elasticsearchClientService.createCollection(index, 2, 1); Assert.assertEquals(true, elasticsearchClientService.existsCollection(index)); // Put a document in the bulk processor : String document1 = ElasticsearchRecordConverter.convertToString(record); elasticsearchClientService.bulkPut(index, type, document1, Optional.of(docId)); // Flush the bulk processor : elasticsearchClientService.bulkFlush(); Thread.sleep(2000); try { // Refresh the index : elasticsearchClientService.refreshCollection(index); } catch (Exception e) { logger.error("Error while refreshing the index : " + e.toString()); } long documentsNumber = 0; try { documentsNumber = elasticsearchClientService.countCollection(index); } catch (Exception e) { logger.error("Error while counting the number of documents in the index : " + e.toString()); } Assert.assertEquals(1, documentsNumber); List<MultiGetQueryRecord> multiGetQueryRecords = new ArrayList<>(); ArrayList<String> documentIds = new ArrayList<>(); List<MultiGetResponseRecord> multiGetResponseRecords = new ArrayList<>(); // Make sure a dummy query returns no result : documentIds.add(docId); try { multiGetQueryRecords.add(new MultiGetQueryRecord(index, type, new String[]{"location", "id"}, new String[]{}, documentIds)); } catch (InvalidMultiGetQueryRecordException e) { e.printStackTrace(); } multiGetResponseRecords = elasticsearchClientService.multiGet(multiGetQueryRecords); Assert.assertEquals(1, multiGetResponseRecords.size()); // number of documents retrieved } @Test public void testMultiGet() throws InitializationException, IOException, InterruptedException, InvalidMultiGetQueryRecordException { final String index1 = "index1"; final String index2 = "index2"; final String type1 = "type1"; Map<String, Object> document1 = new HashMap<>(); final String docId1 = "id1"; document1.put("field_beg_1", "field_beg_1_document1_value"); document1.put("field_beg_2", "field_beg_2_document1_value"); document1.put("field_beg_3", "field_beg_3_document1_value"); document1.put("field_fin_1", "field_fin_1_document1_value"); document1.put("field_fin_2", "field_fin_2_document1_value"); Map<String, Object> document2 = new HashMap<>(); final String docId2 = "id2"; document2.put("field_beg_1", "field_beg_1_document2_value"); document2.put("field_beg_2", "field_beg_2_document2_value"); document2.put("field_beg_3", "field_beg_3_document2_value"); document2.put("field_fin_1", "field_fin_1_document2_value"); document2.put("field_fin_2", "field_fin_2_document2_value"); Map<String, Object> document3 = new HashMap<>(); final String docId3 = "id3"; document3.put("field_beg_1", "field_beg_1_document3_value"); document3.put("field_beg_2", "field_beg_2_document3_value"); // this 3rd field is intentionally removed : // document3.put("field_beg_3", "field_beg_3_document3_value"); document3.put("field_fin_1", "field_fin_1_document3_value"); document3.put("field_fin_2", "field_fin_2_document3_value"); final TestRunner runner = TestRunners.newTestRunner(new TestProcessor()); // create the controller service and link it to the test processor : final ElasticsearchClientService elasticsearchClientService = configureElasticsearchClientService(runner); // Verify the indexes do not exist Assert.assertEquals(false, elasticsearchClientService.existsCollection(index1)); Assert.assertEquals(false, elasticsearchClientService.existsCollection(index2)); // Create the indexes elasticsearchClientService.createCollection(index1, 2, 1); elasticsearchClientService.createCollection(index2, 2, 1); Assert.assertEquals(true, elasticsearchClientService.existsCollection(index1)); Assert.assertEquals(true, elasticsearchClientService.existsCollection(index2)); // Put documents in the bulk processor : elasticsearchClientService.bulkPut(index1, type1, document1, Optional.of(docId1)); elasticsearchClientService.bulkPut(index1, type1, document2, Optional.of(docId2)); elasticsearchClientService.bulkPut(index1, type1, document3, Optional.of(docId3)); elasticsearchClientService.bulkPut(index2, type1, document1, Optional.of(docId1)); elasticsearchClientService.bulkPut(index2, type1, document2, Optional.of(docId2)); elasticsearchClientService.bulkPut(index2, type1, document3, Optional.of(docId3)); // Flush the bulk processor : elasticsearchClientService.bulkFlush(); Thread.sleep(2000); try { // Refresh the indexes : elasticsearchClientService.refreshCollection(index1); elasticsearchClientService.refreshCollection(index2); } catch (Exception e) { logger.error("Error while refreshing the indexes : " + e.toString()); } long countIndex1 = 0; long countIndex2 = 0; try { countIndex1 = elasticsearchClientService.countCollection(index1); countIndex2 = elasticsearchClientService.countCollection(index2); } catch (Exception e) { logger.error("Error while counting the number of documents in the index : " + e.toString()); } Assert.assertEquals(3, countIndex1); Assert.assertEquals(3, countIndex2); List<MultiGetQueryRecord> multiGetQueryRecords = new ArrayList<>(); ArrayList<String> documentIds = new ArrayList<>(); ArrayList<String> documentIds_2 = new ArrayList<>(); List<MultiGetResponseRecord> multiGetResponseRecords; String[] fieldsToInclude = {"field_b*", "field*1"}; String[] fieldsToExclude = {"field_*2"}; // Make sure a dummy query returns no result : documentIds.add(docId1); multiGetQueryRecords.add(new MultiGetQueryRecord("dummy", "", new String[]{"dummy"}, new String[]{}, documentIds)); multiGetResponseRecords = elasticsearchClientService.multiGet(multiGetQueryRecords); Assert.assertEquals(0, multiGetResponseRecords.size()); // number of documents retrieved multiGetQueryRecords.clear(); documentIds.clear(); multiGetResponseRecords.clear(); // Test : 1 MultiGetQueryRecord record, with 1 index, 1 type, 1 id, WITHOUT includes, WITHOUT excludes : documentIds.add(docId1); multiGetQueryRecords.add(new MultiGetQueryRecord(index1, type1, documentIds)); multiGetResponseRecords = elasticsearchClientService.multiGet(multiGetQueryRecords); Assert.assertEquals(1, multiGetResponseRecords.size()); // number of documents retrieved Assert.assertEquals(index1, multiGetResponseRecords.get(0).getCollectionName()); Assert.assertEquals(type1, multiGetResponseRecords.get(0).getTypeName()); Assert.assertEquals(docId1, multiGetResponseRecords.get(0).getDocumentId()); Assert.assertEquals(5, multiGetResponseRecords.get(0).getRetrievedFields().size()); // number of fields retrieved for the document multiGetResponseRecords.get(0).getRetrievedFields().forEach((k, v) -> document1.get(k).equals(v.toString())); multiGetQueryRecords.clear(); documentIds.clear(); multiGetResponseRecords.clear(); // Test : 1 MultiGetQueryRecord record, with 1 index, 0 type, 3 ids, WITH include, WITH exclude : documentIds.add(docId1); documentIds.add(docId2); documentIds.add(docId3); multiGetQueryRecords.add(new MultiGetQueryRecord(index1, null, fieldsToInclude, fieldsToExclude, documentIds)); multiGetResponseRecords = elasticsearchClientService.multiGet(multiGetQueryRecords); Assert.assertEquals(3, multiGetResponseRecords.size()); // verify that 3 documents has been retrieved multiGetResponseRecords.forEach(responseRecord -> Assert.assertEquals(index1, responseRecord.getCollectionName())); // verify that all retrieved are in index1 multiGetResponseRecords.forEach(responseRecord -> Assert.assertEquals(type1, responseRecord.getTypeName())); // verify that the type of all retrieved documents is type1 multiGetResponseRecords.forEach(responseRecord -> { if (responseRecord.getDocumentId() == docId1) { Assert.assertEquals(3, responseRecord.getRetrievedFields().size()); // for document1, verify that 3 fields has been retrieved // verify that the 3 retrieved fields are the correct ones : Assert.assertEquals(true, responseRecord.getRetrievedFields().containsKey("field_beg_1")); Assert.assertEquals(true, responseRecord.getRetrievedFields().containsKey("field_beg_3")); Assert.assertEquals(true, responseRecord.getRetrievedFields().containsKey("field_fin_1")); // verify that the values of the 3 retrieved fields are the correct ones : Assert.assertEquals("field_beg_1_document1_value", responseRecord.getRetrievedFields().get("field_beg_1").toString()); Assert.assertEquals("field_beg_3_document1_value", responseRecord.getRetrievedFields().get("field_beg_3").toString()); Assert.assertEquals("field_fin_1_document1_value", responseRecord.getRetrievedFields().get("field_fin_1").toString()); } if (responseRecord.getDocumentId() == docId2) Assert.assertEquals(3, responseRecord.getRetrievedFields().size()); // for document2, verify that 3 fields has been retrieved if (responseRecord.getDocumentId() == docId3) Assert.assertEquals(2, responseRecord.getRetrievedFields().size()); // for document3, verify that 2 fields has been retrieved }); multiGetQueryRecords.clear(); documentIds.clear(); multiGetResponseRecords.clear(); // Test : 2 MultiGetQueryRecord records : // - 1st : 1 index (index1), 1 type, 2 ids, WITH include, WITH exclude --> expecting : 2 docs retrieved (from index1), 3 fields each (except doc3 : 2 fields) // - 2nd : 1 index (index2), 0 type, 3 ids, WITH include, WITHOUT exclude --> expecting : 3 docs retrieved (from index2), 4 fields each (except doc3 : 3 fields) documentIds.add(docId1); documentIds.add(docId2); multiGetQueryRecords.add(new MultiGetQueryRecord(index1, type1, fieldsToInclude, fieldsToExclude, documentIds)); documentIds_2.add(docId1); documentIds_2.add(docId1); documentIds_2.add(docId1); multiGetQueryRecords.add(new MultiGetQueryRecord(index2, null, fieldsToInclude, null, documentIds_2)); multiGetResponseRecords = elasticsearchClientService.multiGet(multiGetQueryRecords); Assert.assertEquals(5, multiGetResponseRecords.size()); // verify that 5 documents has been retrieved multiGetResponseRecords.forEach(responseRecord -> { if (responseRecord.getCollectionName() == index1 && !responseRecord.getDocumentId().equals(docId3)) Assert.assertEquals(3, responseRecord.getRetrievedFields().size()); // for documents from index1 (except doc3), verify that 3 fields has been retrieved if (responseRecord.getCollectionName() == index1 && responseRecord.getDocumentId().equals(docId3)) Assert.assertEquals(2, responseRecord.getRetrievedFields().size()); // for document3 from index1, verify that 2 fields has been retrieved if (responseRecord.getDocumentId() == index2 && !responseRecord.getDocumentId().equals(docId3)) Assert.assertEquals(4, responseRecord.getRetrievedFields().size()); // for documents from index2 (except doc3), verify that 4 fields has been retrieved if (responseRecord.getDocumentId() == index2 && responseRecord.getDocumentId().equals(docId3)) Assert.assertEquals(3, responseRecord.getRetrievedFields().size()); // for document3 from index2, verify that 3 fields has been retrieved }); } @Test public void testMultiGetInvalidRecords() throws InitializationException, IOException, InterruptedException, InvalidMultiGetQueryRecordException { List<MultiGetQueryRecord> multiGetQueryRecords = new ArrayList<>(); String errorMessage = ""; // Validate null index behaviour : try { multiGetQueryRecords.add(new MultiGetQueryRecord(null, null, null, null, null)); } catch (InvalidMultiGetQueryRecordException e) { errorMessage = e.getMessage(); } Assert.assertEquals(errorMessage, "The index name cannot be null"); // Validate empty index behaviour : try { multiGetQueryRecords.add(new MultiGetQueryRecord("", null, null, null, null)); } catch (InvalidMultiGetQueryRecordException e) { errorMessage = e.getMessage(); } Assert.assertEquals(errorMessage, "The index name cannot be empty"); // Validate null documentIds behaviour : try { multiGetQueryRecords.add(new MultiGetQueryRecord("dummy", null, null, null, null)); } catch (InvalidMultiGetQueryRecordException e) { errorMessage = e.getMessage(); } Assert.assertEquals(errorMessage, "The list of document ids cannot be null"); // Make sure no invalid MultiGetQueryRecord has been added to multiGetQueryRecords list : Assert.assertEquals(0, multiGetQueryRecords.size()); } }
Improved elasticsearch tests by initializing docker container once and not for each tests. Time passed from 1m11s to 11s.
logisland-components/logisland-services/logisland-service-elasticsearch/logisland-service-elasticsearch_6_6_2-client/src/integration-test/java/com/hurence/logisland/service/elasticsearch/Elasticsearch_6_6_2_ClientServiceIT.java
Improved elasticsearch tests by initializing docker container once and not for each tests. Time passed from 1m11s to 11s.
Java
apache-2.0
245af014eef0cf2958de206a14ab7293ca90c9e0
0
alexruiz/fest-reflect
/* * Created on Oct 31, 2006 * * 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. * * Copyright @2006-2013 the original author or authors. */ package org.fest.reflect.method; import static org.fest.reflect.util.Accessibles.makeAccessible; import static org.fest.reflect.util.Accessibles.setAccessibleIgnoringExceptions; import static org.fest.reflect.util.Throwables.targetOf; import static org.fest.reflect.util.Types.castSafely; import static org.fest.util.Arrays.format; import static org.fest.util.Preconditions.checkNotNull; import static org.fest.util.Preconditions.checkNotNullOrEmpty; import static org.fest.util.Strings.quote; import java.lang.reflect.Method; import javax.annotation.Nonnull; import javax.annotation.Nullable; import org.fest.reflect.exception.ReflectionError; /** * Invokes a method using * <a href="http://docs.oracle.com/javase/tutorial/reflect/index.html" target="_blank">Java Reflection</a>. * * @param <T> the return type of the method to invoke. * @author Yvonne Wang * @author Alex Ruiz */ public final class MethodInvoker<T> { private final Class<T> returnType; private final Object target; private final Method method; MethodInvoker(@Nonnull String methodName, @Nonnull Class<T> returnType, @Nonnull Class<?>[] parameterTypes, @Nonnull Object target) { this.returnType = checkNotNull(returnType); this.target = checkNotNull(target); this.method = findMethodInClassHierarchy(checkNotNullOrEmpty(methodName), checkNotNull(parameterTypes)); } private @Nonnull Method findMethodInClassHierarchy(@Nonnull String methodName, @Nonnull Class<?>[] parameterTypes) { Method method = null; Class<?> targetType = target instanceof Class<?> ? (Class<?>) target : target.getClass(); Class<?> type = targetType; while (type != null) { method = findMethod(methodName, type, parameterTypes); if (method != null) { break; } type = type.getSuperclass(); } if (method == null) { String format = "Unable to find method: %s in: %s with parameter type(s) %s"; throw new ReflectionError(String.format(format, quote(methodName), targetType.getName(), format(parameterTypes))); } return method; } private static @Nullable Method findMethod( @Nonnull String methodName, @Nonnull Class<?> type, @Nonnull Class<?>[] parameterTypes) { try { return type.getDeclaredMethod(methodName, parameterTypes); } catch (SecurityException e) { return null; } catch (NoSuchMethodException e) { return null; } } /** * <p> * Invokes a method. * </p> * * <p> * Examples demonstrating usage of the fluent interface: * * <pre> * // Equivalent to invoking the method 'person.setName("Luke")' * {@link org.fest.reflect.core.Reflection#method(String) method}("setName").{@link org.fest.reflect.method.MethodName#withParameterTypes(Class...) withParameterTypes}(String.class) * .{@link org.fest.reflect.method.ParameterTypes#in(Object) in}(person) * .{@link org.fest.reflect.method.MethodInvoker#invoke(Object...) invoke}("Luke"); * * // Equivalent to invoking the method 'jedi.getPowers()' * List&lt;String&gt; powers = {@link org.fest.reflect.core.Reflection#method(String) method}("getPowers").{@link org.fest.reflect.method.MethodName#withReturnType(org.fest.reflect.reference.TypeRef) withReturnType}(new {@link org.fest.reflect.reference.TypeRef TypeRef}&lt;List&lt;String&gt;&gt;() {}) * .{@link org.fest.reflect.method.ReturnTypeRef#in(Object) in}(person) * .{@link org.fest.reflect.method.MethodInvoker#invoke(Object...) invoke}(); * * // Equivalent to invoking the static method 'Jedi.setCommonPower("Jump")' * {@link org.fest.reflect.core.Reflection#method(String) method}("setCommonPower").{@link org.fest.reflect.method.MethodName#withParameterTypes(Class...) withParameterTypes}(String.class) * .{@link org.fest.reflect.method.ParameterTypes#in(Object) in}(Jedi.class) * .{@link org.fest.reflect.method.MethodInvoker#invoke(Object...) invoke}("Jump"); * * // Equivalent to invoking the static method 'Jedi.addPadawan()' * {@link org.fest.reflect.core.Reflection#method(String) method}("addPadawan").{@link org.fest.reflect.method.MethodName#in(Object) in}(Jedi.class).{@link org.fest.reflect.method.MethodInvoker#invoke(Object...) invoke}(); * </pre> * </p> * * @param args the arguments to use to call the method managed by this class. * @return the result of the method call. * @throws ReflectionError if the method cannot be invoked. */ public @Nullable T invoke(@Nonnull Object... args) { checkNotNull(args); Method method = method(); boolean accessible = method.isAccessible(); try { makeAccessible(method); Object returnValue = method.invoke(target, args); return castSafely(returnValue, checkNotNull(returnType)); } catch (Throwable t) { Throwable cause = targetOf(t); if (cause instanceof RuntimeException) { throw (RuntimeException) cause; } String format = "Unable to invoke method %s with arguments %s"; throw new ReflectionError(String.format(format, quote(method.getName()), format(args)), cause); } finally { setAccessibleIgnoringExceptions(method, accessible); } } /** * @return the underlying method to invoke via Java Reflection. */ public @Nonnull Method method() { return method; } }
src/main/java/org/fest/reflect/method/MethodInvoker.java
/* * Created on Oct 31, 2006 * * 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. * * Copyright @2006-2013 the original author or authors. */ package org.fest.reflect.method; import static org.fest.reflect.util.Accessibles.makeAccessible; import static org.fest.reflect.util.Accessibles.setAccessibleIgnoringExceptions; import static org.fest.reflect.util.Throwables.targetOf; import static org.fest.reflect.util.Types.castSafely; import static org.fest.util.Arrays.format; import static org.fest.util.Preconditions.checkNotNull; import static org.fest.util.Preconditions.checkNotNullOrEmpty; import static org.fest.util.Strings.quote; import java.lang.reflect.Method; import javax.annotation.Nonnull; import javax.annotation.Nullable; import org.fest.reflect.exception.ReflectionError; /** * Invokes a method using * <a href="http://docs.oracle.com/javase/tutorial/reflect/index.html" target="_blank">Java Reflection</a>. * * @param <T> the return type of the method to invoke. * @author Yvonne Wang * @author Alex Ruiz */ public final class MethodInvoker<T> { private final Class<T> returnType; private final Object target; private final Method method; MethodInvoker(@Nonnull String methodName, @Nonnull Class<T> returnType, @Nonnull Class<?>[] parameterTypes, @Nonnull Object target) { this.returnType = checkNotNull(returnType); this.target = checkNotNull(target); this.method = findMethodInClassHierarchy(checkNotNullOrEmpty(methodName), checkNotNull(parameterTypes)); } private @Nonnull Method findMethodInClassHierarchy(@Nonnull String methodName, @Nonnull Class<?>[] parameterTypes) { Method method = null; Class<?> targetType = target instanceof Class<?> ? (Class<?>) target : target.getClass(); Class<?> type = targetType; while (type != null) { method = findMethod(methodName, type, parameterTypes); if (method != null) { break; } type = type.getSuperclass(); } if (method == null) { String format = "Unable to find method: %s in: %s with parameter type(s) %s"; throw new ReflectionError(String.format(format, quote(methodName), targetType.getName(), format(parameterTypes))); } return method; } private static @Nullable Method findMethod( @Nonnull String methodName, @Nonnull Class<?> type, @Nonnull Class<?>[] parameterTypes) { try { return type.getDeclaredMethod(methodName, parameterTypes); } catch (SecurityException e) { return null; } catch (NoSuchMethodException e) { return null; } } /** * <p> * Invokes a method. * </p> * * <p> * Examples demonstrating usage of the fluent interface: * * <pre> * // Equivalent to invoking the method 'person.setName("Luke")' * {@link org.fest.reflect.core.Reflection#method(String) method}("setName").{@link org.fest.reflect.method.MethodName#withParameterTypes(Class...) withParameterTypes}(String.class) * .{@link org.fest.reflect.method.ParameterTypes#in(Object) in}(person) * .{@link org.fest.reflect.method.MethodInvoker#invoke(Object...) invoke}("Luke"); * * // Equivalent to invoking the method 'jedi.getPowers()' * List&lt;String&gt; powers = {@link org.fest.reflect.core.Reflection#method(String) method}("getPowers").{@link org.fest.reflect.method.MethodName#withReturnType(org.fest.reflect.reference.TypeRef) withReturnType}(new {@link org.fest.reflect.reference.TypeRef TypeRef}&lt;List&lt;String&gt;&gt;() {}) * .{@link org.fest.reflect.method.ReturnTypeRef#in(Object) in}(person) * .{@link org.fest.reflect.method.MethodInvoker#invoke(Object...) invoke}(); * * // Equivalent to invoking the static method 'Jedi.setCommonPower("Jump")' * {@link org.fest.reflect.core.Reflection#method(String) method}("setCommonPower").{@link org.fest.reflect.method.MethodName#withParameterTypes(Class...) withParameterTypes}(String.class) * .{@link org.fest.reflect.method.ParameterTypes#in(Object) in}(Jedi.class) * .{@link org.fest.reflect.method.MethodInvoker#invoke(Object...) invoke}("Jump"); * * // Equivalent to invoking the static method 'Jedi.addPadawan()' * {@link org.fest.reflect.core.Reflection#method(String) method}("addPadawan").{@link org.fest.reflect.method.MethodName#in(Object) in}(Jedi.class).{@link org.fest.reflect.method.MethodInvoker#invoke(Object...) invoke}(); * </pre> * </p> * * @param args the arguments to use to call the method managed by this class. * @return the result of the method call. * @throws ReflectionError if the method cannot be invoked. */ public @Nullable T invoke(@Nonnull Object... args) { checkNotNull(args); Method method = target(); boolean accessible = method.isAccessible(); try { makeAccessible(method); Object returnValue = method.invoke(target, args); return castSafely(returnValue, checkNotNull(returnType)); } catch (Throwable t) { Throwable cause = targetOf(t); if (cause instanceof RuntimeException) { throw (RuntimeException) cause; } String format = "Unable to invoke method %s with arguments %s"; throw new ReflectionError(String.format(format, quote(method.getName()), format(args)), cause); } finally { setAccessibleIgnoringExceptions(method, accessible); } } /** * @return the underlying method to invoke via Java Reflection. */ public @Nonnull Method target() { return method; } }
Minor changes.
src/main/java/org/fest/reflect/method/MethodInvoker.java
Minor changes.
Java
apache-2.0
c9aac6d605285477913cf1b55c3005242329fac9
0
adinardi/google-closure-compiler,bramstein/closure-compiler-inline,h4ck3rm1k3/javascript-closure-compiler-git,adinardi/google-closure-compiler,h4ck3rm1k3/javascript-closure-compiler-git,dound/google-closure-compiler,bramstein/closure-compiler-inline,knutwalker/google-closure-compiler,dound/google-closure-compiler,knutwalker/google-closure-compiler
/* * Copyright 2009 The Closure Compiler 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 com.google.javascript.jscomp; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Charsets; import com.google.common.base.Preconditions; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.google.common.io.Files; import com.google.javascript.jscomp.AbstractCompiler.LifeCycleStage; import com.google.javascript.jscomp.CompilerOptions.LanguageMode; import com.google.javascript.jscomp.NodeTraversal.Callback; import com.google.javascript.rhino.Node; import com.google.javascript.rhino.Token; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.text.ParseException; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; /** * Pass factories and meta-data for native JSCompiler passes. * * @author [email protected] (Nick Santos) */ // TODO(nicksantos): This needs state for a variety of reasons. Some of it // is to satisfy the existing API. Some of it is because passes really do // need to share state in non-trivial ways. This should be audited and // cleaned up. public class DefaultPassConfig extends PassConfig { /* For the --mark-as-compiled pass */ private static final String COMPILED_CONSTANT_NAME = "COMPILED"; /* Constant name for Closure's locale */ private static final String CLOSURE_LOCALE_CONSTANT_NAME = "goog.LOCALE"; // Compiler errors when invalid combinations of passes are run. static final DiagnosticType TIGHTEN_TYPES_WITHOUT_TYPE_CHECK = DiagnosticType.error("JSC_TIGHTEN_TYPES_WITHOUT_TYPE_CHECK", "TightenTypes requires type checking. Please use --check_types."); static final DiagnosticType CANNOT_USE_PROTOTYPE_AND_VAR = DiagnosticType.error("JSC_CANNOT_USE_PROTOTYPE_AND_VAR", "Rename prototypes and inline variables cannot be used together"); // Miscellaneous errors. static final DiagnosticType REPORT_PATH_IO_ERROR = DiagnosticType.error("JSC_REPORT_PATH_IO_ERROR", "Error writing compiler report to {0}"); private static final DiagnosticType INPUT_MAP_PROP_PARSE = DiagnosticType.error("JSC_INPUT_MAP_PROP_PARSE", "Input property map parse error: {0}"); private static final DiagnosticType INPUT_MAP_VAR_PARSE = DiagnosticType.error("JSC_INPUT_MAP_VAR_PARSE", "Input variable map parse error: {0}"); private static final DiagnosticType NAME_REF_GRAPH_FILE_ERROR = DiagnosticType.error("JSC_NAME_REF_GRAPH_FILE_ERROR", "Error \"{1}\" writing name reference graph to \"{0}\"."); private static final DiagnosticType NAME_REF_REPORT_FILE_ERROR = DiagnosticType.error("JSC_NAME_REF_REPORT_FILE_ERROR", "Error \"{1}\" writing name reference report to \"{0}\"."); /** * A global namespace to share across checking passes. * TODO(nicksantos): This is a hack until I can get the namespace into * the symbol table. */ private GlobalNamespace namespaceForChecks = null; /** * A type-tightener to share across optimization passes. */ private TightenTypes tightenTypes = null; /** Names exported by goog.exportSymbol. */ private Set<String> exportedNames = null; /** * Ids for cross-module method stubbing, so that each method has * a unique id. */ private CrossModuleMethodMotion.IdGenerator crossModuleIdGenerator = new CrossModuleMethodMotion.IdGenerator(); /** * Keys are arguments passed to getCssName() found during compilation; values * are the number of times the key appeared as an argument to getCssName(). */ private Map<String, Integer> cssNames = null; /** The variable renaming map */ private VariableMap variableMap = null; /** The property renaming map */ private VariableMap propertyMap = null; /** The naming map for anonymous functions */ private VariableMap anonymousFunctionNameMap = null; /** Fully qualified function names and globally unique ids */ private FunctionNames functionNames = null; /** String replacement map */ private VariableMap stringMap = null; /** Id generator map */ private String idGeneratorMap = null; public DefaultPassConfig(CompilerOptions options) { super(options); } @Override State getIntermediateState() { return new State( cssNames == null ? null : Maps.newHashMap(cssNames), exportedNames == null ? null : Collections.unmodifiableSet(exportedNames), crossModuleIdGenerator, variableMap, propertyMap, anonymousFunctionNameMap, stringMap, functionNames, idGeneratorMap); } @Override void setIntermediateState(State state) { this.cssNames = state.cssNames == null ? null : Maps.newHashMap(state.cssNames); this.exportedNames = state.exportedNames == null ? null : Sets.newHashSet(state.exportedNames); this.crossModuleIdGenerator = state.crossModuleIdGenerator; this.variableMap = state.variableMap; this.propertyMap = state.propertyMap; this.anonymousFunctionNameMap = state.anonymousFunctionNameMap; this.stringMap = state.stringMap; this.functionNames = state.functionNames; this.idGeneratorMap = state.idGeneratorMap; } @Override protected List<PassFactory> getChecks() { List<PassFactory> checks = Lists.newArrayList(); if (options.closurePass) { checks.add(closureGoogScopeAliases); } if (options.nameAnonymousFunctionsOnly) { if (options.anonymousFunctionNaming == AnonymousFunctionNamingPolicy.MAPPED) { checks.add(nameMappedAnonymousFunctions); } else if (options.anonymousFunctionNaming == AnonymousFunctionNamingPolicy.UNMAPPED) { checks.add(nameUnmappedAnonymousFunctions); } return checks; } if (options.checkSuspiciousCode || options.enables(DiagnosticGroups.GLOBAL_THIS)) { checks.add(suspiciousCode); } if (options.checkControlStructures) { checks.add(checkControlStructures); } if (options.checkRequires.isOn()) { checks.add(checkRequires); } if (options.checkProvides.isOn()) { checks.add(checkProvides); } // The following passes are more like "preprocessor" passes. // It's important that they run before most checking passes. // Perhaps this method should be renamed? if (options.generateExports) { checks.add(generateExports); } if (options.exportTestFunctions) { checks.add(exportTestFunctions); } if (options.closurePass) { checks.add(closurePrimitives.makeOneTimePass()); } if (options.closurePass && options.checkMissingGetCssNameLevel.isOn()) { checks.add(closureCheckGetCssName); } if (options.syntheticBlockStartMarker != null) { // This pass must run before the first fold constants pass. checks.add(createSyntheticBlocks); } checks.add(checkVars); if (options.computeFunctionSideEffects) { checks.add(checkRegExp); } if (options.checkShadowVars.isOn()) { checks.add(checkShadowVars); } if (options.aggressiveVarCheck.isOn()) { checks.add(checkVariableReferences); } // This pass should run before types are assigned. if (options.processObjectPropertyString) { checks.add(objectPropertyStringPreprocess); } if (options.checkTypes || options.inferTypes) { checks.add(resolveTypes.makeOneTimePass()); checks.add(inferTypes.makeOneTimePass()); if (options.checkTypes) { checks.add(checkTypes.makeOneTimePass()); } else { checks.add(inferJsDocInfo.makeOneTimePass()); } } if (options.checkUnreachableCode.isOn() || (options.checkTypes && options.checkMissingReturn.isOn())) { checks.add(checkControlFlow); } // CheckAccessControls only works if check types is on. if (options.checkTypes && (options.enables(DiagnosticGroups.ACCESS_CONTROLS) || options.enables(DiagnosticGroups.CONSTANT_PROPERTY))) { checks.add(checkAccessControls); } if (options.checkGlobalNamesLevel.isOn()) { checks.add(checkGlobalNames); } if (options.getLanguageIn() == LanguageMode.ECMASCRIPT5_STRICT || options.checkCaja || options.checkEs5Strict) { checks.add(checkStrictMode); } // Replace 'goog.getCssName' before processing defines but after the // other checks have been done. if (options.closurePass) { checks.add(closureReplaceGetCssName); } // i18n // If you want to customize the compiler to use a different i18n pass, // you can create a PassConfig that calls replacePassFactory // to replace this. checks.add(options.messageBundle != null ? replaceMessages : createEmptyPass("replaceMessages")); if (options.getTweakProcessing().isOn()) { checks.add(processTweaks); } // Defines in code always need to be processed. checks.add(processDefines); if (options.instrumentationTemplate != null || options.recordFunctionInformation) { checks.add(computeFunctionNames); } if (options.nameReferenceGraphPath != null && !options.nameReferenceGraphPath.isEmpty()) { checks.add(printNameReferenceGraph); } if (options.nameReferenceReportPath != null && !options.nameReferenceReportPath.isEmpty()) { checks.add(printNameReferenceReport); } assertAllOneTimePasses(checks); return checks; } @Override protected List<PassFactory> getOptimizations() { List<PassFactory> passes = Lists.newArrayList(); // TODO(nicksantos): The order of these passes makes no sense, and needs // to be re-arranged. if (options.runtimeTypeCheck) { passes.add(runtimeTypeCheck); } passes.add(createEmptyPass("beforeStandardOptimizations")); if (!options.idGenerators.isEmpty()) { passes.add(replaceIdGenerators); } // Optimizes references to the arguments variable. if (options.optimizeArgumentsArray) { passes.add(optimizeArgumentsArray); } // Abstract method removal works best on minimally modified code, and also // only needs to run once. if (options.closurePass && (options.removeAbstractMethods || options.removeClosureAsserts)) { passes.add(closureCodeRemoval); } // Collapsing properties can undo constant inlining, so we do this before // the main optimization loop. if (options.collapseProperties) { passes.add(collapseProperties); } // ReplaceStrings runs after CollapseProperties in order to simplify // pulling in values of constants defined in enums structures. if (!options.replaceStringsFunctionDescriptions.isEmpty()) { passes.add(replaceStrings); } // Tighten types based on actual usage. if (options.tightenTypes) { passes.add(tightenTypesBuilder); } // Property disambiguation should only run once and needs to be done // soon after type checking, both so that it can make use of type // information and so that other passes can take advantage of the renamed // properties. if (options.disambiguateProperties) { passes.add(disambiguateProperties); } if (options.computeFunctionSideEffects) { passes.add(markPureFunctions); } else if (options.markNoSideEffectCalls) { // TODO(user) The properties that this pass adds to CALL and NEW // AST nodes increase the AST's in-memory size. Given that we are // already running close to our memory limits, we could run into // trouble if we end up using the @nosideeffects annotation a lot // or compute @nosideeffects annotations by looking at function // bodies. It should be easy to propagate @nosideeffects // annotations as part of passes that depend on this property and // store the result outside the AST (which would allow garbage // collection once the pass is done). passes.add(markNoSideEffectCalls); } if (options.chainCalls) { passes.add(chainCalls); } // Constant checking must be done after property collapsing because // property collapsing can introduce new constants (e.g. enum values). if (options.inlineConstantVars) { passes.add(checkConsts); } // The Caja library adds properties to Object.prototype, which breaks // most for-in loops. This adds a check to each loop that skips // any property matching /___$/. if (options.ignoreCajaProperties) { passes.add(ignoreCajaProperties); } assertAllOneTimePasses(passes); if (options.smartNameRemoval || options.reportPath != null) { passes.addAll(getCodeRemovingPasses()); passes.add(smartNamePass); } // This needs to come after the inline constants pass, which is run within // the code removing passes. if (options.closurePass) { passes.add(closureOptimizePrimitives); } // TODO(user): This forces a first crack at crossModuleCodeMotion // before devirtualization. Once certain functions are devirtualized, // it confuses crossModuleCodeMotion ability to recognized that // it is recursive. // TODO(user): This is meant for a temporary quick win. // In the future, we might want to improve our analysis in // CrossModuleCodeMotion so we don't need to do this. if (options.crossModuleCodeMotion) { passes.add(crossModuleCodeMotion); } // Method devirtualization benefits from property disambiguiation so // it should run after that pass but before passes that do // optimizations based on global names (like cross module code motion // and inline functions). Smart Name Removal does better if run before // this pass. if (options.devirtualizePrototypeMethods) { passes.add(devirtualizePrototypeMethods); } if (options.customPasses != null) { passes.add(getCustomPasses( CustomPassExecutionTime.BEFORE_OPTIMIZATION_LOOP)); } passes.add(createEmptyPass("beforeMainOptimizations")); if (options.specializeInitialModule) { // When specializing the initial module, we want our fixups to be // as lean as possible, so we run the entire optimization loop to a // fixed point before specializing, then specialize, and then run the // main optimization loop again. passes.addAll(getMainOptimizationLoop()); if (options.crossModuleCodeMotion) { passes.add(crossModuleCodeMotion); } if (options.crossModuleMethodMotion) { passes.add(crossModuleMethodMotion); } passes.add(specializeInitialModule.makeOneTimePass()); } passes.addAll(getMainOptimizationLoop()); passes.add(createEmptyPass("beforeModuleMotion")); if (options.crossModuleCodeMotion) { passes.add(crossModuleCodeMotion); } if (options.crossModuleMethodMotion) { passes.add(crossModuleMethodMotion); } passes.add(createEmptyPass("afterModuleMotion")); // Some optimizations belong outside the loop because running them more // than once would either have no benefit or be incorrect. if (options.customPasses != null) { passes.add(getCustomPasses( CustomPassExecutionTime.AFTER_OPTIMIZATION_LOOP)); } if (options.flowSensitiveInlineVariables) { passes.add(flowSensitiveInlineVariables); // After inlining some of the variable uses, some variables are unused. // Re-run remove unused vars to clean it up. if (options.removeUnusedVars) { passes.add(removeUnusedVars); } } // Running this pass again is required to have goog.events compile down to // nothing when compiled on its own. if (options.smartNameRemoval) { passes.add(smartNamePass2); } if (options.collapseAnonymousFunctions) { passes.add(collapseAnonymousFunctions); } // Move functions before extracting prototype member declarations. if (options.moveFunctionDeclarations) { passes.add(moveFunctionDeclarations); } if (options.anonymousFunctionNaming == AnonymousFunctionNamingPolicy.MAPPED) { passes.add(nameMappedAnonymousFunctions); } // The mapped name anonymous function pass makes use of information that // the extract prototype member declarations pass removes so the former // happens before the latter. // // Extracting prototype properties screws up the heuristic renaming // policies, so never run it when those policies are requested. if (options.extractPrototypeMemberDeclarations && (options.propertyRenaming != PropertyRenamingPolicy.HEURISTIC && options.propertyRenaming != PropertyRenamingPolicy.AGGRESSIVE_HEURISTIC)) { passes.add(extractPrototypeMemberDeclarations); } if (options.ambiguateProperties && (options.propertyRenaming == PropertyRenamingPolicy.ALL_UNQUOTED)) { passes.add(ambiguateProperties); } if (options.propertyRenaming != PropertyRenamingPolicy.OFF) { passes.add(renameProperties); } // Reserve global names added to the "windows" object. if (options.reserveRawExports) { passes.add(gatherRawExports); } // This comes after property renaming because quoted property names must // not be renamed. if (options.convertToDottedProperties) { passes.add(convertToDottedProperties); } // Property renaming must happen before this pass runs since this // pass may convert dotted properties into quoted properties. It // is beneficial to run before alias strings, alias keywords and // variable renaming. if (options.rewriteFunctionExpressions) { passes.add(rewriteFunctionExpressions); } // This comes after converting quoted property accesses to dotted property // accesses in order to avoid aliasing property names. if (!options.aliasableStrings.isEmpty() || options.aliasAllStrings) { passes.add(aliasStrings); } if (options.aliasExternals) { passes.add(aliasExternals); } if (options.aliasKeywords) { passes.add(aliasKeywords); } // Passes after this point can no longer depend on normalized AST // assumptions. passes.add(markUnnormalized); if (options.coalesceVariableNames) { passes.add(coalesceVariableNames); // coalesceVariables creates identity assignments and more redundant code // that can be removed, rerun the peephole optimizations to clean them // up. if (options.foldConstants) { passes.add(peepholeOptimizations); } } if (options.collapseVariableDeclarations) { passes.add(exploitAssign); passes.add(collapseVariableDeclarations); } // This pass works best after collapseVariableDeclarations. passes.add(denormalize); if (options.instrumentationTemplate != null) { passes.add(instrumentFunctions); } if (options.variableRenaming != VariableRenamingPolicy.ALL) { // If we're leaving some (or all) variables with their old names, // then we need to undo any of the markers we added for distinguishing // local variables ("$$1"). passes.add(invertContextualRenaming); } if (options.variableRenaming != VariableRenamingPolicy.OFF) { passes.add(renameVars); } if (options.groupVariableDeclarations) { passes.add(groupVariableDeclarations); } // This pass should run after names stop changing. if (options.processObjectPropertyString) { passes.add(objectPropertyStringPostprocess); } if (options.labelRenaming) { passes.add(renameLabels); } if (options.foldConstants) { passes.add(latePeepholeOptimizations); } if (options.anonymousFunctionNaming == AnonymousFunctionNamingPolicy.UNMAPPED) { passes.add(nameUnmappedAnonymousFunctions); } if (options.operaCompoundAssignFix) { passes.add(operaCompoundAssignFix); } // Safety checks passes.add(sanityCheckAst); passes.add(sanityCheckVars); return passes; } /** Creates the passes for the main optimization loop. */ private List<PassFactory> getMainOptimizationLoop() { List<PassFactory> passes = Lists.newArrayList(); if (options.inlineGetters) { passes.add(inlineSimpleMethods); } passes.addAll(getCodeRemovingPasses()); if (options.inlineFunctions || options.inlineLocalFunctions) { passes.add(inlineFunctions); } boolean runOptimizeCalls = options.optimizeCalls || options.optimizeParameters || options.optimizeReturns; if (options.removeUnusedVars || options.removeUnusedLocalVars) { if (options.deadAssignmentElimination) { passes.add(deadAssignmentsElimination); } if (!runOptimizeCalls) { passes.add(removeUnusedVars); } } if (runOptimizeCalls) { passes.add(optimizeCallsAndRemoveUnusedVars); } assertAllLoopablePasses(passes); return passes; } /** Creates several passes aimed at removing code. */ private List<PassFactory> getCodeRemovingPasses() { List<PassFactory> passes = Lists.newArrayList(); if (options.collapseObjectLiterals && !isInliningForbidden()) { passes.add(collapseObjectLiterals); } if (options.inlineVariables || options.inlineLocalVariables) { passes.add(inlineVariables); } else if (options.inlineConstantVars) { passes.add(inlineConstants); } if (options.foldConstants) { // These used to be one pass. passes.add(minimizeExitPoints); passes.add(peepholeOptimizations); } if (options.removeDeadCode) { passes.add(removeUnreachableCode); } if (options.removeUnusedPrototypeProperties) { passes.add(removeUnusedPrototypeProperties); } assertAllLoopablePasses(passes); return passes; } /** * Checks for code that is probably wrong (such as stray expressions). */ // TODO(bolinfest): Write a CompilerPass for this. final HotSwapPassFactory suspiciousCode = new HotSwapPassFactory("suspiciousCode", true) { @Override protected HotSwapCompilerPass createInternal(final AbstractCompiler compiler) { List<Callback> sharedCallbacks = Lists.newArrayList(); if (options.checkSuspiciousCode) { sharedCallbacks.add(new CheckAccidentalSemicolon(CheckLevel.WARNING)); sharedCallbacks.add(new CheckSideEffects(CheckLevel.WARNING)); } if (options.enables(DiagnosticGroups.GLOBAL_THIS)) { sharedCallbacks.add(new CheckGlobalThis(compiler)); } return combineChecks(compiler, sharedCallbacks); } }; /** Verify that all the passes are one-time passes. */ private void assertAllOneTimePasses(List<PassFactory> passes) { for (PassFactory pass : passes) { Preconditions.checkState(pass.isOneTimePass()); } } /** Verify that all the passes are multi-run passes. */ private void assertAllLoopablePasses(List<PassFactory> passes) { for (PassFactory pass : passes) { Preconditions.checkState(!pass.isOneTimePass()); } } /** Checks for validity of the control structures. */ private final HotSwapPassFactory checkControlStructures = new HotSwapPassFactory("checkControlStructures", true) { @Override protected HotSwapCompilerPass createInternal(AbstractCompiler compiler) { return new ControlStructureCheck(compiler); } }; /** Checks that all constructed classes are goog.require()d. */ private final HotSwapPassFactory checkRequires = new HotSwapPassFactory("checkRequires", true) { @Override protected HotSwapCompilerPass createInternal(AbstractCompiler compiler) { return new CheckRequiresForConstructors(compiler, options.checkRequires); } }; /** Makes sure @constructor is paired with goog.provides(). */ private final HotSwapPassFactory checkProvides = new HotSwapPassFactory("checkProvides", true) { @Override protected HotSwapCompilerPass createInternal(AbstractCompiler compiler) { return new CheckProvides(compiler, options.checkProvides); } }; private static final DiagnosticType GENERATE_EXPORTS_ERROR = DiagnosticType.error( "JSC_GENERATE_EXPORTS_ERROR", "Exports can only be generated if export symbol/property " + "functions are set."); /** Generates exports for @export annotations. */ private final PassFactory generateExports = new PassFactory("generateExports", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { CodingConvention convention = compiler.getCodingConvention(); if (convention.getExportSymbolFunction() != null && convention.getExportPropertyFunction() != null) { return new GenerateExports(compiler, convention.getExportSymbolFunction(), convention.getExportPropertyFunction()); } else { return new ErrorPass(compiler, GENERATE_EXPORTS_ERROR); } } }; /** Generates exports for functions associated with JSUnit. */ private final PassFactory exportTestFunctions = new PassFactory("exportTestFunctions", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { CodingConvention convention = compiler.getCodingConvention(); if (convention.getExportSymbolFunction() != null) { return new ExportTestFunctions(compiler, convention.getExportSymbolFunction()); } else { return new ErrorPass(compiler, GENERATE_EXPORTS_ERROR); } } }; /** Raw exports processing pass. */ final PassFactory gatherRawExports = new PassFactory("gatherRawExports", false) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { final GatherRawExports pass = new GatherRawExports( compiler); return new CompilerPass() { @Override public void process(Node externs, Node root) { pass.process(externs, root); if (exportedNames == null) { exportedNames = Sets.newHashSet(); } exportedNames.addAll(pass.getExportedVariableNames()); } }; } }; /** Closure pre-processing pass. */ @SuppressWarnings("deprecation") final HotSwapPassFactory closurePrimitives = new HotSwapPassFactory("processProvidesAndRequires", false) { @Override protected HotSwapCompilerPass createInternal(AbstractCompiler compiler) { final ProcessClosurePrimitives pass = new ProcessClosurePrimitives( compiler, options.brokenClosureRequiresLevel, options.rewriteNewDateGoogNow); return new HotSwapCompilerPass() { @Override public void process(Node externs, Node root) { pass.process(externs, root); exportedNames = pass.getExportedVariableNames(); } @Override public void hotSwapScript(Node scriptRoot) { pass.hotSwapScript(scriptRoot); } }; } }; /** * The default i18n pass. * A lot of the options are not configurable, because ReplaceMessages * has a lot of legacy logic. */ private final PassFactory replaceMessages = new PassFactory("replaceMessages", true) { @Override protected CompilerPass createInternal(final AbstractCompiler compiler) { return new ReplaceMessages(compiler, options.messageBundle, /* warn about message dupes */ true, /* allow messages with goog.getMsg */ JsMessage.Style.getFromParams(true, false), /* if we can't find a translation, don't worry about it. */ false); } }; /** Applies aliases and inlines goog.scope. */ final HotSwapPassFactory closureGoogScopeAliases = new HotSwapPassFactory("processGoogScopeAliases", true) { @Override protected HotSwapCompilerPass createInternal(AbstractCompiler compiler) { return new ScopedAliases( compiler, options.getAliasTransformationHandler()); } }; /** Checks that CSS class names are wrapped in goog.getCssName */ private final PassFactory closureCheckGetCssName = new PassFactory("checkMissingGetCssName", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { String blacklist = options.checkMissingGetCssNameBlacklist; Preconditions.checkState(blacklist != null && !blacklist.isEmpty(), "Not checking use of goog.getCssName because of empty blacklist."); return new CheckMissingGetCssName( compiler, options.checkMissingGetCssNameLevel, blacklist); } }; /** * Processes goog.getCssName. The cssRenamingMap is used to lookup * replacement values for the classnames. If null, the raw class names are * inlined. */ private final PassFactory closureReplaceGetCssName = new PassFactory("renameCssNames", true) { @Override protected CompilerPass createInternal(final AbstractCompiler compiler) { return new CompilerPass() { @Override public void process(Node externs, Node jsRoot) { Map<String, Integer> newCssNames = null; if (options.gatherCssNames) { newCssNames = Maps.newHashMap(); } (new ReplaceCssNames(compiler, newCssNames)).process( externs, jsRoot); cssNames = newCssNames; } }; } }; /** * Creates synthetic blocks to prevent FoldConstants from moving code * past markers in the source. */ private final PassFactory createSyntheticBlocks = new PassFactory("createSyntheticBlocks", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new CreateSyntheticBlocks(compiler, options.syntheticBlockStartMarker, options.syntheticBlockEndMarker); } }; /** Various peephole optimizations. */ private final PassFactory peepholeOptimizations = new PassFactory("peepholeOptimizations", false) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new PeepholeOptimizationsPass(compiler, new PeepholeSubstituteAlternateSyntax(false), new PeepholeReplaceKnownMethods(), new PeepholeRemoveDeadCode(), new PeepholeFoldConstants(), new PeepholeCollectPropertyAssignments()); } }; /** Same as peepholeOptimizations but aggressively merges code together */ private final PassFactory latePeepholeOptimizations = new PassFactory("latePeepholeOptimizations", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new PeepholeOptimizationsPass(compiler, new StatementFusion(), new PeepholeRemoveDeadCode(), new PeepholeSubstituteAlternateSyntax(true), new PeepholeReplaceKnownMethods(), new PeepholeFoldConstants()); } }; /** Checks that all variables are defined. */ private final HotSwapPassFactory checkVars = new HotSwapPassFactory("checkVars", true) { @Override protected HotSwapCompilerPass createInternal(AbstractCompiler compiler) { return new VarCheck(compiler); } }; /** Checks for RegExp references. */ private final PassFactory checkRegExp = new PassFactory("checkRegExp", true) { @Override protected CompilerPass createInternal(final AbstractCompiler compiler) { final CheckRegExp pass = new CheckRegExp(compiler); return new CompilerPass() { @Override public void process(Node externs, Node root) { pass.process(externs, root); compiler.setHasRegExpGlobalReferences( pass.isGlobalRegExpPropertiesUsed()); } }; } }; /** Checks that no vars are illegally shadowed. */ private final PassFactory checkShadowVars = new PassFactory("variableShadowDeclarationCheck", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new VariableShadowDeclarationCheck( compiler, options.checkShadowVars); } }; /** Checks that references to variables look reasonable. */ private final HotSwapPassFactory checkVariableReferences = new HotSwapPassFactory("checkVariableReferences", true) { @Override protected HotSwapCompilerPass createInternal(AbstractCompiler compiler) { return new VariableReferenceCheck( compiler, options.aggressiveVarCheck); } }; /** Pre-process goog.testing.ObjectPropertyString. */ private final PassFactory objectPropertyStringPreprocess = new PassFactory("ObjectPropertyStringPreprocess", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new ObjectPropertyStringPreprocess(compiler); } }; /** Creates a typed scope and adds types to the type registry. */ final HotSwapPassFactory resolveTypes = new HotSwapPassFactory("resolveTypes", false) { @Override protected HotSwapCompilerPass createInternal(AbstractCompiler compiler) { return new GlobalTypeResolver(compiler); } }; /** Runs type inference. */ final HotSwapPassFactory inferTypes = new HotSwapPassFactory("inferTypes", false) { @Override protected HotSwapCompilerPass createInternal(final AbstractCompiler compiler) { return new HotSwapCompilerPass() { @Override public void process(Node externs, Node root) { Preconditions.checkNotNull(topScope); Preconditions.checkNotNull(getTypedScopeCreator()); makeTypeInference(compiler).process(externs, root); } @Override public void hotSwapScript(Node scriptRoot) { makeTypeInference(compiler).inferTypes(scriptRoot); } }; } }; final HotSwapPassFactory inferJsDocInfo = new HotSwapPassFactory("inferJsDocInfo", false) { @Override protected HotSwapCompilerPass createInternal( final AbstractCompiler compiler) { return new HotSwapCompilerPass() { @Override public void process(Node externs, Node root) { Preconditions.checkNotNull(topScope); Preconditions.checkNotNull(getTypedScopeCreator()); makeInferJsDocInfo(compiler).process(externs, root); } @Override public void hotSwapScript(Node scriptRoot) { makeInferJsDocInfo(compiler).hotSwapScript(scriptRoot); } }; } }; /** Checks type usage */ private final HotSwapPassFactory checkTypes = new HotSwapPassFactory("checkTypes", false) { @Override protected HotSwapCompilerPass createInternal(final AbstractCompiler compiler) { return new HotSwapCompilerPass() { @Override public void process(Node externs, Node root) { Preconditions.checkNotNull(topScope); Preconditions.checkNotNull(getTypedScopeCreator()); TypeCheck check = makeTypeCheck(compiler); check.process(externs, root); compiler.getErrorManager().setTypedPercent(check.getTypedPercent()); } @Override public void hotSwapScript(Node scriptRoot) { makeTypeCheck(compiler).check(scriptRoot, false); } }; } }; /** * Checks possible execution paths of the program for problems: missing return * statements and dead code. */ private final HotSwapPassFactory checkControlFlow = new HotSwapPassFactory("checkControlFlow", true) { @Override protected HotSwapCompilerPass createInternal(AbstractCompiler compiler) { List<Callback> callbacks = Lists.newArrayList(); if (options.checkUnreachableCode.isOn()) { callbacks.add( new CheckUnreachableCode(compiler, options.checkUnreachableCode)); } if (options.checkMissingReturn.isOn() && options.checkTypes) { callbacks.add( new CheckMissingReturn(compiler, options.checkMissingReturn)); } return combineChecks(compiler, callbacks); } }; /** Checks access controls. Depends on type-inference. */ private final HotSwapPassFactory checkAccessControls = new HotSwapPassFactory("checkAccessControls", true) { @Override protected HotSwapCompilerPass createInternal(AbstractCompiler compiler) { return new CheckAccessControls(compiler); } }; /** Executes the given callbacks with a {@link CombinedCompilerPass}. */ private static HotSwapCompilerPass combineChecks(AbstractCompiler compiler, List<Callback> callbacks) { Preconditions.checkArgument(callbacks.size() > 0); Callback[] array = callbacks.toArray(new Callback[callbacks.size()]); return new CombinedCompilerPass(compiler, array); } /** A compiler pass that resolves types in the global scope. */ private class GlobalTypeResolver implements HotSwapCompilerPass { private final AbstractCompiler compiler; GlobalTypeResolver(AbstractCompiler compiler) { this.compiler = compiler; } @Override public void process(Node externs, Node root) { if (topScope == null) { regenerateGlobalTypedScope(compiler, root.getParent()); } else { compiler.getTypeRegistry().resolveTypesInScope(topScope); } } @Override public void hotSwapScript(Node scriptRoot) { patchGlobalTypedScope(compiler, scriptRoot); } } /** Checks global name usage. */ private final PassFactory checkGlobalNames = new PassFactory("Check names", true) { @Override protected CompilerPass createInternal(final AbstractCompiler compiler) { return new CompilerPass() { @Override public void process(Node externs, Node jsRoot) { // Create a global namespace for analysis by check passes. // Note that this class does all heavy computation lazily, // so it's OK to create it here. namespaceForChecks = new GlobalNamespace(compiler, jsRoot); new CheckGlobalNames(compiler, options.checkGlobalNamesLevel) .injectNamespace(namespaceForChecks).process(externs, jsRoot); } }; } }; /** Checks that the code is ES5 or Caja compliant. */ private final PassFactory checkStrictMode = new PassFactory("checkStrictMode", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new StrictModeCheck(compiler, !options.checkSymbols, // don't check variables twice !options.checkCaja); // disable eval check if not Caja } }; /** Process goog.tweak.getTweak() calls. */ final PassFactory processTweaks = new PassFactory("processTweaks", true) { @Override protected CompilerPass createInternal(final AbstractCompiler compiler) { return new CompilerPass() { @Override public void process(Node externs, Node jsRoot) { new ProcessTweaks(compiler, options.getTweakProcessing().shouldStrip(), options.getTweakReplacements()).process(externs, jsRoot); } }; } }; /** Override @define-annotated constants. */ final PassFactory processDefines = new PassFactory("processDefines", true) { @Override protected CompilerPass createInternal(final AbstractCompiler compiler) { return new CompilerPass() { @Override public void process(Node externs, Node jsRoot) { Map<String, Node> replacements = getAdditionalReplacements(options); replacements.putAll(options.getDefineReplacements()); new ProcessDefines(compiler, replacements) .injectNamespace(namespaceForChecks).process(externs, jsRoot); // Kill the namespace in the other class // so that it can be garbage collected after all passes // are through with it. namespaceForChecks = null; } }; } }; /** Checks that all constants are not modified */ private final PassFactory checkConsts = new PassFactory("checkConsts", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new ConstCheck(compiler); } }; /** Computes the names of functions for later analysis. */ private final PassFactory computeFunctionNames = new PassFactory("computeFunctionNames", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return ((functionNames = new FunctionNames(compiler))); } }; /** Skips Caja-private properties in for-in loops */ private final PassFactory ignoreCajaProperties = new PassFactory("ignoreCajaProperties", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new IgnoreCajaProperties(compiler); } }; /** Inserts runtime type assertions for debugging. */ private final PassFactory runtimeTypeCheck = new PassFactory("runtimeTypeCheck", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new RuntimeTypeCheck(compiler, options.runtimeTypeCheckLogFunction); } }; /** Generates unique ids. */ private final PassFactory replaceIdGenerators = new PassFactory("replaceIdGenerators", true) { @Override protected CompilerPass createInternal(final AbstractCompiler compiler) { return new CompilerPass() { @Override public void process(Node externs, Node root) { ReplaceIdGenerators pass = new ReplaceIdGenerators(compiler, options.idGenerators); pass.process(externs, root); idGeneratorMap = pass.getIdGeneratorMap(); } }; } }; /** Replace strings. */ private final PassFactory replaceStrings = new PassFactory("replaceStrings", true) { @Override protected CompilerPass createInternal(final AbstractCompiler compiler) { return new CompilerPass() { @Override public void process(Node externs, Node root) { ReplaceStrings pass = new ReplaceStrings( compiler, options.replaceStringsPlaceholderToken, options.replaceStringsFunctionDescriptions, options.replaceStringsReservedStrings); pass.process(externs, root); stringMap = pass.getStringMap(); } }; } }; /** Optimizes the "arguments" array. */ private final PassFactory optimizeArgumentsArray = new PassFactory("optimizeArgumentsArray", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new OptimizeArgumentsArray(compiler); } }; /** Remove variables set to goog.abstractMethod. */ private final PassFactory closureCodeRemoval = new PassFactory("closureCodeRemoval", true) { @Override protected CompilerPass createInternal(final AbstractCompiler compiler) { return new ClosureCodeRemoval(compiler, options.removeAbstractMethods, options.removeClosureAsserts); } }; /** Special case optimizations for closure functions. */ private final PassFactory closureOptimizePrimitives = new PassFactory("closureOptimizePrimitives", true) { @Override protected CompilerPass createInternal(final AbstractCompiler compiler) { return new ClosureOptimizePrimitives(compiler); } }; /** Collapses names in the global scope. */ private final PassFactory collapseProperties = new PassFactory("collapseProperties", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new CollapseProperties( compiler, options.collapsePropertiesOnExternTypes, !isInliningForbidden()); } }; /** Rewrite properties as variables. */ private final PassFactory collapseObjectLiterals = new PassFactory("collapseObjectLiterals", false) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new InlineObjectLiterals( compiler, compiler.getUniqueNameIdSupplier()); } }; /** * Try to infer the actual types, which may be narrower * than the declared types. */ private final PassFactory tightenTypesBuilder = new PassFactory("tightenTypes", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { if (!options.checkTypes) { return new ErrorPass(compiler, TIGHTEN_TYPES_WITHOUT_TYPE_CHECK); } tightenTypes = new TightenTypes(compiler); return tightenTypes; } }; /** Devirtualize property names based on type information. */ private final PassFactory disambiguateProperties = new PassFactory("disambiguateProperties", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { if (tightenTypes == null) { return DisambiguateProperties.forJSTypeSystem(compiler); } else { return DisambiguateProperties.forConcreteTypeSystem( compiler, tightenTypes); } } }; /** * Chain calls to functions that return this. */ private final PassFactory chainCalls = new PassFactory("chainCalls", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new ChainCalls(compiler); } }; /** * Rewrite instance methods as static methods, to make them easier * to inline. */ private final PassFactory devirtualizePrototypeMethods = new PassFactory("devirtualizePrototypeMethods", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new DevirtualizePrototypeMethods(compiler); } }; /** * Optimizes unused function arguments, unused return values, and inlines * constant parameters. Also runs RemoveUnusedVars. */ private final PassFactory optimizeCallsAndRemoveUnusedVars = new PassFactory("optimizeCalls_and_removeUnusedVars", false) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { OptimizeCalls passes = new OptimizeCalls(compiler); if (options.optimizeReturns) { // Remove unused return values. passes.addPass(new OptimizeReturns(compiler)); } if (options.optimizeParameters) { // Remove all parameters that are constants or unused. passes.addPass(new OptimizeParameters(compiler)); } if (options.optimizeCalls) { boolean removeOnlyLocals = options.removeUnusedLocalVars && !options.removeUnusedVars; boolean preserveAnonymousFunctionNames = options.anonymousFunctionNaming != AnonymousFunctionNamingPolicy.OFF; passes.addPass( new RemoveUnusedVars(compiler, !removeOnlyLocals, preserveAnonymousFunctionNames, true)); } return passes; } }; /** * Look for function calls that are pure, and annotate them * that way. */ private final PassFactory markPureFunctions = new PassFactory("markPureFunctions", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new PureFunctionIdentifier.Driver( compiler, options.debugFunctionSideEffectsPath, false); } }; /** * Look for function calls that have no side effects, and annotate them * that way. */ private final PassFactory markNoSideEffectCalls = new PassFactory("markNoSideEffectCalls", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new MarkNoSideEffectCalls(compiler); } }; /** Inlines variables heuristically. */ private final PassFactory inlineVariables = new PassFactory("inlineVariables", false) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { if (isInliningForbidden()) { // In old renaming schemes, inlining a variable can change whether // or not a property is renamed. This is bad, and those old renaming // schemes need to die. return new ErrorPass(compiler, CANNOT_USE_PROTOTYPE_AND_VAR); } else { InlineVariables.Mode mode; if (options.inlineVariables) { mode = InlineVariables.Mode.ALL; } else if (options.inlineLocalVariables) { mode = InlineVariables.Mode.LOCALS_ONLY; } else { throw new IllegalStateException("No variable inlining option set."); } return new InlineVariables(compiler, mode, true); } } }; /** Inlines variables that are marked as constants. */ private final PassFactory inlineConstants = new PassFactory("inlineConstants", false) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new InlineVariables( compiler, InlineVariables.Mode.CONSTANTS_ONLY, true); } }; /** * Perform local control flow optimizations. */ private final PassFactory minimizeExitPoints = new PassFactory("minimizeExitPoints", false) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new MinimizeExitPoints(compiler); } }; /** * Use data flow analysis to remove dead branches. */ private final PassFactory removeUnreachableCode = new PassFactory("removeUnreachableCode", false) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new UnreachableCodeElimination(compiler, true); } }; /** * Remove prototype properties that do not appear to be used. */ private final PassFactory removeUnusedPrototypeProperties = new PassFactory("removeUnusedPrototypeProperties", false) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new RemoveUnusedPrototypeProperties( compiler, options.removeUnusedPrototypePropertiesInExterns, !options.removeUnusedVars); } }; /** * Process smart name processing - removes unused classes and does referencing * starting with minimum set of names. */ private final PassFactory smartNamePass = new PassFactory("smartNamePass", true) { @Override protected CompilerPass createInternal(final AbstractCompiler compiler) { return new CompilerPass() { @Override public void process(Node externs, Node root) { NameAnalyzer na = new NameAnalyzer(compiler, false); na.process(externs, root); String reportPath = options.reportPath; if (reportPath != null) { try { Files.write(na.getHtmlReport(), new File(reportPath), Charsets.UTF_8); } catch (IOException e) { compiler.report(JSError.make(REPORT_PATH_IO_ERROR, reportPath)); } } if (options.smartNameRemoval) { na.removeUnreferenced(); } } }; } }; /** * Process smart name processing - removes unused classes and does referencing * starting with minimum set of names. */ private final PassFactory smartNamePass2 = new PassFactory("smartNamePass", true) { @Override protected CompilerPass createInternal(final AbstractCompiler compiler) { return new CompilerPass() { @Override public void process(Node externs, Node root) { NameAnalyzer na = new NameAnalyzer(compiler, false); na.process(externs, root); na.removeUnreferenced(); } }; } }; /** Inlines simple methods, like getters */ private final PassFactory inlineSimpleMethods = new PassFactory("inlineSimpleMethods", false) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new InlineSimpleMethods(compiler); } }; /** Kills dead assignments. */ private final PassFactory deadAssignmentsElimination = new PassFactory("deadAssignmentsElimination", false) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new DeadAssignmentsElimination(compiler); } }; /** Inlines function calls. */ private final PassFactory inlineFunctions = new PassFactory("inlineFunctions", false) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { boolean enableBlockInlining = !isInliningForbidden(); return new InlineFunctions( compiler, compiler.getUniqueNameIdSupplier(), options.inlineFunctions, options.inlineLocalFunctions, enableBlockInlining, options.isAssumeStrictThis() || options.getLanguageIn() == LanguageMode.ECMASCRIPT5_STRICT); } }; /** Removes variables that are never used. */ private final PassFactory removeUnusedVars = new PassFactory("removeUnusedVars", false) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { boolean removeOnlyLocals = options.removeUnusedLocalVars && !options.removeUnusedVars; boolean preserveAnonymousFunctionNames = options.anonymousFunctionNaming != AnonymousFunctionNamingPolicy.OFF; return new RemoveUnusedVars( compiler, !removeOnlyLocals, preserveAnonymousFunctionNames, false); } }; /** * Move global symbols to a deeper common module */ private final PassFactory crossModuleCodeMotion = new PassFactory("crossModuleCodeMotion", false) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new CrossModuleCodeMotion(compiler, compiler.getModuleGraph()); } }; /** * Move methods to a deeper common module */ private final PassFactory crossModuleMethodMotion = new PassFactory("crossModuleMethodMotion", false) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new CrossModuleMethodMotion( compiler, crossModuleIdGenerator, // Only move properties in externs if we're not treating // them as exports. options.removeUnusedPrototypePropertiesInExterns); } }; /** * Specialize the initial module at the cost of later modules */ private final PassFactory specializeInitialModule = new PassFactory("specializeInitialModule", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new SpecializeModule(compiler, devirtualizePrototypeMethods, inlineFunctions, removeUnusedPrototypeProperties); } }; /** A data-flow based variable inliner. */ private final PassFactory flowSensitiveInlineVariables = new PassFactory("flowSensitiveInlineVariables", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new FlowSensitiveInlineVariables(compiler); } }; /** Uses register-allocation algorithms to use fewer variables. */ private final PassFactory coalesceVariableNames = new PassFactory("coalesceVariableNames", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new CoalesceVariableNames(compiler, options.generatePseudoNames); } }; /** * Some simple, local collapses (e.g., {@code var x; var y;} becomes * {@code var x,y;}. */ private final PassFactory exploitAssign = new PassFactory("expointAssign", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new PeepholeOptimizationsPass(compiler, new ExploitAssigns()); } }; /** * Some simple, local collapses (e.g., {@code var x; var y;} becomes * {@code var x,y;}. */ private final PassFactory collapseVariableDeclarations = new PassFactory("collapseVariableDeclarations", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new CollapseVariableDeclarations(compiler); } }; /** * Simple global collapses of variable declarations. */ private final PassFactory groupVariableDeclarations = new PassFactory("groupVariableDeclarations", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new GroupVariableDeclarations(compiler); } }; /** * Extracts common sub-expressions. */ private final PassFactory extractPrototypeMemberDeclarations = new PassFactory("extractPrototypeMemberDeclarations", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new ExtractPrototypeMemberDeclarations(compiler); } }; /** Rewrites common function definitions to be more compact. */ private final PassFactory rewriteFunctionExpressions = new PassFactory("rewriteFunctionExpressions", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new FunctionRewriter(compiler); } }; /** Collapses functions to not use the VAR keyword. */ private final PassFactory collapseAnonymousFunctions = new PassFactory("collapseAnonymousFunctions", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new CollapseAnonymousFunctions(compiler); } }; /** Moves function declarations to the top, to simulate actual hoisting. */ private final PassFactory moveFunctionDeclarations = new PassFactory("moveFunctionDeclarations", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new MoveFunctionDeclarations(compiler); } }; private final PassFactory nameUnmappedAnonymousFunctions = new PassFactory("nameAnonymousFunctions", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new NameAnonymousFunctions(compiler); } }; private final PassFactory nameMappedAnonymousFunctions = new PassFactory("nameAnonymousFunctions", true) { @Override protected CompilerPass createInternal(final AbstractCompiler compiler) { return new CompilerPass() { @Override public void process(Node externs, Node root) { NameAnonymousFunctionsMapped naf = new NameAnonymousFunctionsMapped(compiler); naf.process(externs, root); anonymousFunctionNameMap = naf.getFunctionMap(); } }; } }; private final PassFactory operaCompoundAssignFix = new PassFactory("operaCompoundAssignFix", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new OperaCompoundAssignFix(compiler); } }; /** Alias external symbols. */ private final PassFactory aliasExternals = new PassFactory("aliasExternals", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new AliasExternals(compiler, compiler.getModuleGraph(), options.unaliasableGlobals, options.aliasableGlobals); } }; /** * Alias string literals with global variables, to avoid creating lots of * transient objects. */ private final PassFactory aliasStrings = new PassFactory("aliasStrings", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new AliasStrings( compiler, compiler.getModuleGraph(), options.aliasAllStrings ? null : options.aliasableStrings, options.aliasStringsBlacklist, options.outputJsStringUsage); } }; /** Aliases common keywords (true, false) */ private final PassFactory aliasKeywords = new PassFactory("aliasKeywords", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new AliasKeywords(compiler); } }; /** Handling for the ObjectPropertyString primitive. */ private final PassFactory objectPropertyStringPostprocess = new PassFactory("ObjectPropertyStringPostprocess", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new ObjectPropertyStringPostprocess(compiler); } }; /** * Renames properties so that the two properties that never appear on * the same object get the same name. */ private final PassFactory ambiguateProperties = new PassFactory("ambiguateProperties", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new AmbiguateProperties( compiler, options.anonymousFunctionNaming.getReservedCharacters()); } }; /** * Mark the point at which the normalized AST assumptions no longer hold. */ private final PassFactory markUnnormalized = new PassFactory("markUnnormalized", true) { @Override protected CompilerPass createInternal(final AbstractCompiler compiler) { return new CompilerPass() { @Override public void process(Node externs, Node root) { compiler.setLifeCycleStage(LifeCycleStage.RAW); } }; } }; /** Denormalize the AST for code generation. */ private final PassFactory denormalize = new PassFactory("denormalize", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new Denormalize(compiler); } }; /** Inverting name normalization. */ private final PassFactory invertContextualRenaming = new PassFactory("invertNames", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return MakeDeclaredNamesUnique.getContextualRenameInverter(compiler); } }; /** * Renames properties. */ private final PassFactory renameProperties = new PassFactory("renameProperties", true) { @Override protected CompilerPass createInternal(final AbstractCompiler compiler) { VariableMap map = null; if (options.inputPropertyMapSerialized != null) { try { map = VariableMap.fromBytes(options.inputPropertyMapSerialized); } catch (ParseException e) { return new ErrorPass(compiler, JSError.make(INPUT_MAP_PROP_PARSE, e.getMessage())); } } final VariableMap prevPropertyMap = map; return new CompilerPass() { @Override public void process(Node externs, Node root) { propertyMap = runPropertyRenaming( compiler, prevPropertyMap, externs, root); } }; } }; private VariableMap runPropertyRenaming( AbstractCompiler compiler, VariableMap prevPropertyMap, Node externs, Node root) { char[] reservedChars = options.anonymousFunctionNaming.getReservedCharacters(); switch (options.propertyRenaming) { case HEURISTIC: RenamePrototypes rproto = new RenamePrototypes(compiler, false, reservedChars, prevPropertyMap); rproto.process(externs, root); return rproto.getPropertyMap(); case AGGRESSIVE_HEURISTIC: RenamePrototypes rproto2 = new RenamePrototypes(compiler, true, reservedChars, prevPropertyMap); rproto2.process(externs, root); return rproto2.getPropertyMap(); case ALL_UNQUOTED: RenameProperties rprop = new RenameProperties( compiler, options.propertyAffinity, options.generatePseudoNames, prevPropertyMap, reservedChars); rprop.process(externs, root); return rprop.getPropertyMap(); default: throw new IllegalStateException( "Unrecognized property renaming policy"); } } /** Renames variables. */ private final PassFactory renameVars = new PassFactory("renameVars", true) { @Override protected CompilerPass createInternal(final AbstractCompiler compiler) { VariableMap map = null; if (options.inputVariableMapSerialized != null) { try { map = VariableMap.fromBytes(options.inputVariableMapSerialized); } catch (ParseException e) { return new ErrorPass(compiler, JSError.make(INPUT_MAP_VAR_PARSE, e.getMessage())); } } final VariableMap prevVariableMap = map; return new CompilerPass() { @Override public void process(Node externs, Node root) { variableMap = runVariableRenaming( compiler, prevVariableMap, externs, root); } }; } }; private VariableMap runVariableRenaming( AbstractCompiler compiler, VariableMap prevVariableMap, Node externs, Node root) { char[] reservedChars = options.anonymousFunctionNaming.getReservedCharacters(); boolean preserveAnonymousFunctionNames = options.anonymousFunctionNaming != AnonymousFunctionNamingPolicy.OFF; RenameVars rn = new RenameVars( compiler, options.renamePrefix, options.variableRenaming == VariableRenamingPolicy.LOCAL, preserveAnonymousFunctionNames, options.generatePseudoNames, options.shadowVariables, prevVariableMap, reservedChars, exportedNames); rn.process(externs, root); return rn.getVariableMap(); } /** Renames labels */ private final PassFactory renameLabels = new PassFactory("renameLabels", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new RenameLabels(compiler); } }; /** Convert bracket access to dot access */ private final PassFactory convertToDottedProperties = new PassFactory("convertToDottedProperties", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new ConvertToDottedProperties(compiler); } }; /** Checks that all variables are defined. */ private final PassFactory sanityCheckAst = new PassFactory("sanityCheckAst", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new AstValidator(); } }; /** Checks that all variables are defined. */ private final PassFactory sanityCheckVars = new PassFactory("sanityCheckVars", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new VarCheck(compiler, true); } }; /** Adds instrumentations according to an instrumentation template. */ private final PassFactory instrumentFunctions = new PassFactory("instrumentFunctions", true) { @Override protected CompilerPass createInternal(final AbstractCompiler compiler) { return new CompilerPass() { @Override public void process(Node externs, Node root) { try { FileReader templateFile = new FileReader(options.instrumentationTemplate); (new InstrumentFunctions( compiler, functionNames, options.instrumentationTemplate, options.appNameStr, templateFile)).process(externs, root); } catch (IOException e) { compiler.report( JSError.make(AbstractCompiler.READ_ERROR, options.instrumentationTemplate)); } } }; } }; /** * Create a no-op pass that can only run once. Used to break up loops. */ private static PassFactory createEmptyPass(String name) { return new PassFactory(name, true) { @Override protected CompilerPass createInternal(final AbstractCompiler compiler) { return runInSerial(); } }; } /** * Runs custom passes that are designated to run at a particular time. */ private PassFactory getCustomPasses( final CustomPassExecutionTime executionTime) { return new PassFactory("runCustomPasses", true) { @Override protected CompilerPass createInternal(final AbstractCompiler compiler) { return runInSerial(options.customPasses.get(executionTime)); } }; } /** * All inlining is forbidden in heuristic renaming mode, because inlining * will ruin the invariants that it depends on. */ private boolean isInliningForbidden() { return options.propertyRenaming == PropertyRenamingPolicy.HEURISTIC || options.propertyRenaming == PropertyRenamingPolicy.AGGRESSIVE_HEURISTIC; } /** Create a compiler pass that runs the given passes in serial. */ private static CompilerPass runInSerial(final CompilerPass ... passes) { return runInSerial(Lists.newArrayList(passes)); } /** Create a compiler pass that runs the given passes in serial. */ private static CompilerPass runInSerial( final Collection<CompilerPass> passes) { return new CompilerPass() { @Override public void process(Node externs, Node root) { for (CompilerPass pass : passes) { pass.process(externs, root); } } }; } @VisibleForTesting static Map<String, Node> getAdditionalReplacements( CompilerOptions options) { Map<String, Node> additionalReplacements = Maps.newHashMap(); if (options.markAsCompiled || options.closurePass) { additionalReplacements.put(COMPILED_CONSTANT_NAME, new Node(Token.TRUE)); } if (options.closurePass && options.locale != null) { additionalReplacements.put(CLOSURE_LOCALE_CONSTANT_NAME, Node.newString(options.locale)); } return additionalReplacements; } private final PassFactory printNameReferenceGraph = new PassFactory("printNameReferenceGraph", true) { @Override protected CompilerPass createInternal(final AbstractCompiler compiler) { return new CompilerPass() { @Override public void process(Node externs, Node jsRoot) { NameReferenceGraphConstruction gc = new NameReferenceGraphConstruction(compiler); gc.process(externs, jsRoot); String graphFileName = options.nameReferenceGraphPath; try { Files.write(DotFormatter.toDot(gc.getNameReferenceGraph()), new File(graphFileName), Charsets.UTF_8); } catch (IOException e) { compiler.report( JSError.make( NAME_REF_GRAPH_FILE_ERROR, e.getMessage(), graphFileName)); } } }; } }; private final PassFactory printNameReferenceReport = new PassFactory("printNameReferenceReport", true) { @Override protected CompilerPass createInternal(final AbstractCompiler compiler) { return new CompilerPass() { @Override public void process(Node externs, Node jsRoot) { NameReferenceGraphConstruction gc = new NameReferenceGraphConstruction(compiler); String reportFileName = options.nameReferenceReportPath; try { NameReferenceGraphReport report = new NameReferenceGraphReport(gc.getNameReferenceGraph()); Files.write(report.getHtmlReport(), new File(reportFileName), Charsets.UTF_8); } catch (IOException e) { compiler.report( JSError.make( NAME_REF_REPORT_FILE_ERROR, e.getMessage(), reportFileName)); } } }; } }; /** * A pass-factory that is good for {@code HotSwapCompilerPass} passes. */ abstract static class HotSwapPassFactory extends PassFactory { HotSwapPassFactory(String name, boolean isOneTimePass) { super(name, isOneTimePass); } @Override protected abstract HotSwapCompilerPass createInternal(AbstractCompiler compiler); @Override HotSwapCompilerPass getHotSwapPass(AbstractCompiler compiler) { return this.createInternal(compiler); } } }
src/com/google/javascript/jscomp/DefaultPassConfig.java
/* * Copyright 2009 The Closure Compiler 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 com.google.javascript.jscomp; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Charsets; import com.google.common.base.Preconditions; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.google.common.io.Files; import com.google.javascript.jscomp.AbstractCompiler.LifeCycleStage; import com.google.javascript.jscomp.CompilerOptions.LanguageMode; import com.google.javascript.jscomp.NodeTraversal.Callback; import com.google.javascript.rhino.Node; import com.google.javascript.rhino.Token; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.text.ParseException; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; /** * Pass factories and meta-data for native JSCompiler passes. * * @author [email protected] (Nick Santos) */ // TODO(nicksantos): This needs state for a variety of reasons. Some of it // is to satisfy the existing API. Some of it is because passes really do // need to share state in non-trivial ways. This should be audited and // cleaned up. public class DefaultPassConfig extends PassConfig { /* For the --mark-as-compiled pass */ private static final String COMPILED_CONSTANT_NAME = "COMPILED"; /* Constant name for Closure's locale */ private static final String CLOSURE_LOCALE_CONSTANT_NAME = "goog.LOCALE"; // Compiler errors when invalid combinations of passes are run. static final DiagnosticType TIGHTEN_TYPES_WITHOUT_TYPE_CHECK = DiagnosticType.error("JSC_TIGHTEN_TYPES_WITHOUT_TYPE_CHECK", "TightenTypes requires type checking. Please use --check_types."); static final DiagnosticType CANNOT_USE_PROTOTYPE_AND_VAR = DiagnosticType.error("JSC_CANNOT_USE_PROTOTYPE_AND_VAR", "Rename prototypes and inline variables cannot be used together"); // Miscellaneous errors. static final DiagnosticType REPORT_PATH_IO_ERROR = DiagnosticType.error("JSC_REPORT_PATH_IO_ERROR", "Error writing compiler report to {0}"); private static final DiagnosticType INPUT_MAP_PROP_PARSE = DiagnosticType.error("JSC_INPUT_MAP_PROP_PARSE", "Input property map parse error: {0}"); private static final DiagnosticType INPUT_MAP_VAR_PARSE = DiagnosticType.error("JSC_INPUT_MAP_VAR_PARSE", "Input variable map parse error: {0}"); private static final DiagnosticType NAME_REF_GRAPH_FILE_ERROR = DiagnosticType.error("JSC_NAME_REF_GRAPH_FILE_ERROR", "Error \"{1}\" writing name reference graph to \"{0}\"."); private static final DiagnosticType NAME_REF_REPORT_FILE_ERROR = DiagnosticType.error("JSC_NAME_REF_REPORT_FILE_ERROR", "Error \"{1}\" writing name reference report to \"{0}\"."); /** * A global namespace to share across checking passes. * TODO(nicksantos): This is a hack until I can get the namespace into * the symbol table. */ private GlobalNamespace namespaceForChecks = null; /** * A type-tightener to share across optimization passes. */ private TightenTypes tightenTypes = null; /** Names exported by goog.exportSymbol. */ private Set<String> exportedNames = null; /** * Ids for cross-module method stubbing, so that each method has * a unique id. */ private CrossModuleMethodMotion.IdGenerator crossModuleIdGenerator = new CrossModuleMethodMotion.IdGenerator(); /** * Keys are arguments passed to getCssName() found during compilation; values * are the number of times the key appeared as an argument to getCssName(). */ private Map<String, Integer> cssNames = null; /** The variable renaming map */ private VariableMap variableMap = null; /** The property renaming map */ private VariableMap propertyMap = null; /** The naming map for anonymous functions */ private VariableMap anonymousFunctionNameMap = null; /** Fully qualified function names and globally unique ids */ private FunctionNames functionNames = null; /** String replacement map */ private VariableMap stringMap = null; /** Id generator map */ private String idGeneratorMap = null; public DefaultPassConfig(CompilerOptions options) { super(options); } @Override State getIntermediateState() { return new State( cssNames == null ? null : Maps.newHashMap(cssNames), exportedNames == null ? null : Collections.unmodifiableSet(exportedNames), crossModuleIdGenerator, variableMap, propertyMap, anonymousFunctionNameMap, stringMap, functionNames, idGeneratorMap); } @Override void setIntermediateState(State state) { this.cssNames = state.cssNames == null ? null : Maps.newHashMap(state.cssNames); this.exportedNames = state.exportedNames == null ? null : Sets.newHashSet(state.exportedNames); this.crossModuleIdGenerator = state.crossModuleIdGenerator; this.variableMap = state.variableMap; this.propertyMap = state.propertyMap; this.anonymousFunctionNameMap = state.anonymousFunctionNameMap; this.stringMap = state.stringMap; this.functionNames = state.functionNames; this.idGeneratorMap = state.idGeneratorMap; } @Override protected List<PassFactory> getChecks() { List<PassFactory> checks = Lists.newArrayList(); if (options.closurePass) { checks.add(closureGoogScopeAliases); } if (options.nameAnonymousFunctionsOnly) { if (options.anonymousFunctionNaming == AnonymousFunctionNamingPolicy.MAPPED) { checks.add(nameMappedAnonymousFunctions); } else if (options.anonymousFunctionNaming == AnonymousFunctionNamingPolicy.UNMAPPED) { checks.add(nameUnmappedAnonymousFunctions); } return checks; } if (options.checkSuspiciousCode || options.enables(DiagnosticGroups.GLOBAL_THIS)) { checks.add(suspiciousCode); } if (options.checkControlStructures) { checks.add(checkControlStructures); } if (options.checkRequires.isOn()) { checks.add(checkRequires); } if (options.checkProvides.isOn()) { checks.add(checkProvides); } // The following passes are more like "preprocessor" passes. // It's important that they run before most checking passes. // Perhaps this method should be renamed? if (options.generateExports) { checks.add(generateExports); } if (options.exportTestFunctions) { checks.add(exportTestFunctions); } if (options.closurePass) { checks.add(closurePrimitives.makeOneTimePass()); } if (options.closurePass && options.checkMissingGetCssNameLevel.isOn()) { checks.add(closureCheckGetCssName); } if (options.syntheticBlockStartMarker != null) { // This pass must run before the first fold constants pass. checks.add(createSyntheticBlocks); } checks.add(checkVars); if (options.computeFunctionSideEffects) { checks.add(checkRegExp); } if (options.checkShadowVars.isOn()) { checks.add(checkShadowVars); } if (options.aggressiveVarCheck.isOn()) { checks.add(checkVariableReferences); } // This pass should run before types are assigned. if (options.processObjectPropertyString) { checks.add(objectPropertyStringPreprocess); } if (options.checkTypes || options.inferTypes) { checks.add(resolveTypes.makeOneTimePass()); checks.add(inferTypes.makeOneTimePass()); if (options.checkTypes) { checks.add(checkTypes.makeOneTimePass()); } else { checks.add(inferJsDocInfo.makeOneTimePass()); } } if (options.checkUnreachableCode.isOn() || (options.checkTypes && options.checkMissingReturn.isOn())) { checks.add(checkControlFlow); } // CheckAccessControls only works if check types is on. if (options.checkTypes && (options.enables(DiagnosticGroups.ACCESS_CONTROLS) || options.enables(DiagnosticGroups.CONSTANT_PROPERTY))) { checks.add(checkAccessControls); } if (options.checkGlobalNamesLevel.isOn()) { checks.add(checkGlobalNames); } if (options.getLanguageIn() == LanguageMode.ECMASCRIPT5_STRICT || options.checkCaja || options.checkEs5Strict) { checks.add(checkStrictMode); } // Replace 'goog.getCssName' before processing defines but after the // other checks have been done. if (options.closurePass) { checks.add(closureReplaceGetCssName); } // i18n // If you want to customize the compiler to use a different i18n pass, // you can create a PassConfig that calls replacePassFactory // to replace this. checks.add(options.messageBundle != null ? replaceMessages : createEmptyPass("replaceMessages")); if (options.getTweakProcessing().isOn()) { checks.add(processTweaks); } // Defines in code always need to be processed. checks.add(processDefines); if (options.instrumentationTemplate != null || options.recordFunctionInformation) { checks.add(computeFunctionNames); } if (options.nameReferenceGraphPath != null && !options.nameReferenceGraphPath.isEmpty()) { checks.add(printNameReferenceGraph); } if (options.nameReferenceReportPath != null && !options.nameReferenceReportPath.isEmpty()) { checks.add(printNameReferenceReport); } assertAllOneTimePasses(checks); return checks; } @Override protected List<PassFactory> getOptimizations() { List<PassFactory> passes = Lists.newArrayList(); // TODO(nicksantos): The order of these passes makes no sense, and needs // to be re-arranged. if (options.runtimeTypeCheck) { passes.add(runtimeTypeCheck); } passes.add(createEmptyPass("beforeStandardOptimizations")); if (!options.idGenerators.isEmpty()) { passes.add(replaceIdGenerators); } // Optimizes references to the arguments variable. if (options.optimizeArgumentsArray) { passes.add(optimizeArgumentsArray); } // Abstract method removal works best on minimally modified code, and also // only needs to run once. if (options.closurePass && (options.removeAbstractMethods || options.removeClosureAsserts)) { passes.add(closureCodeRemoval); } // Collapsing properties can undo constant inlining, so we do this before // the main optimization loop. if (options.collapseProperties) { passes.add(collapseProperties); } // ReplaceStrings runs after CollapseProperties in order to simplify // pulling in values of constants defined in enums structures. if (!options.replaceStringsFunctionDescriptions.isEmpty()) { passes.add(replaceStrings); } // Tighten types based on actual usage. if (options.tightenTypes) { passes.add(tightenTypesBuilder); } // Property disambiguation should only run once and needs to be done // soon after type checking, both so that it can make use of type // information and so that other passes can take advantage of the renamed // properties. if (options.disambiguateProperties) { passes.add(disambiguateProperties); } if (options.computeFunctionSideEffects) { passes.add(markPureFunctions); } else if (options.markNoSideEffectCalls) { // TODO(user) The properties that this pass adds to CALL and NEW // AST nodes increase the AST's in-memory size. Given that we are // already running close to our memory limits, we could run into // trouble if we end up using the @nosideeffects annotation a lot // or compute @nosideeffects annotations by looking at function // bodies. It should be easy to propagate @nosideeffects // annotations as part of passes that depend on this property and // store the result outside the AST (which would allow garbage // collection once the pass is done). passes.add(markNoSideEffectCalls); } if (options.chainCalls) { passes.add(chainCalls); } // Constant checking must be done after property collapsing because // property collapsing can introduce new constants (e.g. enum values). if (options.inlineConstantVars) { passes.add(checkConsts); } // The Caja library adds properties to Object.prototype, which breaks // most for-in loops. This adds a check to each loop that skips // any property matching /___$/. if (options.ignoreCajaProperties) { passes.add(ignoreCajaProperties); } assertAllOneTimePasses(passes); if (options.smartNameRemoval || options.reportPath != null) { passes.addAll(getCodeRemovingPasses()); passes.add(smartNamePass); } // This needs to come after the inline constants pass, which is run within // the code removing passes. if (options.closurePass) { passes.add(closureOptimizePrimitives); } // TODO(user): This forces a first crack at crossModuleCodeMotion // before devirtualization. Once certain functions are devirtualized, // it confuses crossModuleCodeMotion ability to recognized that // it is recursive. // TODO(user): This is meant for a temporary quick win. // In the future, we might want to improve our analysis in // CrossModuleCodeMotion so we don't need to do this. if (options.crossModuleCodeMotion) { passes.add(crossModuleCodeMotion); } // Method devirtualization benefits from property disambiguiation so // it should run after that pass but before passes that do // optimizations based on global names (like cross module code motion // and inline functions). Smart Name Removal does better if run before // this pass. if (options.devirtualizePrototypeMethods) { passes.add(devirtualizePrototypeMethods); } if (options.customPasses != null) { passes.add(getCustomPasses( CustomPassExecutionTime.BEFORE_OPTIMIZATION_LOOP)); } passes.add(createEmptyPass("beforeMainOptimizations")); if (options.specializeInitialModule) { // When specializing the initial module, we want our fixups to be // as lean as possible, so we run the entire optimization loop to a // fixed point before specializing, then specialize, and then run the // main optimization loop again. passes.addAll(getMainOptimizationLoop()); if (options.crossModuleCodeMotion) { passes.add(crossModuleCodeMotion); } if (options.crossModuleMethodMotion) { passes.add(crossModuleMethodMotion); } passes.add(specializeInitialModule.makeOneTimePass()); } passes.addAll(getMainOptimizationLoop()); passes.add(createEmptyPass("beforeModuleMotion")); if (options.crossModuleCodeMotion) { passes.add(crossModuleCodeMotion); } if (options.crossModuleMethodMotion) { passes.add(crossModuleMethodMotion); } passes.add(createEmptyPass("afterModuleMotion")); // Some optimizations belong outside the loop because running them more // than once would either have no benefit or be incorrect. if (options.customPasses != null) { passes.add(getCustomPasses( CustomPassExecutionTime.AFTER_OPTIMIZATION_LOOP)); } if (options.flowSensitiveInlineVariables) { passes.add(flowSensitiveInlineVariables); // After inlining some of the variable uses, some variables are unused. // Re-run remove unused vars to clean it up. if (options.removeUnusedVars) { passes.add(removeUnusedVars); } } // Running this pass again is required to have goog.events compile down to // nothing when compiled on its own. if (options.smartNameRemoval) { passes.add(smartNamePass2); } if (options.collapseAnonymousFunctions) { passes.add(collapseAnonymousFunctions); } // Move functions before extracting prototype member declarations. if (options.moveFunctionDeclarations) { passes.add(moveFunctionDeclarations); } if (options.anonymousFunctionNaming == AnonymousFunctionNamingPolicy.MAPPED) { passes.add(nameMappedAnonymousFunctions); } // The mapped name anonymous function pass makes use of information that // the extract prototype member declarations pass removes so the former // happens before the latter. // // Extracting prototype properties screws up the heuristic renaming // policies, so never run it when those policies are requested. if (options.extractPrototypeMemberDeclarations && (options.propertyRenaming != PropertyRenamingPolicy.HEURISTIC && options.propertyRenaming != PropertyRenamingPolicy.AGGRESSIVE_HEURISTIC)) { passes.add(extractPrototypeMemberDeclarations); } if (options.ambiguateProperties && (options.propertyRenaming == PropertyRenamingPolicy.ALL_UNQUOTED)) { passes.add(ambiguateProperties); } if (options.propertyRenaming != PropertyRenamingPolicy.OFF) { passes.add(renameProperties); } // Reserve global names added to the "windows" object. if (options.reserveRawExports) { passes.add(gatherRawExports); } // This comes after property renaming because quoted property names must // not be renamed. if (options.convertToDottedProperties) { passes.add(convertToDottedProperties); } // Property renaming must happen before this pass runs since this // pass may convert dotted properties into quoted properties. It // is beneficial to run before alias strings, alias keywords and // variable renaming. if (options.rewriteFunctionExpressions) { passes.add(rewriteFunctionExpressions); } // This comes after converting quoted property accesses to dotted property // accesses in order to avoid aliasing property names. if (!options.aliasableStrings.isEmpty() || options.aliasAllStrings) { passes.add(aliasStrings); } if (options.aliasExternals) { passes.add(aliasExternals); } if (options.aliasKeywords) { passes.add(aliasKeywords); } // Passes after this point can no longer depend on normalized AST // assumptions. passes.add(markUnnormalized); if (options.coalesceVariableNames) { passes.add(coalesceVariableNames); // coalesceVariables creates identity assignments and more redundant code // that can be removed, rerun the peephole optimizations to clean them // up. if (options.foldConstants) { passes.add(peepholeOptimizations); } } if (options.collapseVariableDeclarations) { passes.add(exploitAssign); passes.add(collapseVariableDeclarations); } // This pass works best after collapseVariableDeclarations. passes.add(denormalize); if (options.instrumentationTemplate != null) { passes.add(instrumentFunctions); } if (options.variableRenaming != VariableRenamingPolicy.ALL) { // If we're leaving some (or all) variables with their old names, // then we need to undo any of the markers we added for distinguishing // local variables ("$$1"). passes.add(invertContextualRenaming); } if (options.variableRenaming != VariableRenamingPolicy.OFF) { passes.add(renameVars); } if (options.groupVariableDeclarations) { passes.add(groupVariableDeclarations); } // This pass should run after names stop changing. if (options.processObjectPropertyString) { passes.add(objectPropertyStringPostprocess); } if (options.labelRenaming) { passes.add(renameLabels); } if (options.foldConstants) { passes.add(latePeepholeOptimizations); } if (options.anonymousFunctionNaming == AnonymousFunctionNamingPolicy.UNMAPPED) { passes.add(nameUnmappedAnonymousFunctions); } if (options.operaCompoundAssignFix) { passes.add(operaCompoundAssignFix); } // Safety checks passes.add(sanityCheckAst); passes.add(sanityCheckVars); return passes; } /** Creates the passes for the main optimization loop. */ private List<PassFactory> getMainOptimizationLoop() { List<PassFactory> passes = Lists.newArrayList(); if (options.inlineGetters) { passes.add(inlineSimpleMethods); } passes.addAll(getCodeRemovingPasses()); if (options.inlineFunctions || options.inlineLocalFunctions) { passes.add(inlineFunctions); } boolean runOptimizeCalls = options.optimizeCalls || options.optimizeParameters || options.optimizeReturns; if (options.removeUnusedVars || options.removeUnusedLocalVars) { if (options.deadAssignmentElimination) { passes.add(deadAssignmentsElimination); } if (!runOptimizeCalls) { passes.add(removeUnusedVars); } } if (runOptimizeCalls) { passes.add(optimizeCallsAndRemoveUnusedVars); } assertAllLoopablePasses(passes); return passes; } /** Creates several passes aimed at removing code. */ private List<PassFactory> getCodeRemovingPasses() { List<PassFactory> passes = Lists.newArrayList(); if (options.collapseObjectLiterals && !isInliningForbidden()) { passes.add(collapseObjectLiterals); } if (options.inlineVariables || options.inlineLocalVariables) { passes.add(inlineVariables); } else if (options.inlineConstantVars) { passes.add(inlineConstants); } if (options.foldConstants) { // These used to be one pass. passes.add(minimizeExitPoints); passes.add(peepholeOptimizations); } if (options.removeDeadCode) { passes.add(removeUnreachableCode); } if (options.removeUnusedPrototypeProperties) { passes.add(removeUnusedPrototypeProperties); } assertAllLoopablePasses(passes); return passes; } /** * Checks for code that is probably wrong (such as stray expressions). */ // TODO(bolinfest): Write a CompilerPass for this. final HotSwapPassFactory suspiciousCode = new HotSwapPassFactory("suspiciousCode", true) { @Override protected HotSwapCompilerPass createInternal(final AbstractCompiler compiler) { List<Callback> sharedCallbacks = Lists.newArrayList(); if (options.checkSuspiciousCode) { sharedCallbacks.add(new CheckAccidentalSemicolon(CheckLevel.WARNING)); sharedCallbacks.add(new CheckSideEffects(CheckLevel.WARNING)); } if (options.enables(DiagnosticGroups.GLOBAL_THIS)) { sharedCallbacks.add(new CheckGlobalThis(compiler)); } return combineChecks(compiler, sharedCallbacks); } }; /** Verify that all the passes are one-time passes. */ private void assertAllOneTimePasses(List<PassFactory> passes) { for (PassFactory pass : passes) { Preconditions.checkState(pass.isOneTimePass()); } } /** Verify that all the passes are multi-run passes. */ private void assertAllLoopablePasses(List<PassFactory> passes) { for (PassFactory pass : passes) { Preconditions.checkState(!pass.isOneTimePass()); } } /** Checks for validity of the control structures. */ final HotSwapPassFactory checkControlStructures = new HotSwapPassFactory("checkControlStructures", true) { @Override protected HotSwapCompilerPass createInternal(AbstractCompiler compiler) { return new ControlStructureCheck(compiler); } }; /** Checks that all constructed classes are goog.require()d. */ final HotSwapPassFactory checkRequires = new HotSwapPassFactory("checkRequires", true) { @Override protected HotSwapCompilerPass createInternal(AbstractCompiler compiler) { return new CheckRequiresForConstructors(compiler, options.checkRequires); } }; /** Makes sure @constructor is paired with goog.provides(). */ final HotSwapPassFactory checkProvides = new HotSwapPassFactory("checkProvides", true) { @Override protected HotSwapCompilerPass createInternal(AbstractCompiler compiler) { return new CheckProvides(compiler, options.checkProvides); } }; private static final DiagnosticType GENERATE_EXPORTS_ERROR = DiagnosticType.error( "JSC_GENERATE_EXPORTS_ERROR", "Exports can only be generated if export symbol/property " + "functions are set."); /** Generates exports for @export annotations. */ final PassFactory generateExports = new PassFactory("generateExports", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { CodingConvention convention = compiler.getCodingConvention(); if (convention.getExportSymbolFunction() != null && convention.getExportPropertyFunction() != null) { return new GenerateExports(compiler, convention.getExportSymbolFunction(), convention.getExportPropertyFunction()); } else { return new ErrorPass(compiler, GENERATE_EXPORTS_ERROR); } } }; /** Generates exports for functions associated with JSUnit. */ final PassFactory exportTestFunctions = new PassFactory("exportTestFunctions", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { CodingConvention convention = compiler.getCodingConvention(); if (convention.getExportSymbolFunction() != null) { return new ExportTestFunctions(compiler, convention.getExportSymbolFunction()); } else { return new ErrorPass(compiler, GENERATE_EXPORTS_ERROR); } } }; /** Raw exports processing pass. */ final PassFactory gatherRawExports = new PassFactory("gatherRawExports", false) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { final GatherRawExports pass = new GatherRawExports( compiler); return new CompilerPass() { @Override public void process(Node externs, Node root) { pass.process(externs, root); if (exportedNames == null) { exportedNames = Sets.newHashSet(); } exportedNames.addAll(pass.getExportedVariableNames()); } }; } }; /** Closure pre-processing pass. */ @SuppressWarnings("deprecation") final HotSwapPassFactory closurePrimitives = new HotSwapPassFactory("processProvidesAndRequires", false) { @Override protected HotSwapCompilerPass createInternal(AbstractCompiler compiler) { final ProcessClosurePrimitives pass = new ProcessClosurePrimitives( compiler, options.brokenClosureRequiresLevel, options.rewriteNewDateGoogNow); return new HotSwapCompilerPass() { @Override public void process(Node externs, Node root) { pass.process(externs, root); exportedNames = pass.getExportedVariableNames(); } @Override public void hotSwapScript(Node scriptRoot) { pass.hotSwapScript(scriptRoot); } }; } }; /** * The default i18n pass. * A lot of the options are not configurable, because ReplaceMessages * has a lot of legacy logic. */ final PassFactory replaceMessages = new PassFactory("replaceMessages", true) { @Override protected CompilerPass createInternal(final AbstractCompiler compiler) { return new ReplaceMessages(compiler, options.messageBundle, /* warn about message dupes */ true, /* allow messages with goog.getMsg */ JsMessage.Style.getFromParams(true, false), /* if we can't find a translation, don't worry about it. */ false); } }; /** Applies aliases and inlines goog.scope. */ final HotSwapPassFactory closureGoogScopeAliases = new HotSwapPassFactory("processGoogScopeAliases", true) { @Override protected HotSwapCompilerPass createInternal(AbstractCompiler compiler) { return new ScopedAliases( compiler, options.getAliasTransformationHandler()); } }; /** Checks that CSS class names are wrapped in goog.getCssName */ final PassFactory closureCheckGetCssName = new PassFactory("checkMissingGetCssName", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { String blacklist = options.checkMissingGetCssNameBlacklist; Preconditions.checkState(blacklist != null && !blacklist.isEmpty(), "Not checking use of goog.getCssName because of empty blacklist."); return new CheckMissingGetCssName( compiler, options.checkMissingGetCssNameLevel, blacklist); } }; /** * Processes goog.getCssName. The cssRenamingMap is used to lookup * replacement values for the classnames. If null, the raw class names are * inlined. */ final PassFactory closureReplaceGetCssName = new PassFactory("renameCssNames", true) { @Override protected CompilerPass createInternal(final AbstractCompiler compiler) { return new CompilerPass() { @Override public void process(Node externs, Node jsRoot) { Map<String, Integer> newCssNames = null; if (options.gatherCssNames) { newCssNames = Maps.newHashMap(); } (new ReplaceCssNames(compiler, newCssNames)).process( externs, jsRoot); cssNames = newCssNames; } }; } }; /** * Creates synthetic blocks to prevent FoldConstants from moving code * past markers in the source. */ final PassFactory createSyntheticBlocks = new PassFactory("createSyntheticBlocks", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new CreateSyntheticBlocks(compiler, options.syntheticBlockStartMarker, options.syntheticBlockEndMarker); } }; /** Various peephole optimizations. */ final PassFactory peepholeOptimizations = new PassFactory("peepholeOptimizations", false) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new PeepholeOptimizationsPass(compiler, new PeepholeSubstituteAlternateSyntax(false), new PeepholeReplaceKnownMethods(), new PeepholeRemoveDeadCode(), new PeepholeFoldConstants(), new PeepholeCollectPropertyAssignments()); } }; /** Same as peepholeOptimizations but aggressively merges code together */ final PassFactory latePeepholeOptimizations = new PassFactory("latePeepholeOptimizations", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new PeepholeOptimizationsPass(compiler, new StatementFusion(), new PeepholeRemoveDeadCode(), new PeepholeSubstituteAlternateSyntax(true), new PeepholeReplaceKnownMethods(), new PeepholeFoldConstants()); } }; /** Checks that all variables are defined. */ final HotSwapPassFactory checkVars = new HotSwapPassFactory("checkVars", true) { @Override protected HotSwapCompilerPass createInternal(AbstractCompiler compiler) { return new VarCheck(compiler); } }; /** Checks for RegExp references. */ final PassFactory checkRegExp = new PassFactory("checkRegExp", true) { @Override protected CompilerPass createInternal(final AbstractCompiler compiler) { final CheckRegExp pass = new CheckRegExp(compiler); return new CompilerPass() { @Override public void process(Node externs, Node root) { pass.process(externs, root); compiler.setHasRegExpGlobalReferences( pass.isGlobalRegExpPropertiesUsed()); } }; } }; /** Checks that no vars are illegally shadowed. */ final PassFactory checkShadowVars = new PassFactory("variableShadowDeclarationCheck", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new VariableShadowDeclarationCheck( compiler, options.checkShadowVars); } }; /** Checks that references to variables look reasonable. */ final HotSwapPassFactory checkVariableReferences = new HotSwapPassFactory("checkVariableReferences", true) { @Override protected HotSwapCompilerPass createInternal(AbstractCompiler compiler) { return new VariableReferenceCheck( compiler, options.aggressiveVarCheck); } }; /** Pre-process goog.testing.ObjectPropertyString. */ final PassFactory objectPropertyStringPreprocess = new PassFactory("ObjectPropertyStringPreprocess", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new ObjectPropertyStringPreprocess(compiler); } }; /** Creates a typed scope and adds types to the type registry. */ final HotSwapPassFactory resolveTypes = new HotSwapPassFactory("resolveTypes", false) { @Override protected HotSwapCompilerPass createInternal(AbstractCompiler compiler) { return new GlobalTypeResolver(compiler); } }; /** Runs type inference. */ final HotSwapPassFactory inferTypes = new HotSwapPassFactory("inferTypes", false) { @Override protected HotSwapCompilerPass createInternal(final AbstractCompiler compiler) { return new HotSwapCompilerPass() { @Override public void process(Node externs, Node root) { Preconditions.checkNotNull(topScope); Preconditions.checkNotNull(getTypedScopeCreator()); makeTypeInference(compiler).process(externs, root); } @Override public void hotSwapScript(Node scriptRoot) { makeTypeInference(compiler).inferTypes(scriptRoot); } }; } }; final HotSwapPassFactory inferJsDocInfo = new HotSwapPassFactory("inferJsDocInfo", false) { @Override protected HotSwapCompilerPass createInternal( final AbstractCompiler compiler) { return new HotSwapCompilerPass() { @Override public void process(Node externs, Node root) { Preconditions.checkNotNull(topScope); Preconditions.checkNotNull(getTypedScopeCreator()); makeInferJsDocInfo(compiler).process(externs, root); } @Override public void hotSwapScript(Node scriptRoot) { makeInferJsDocInfo(compiler).hotSwapScript(scriptRoot); } }; } }; /** Checks type usage */ final HotSwapPassFactory checkTypes = new HotSwapPassFactory("checkTypes", false) { @Override protected HotSwapCompilerPass createInternal(final AbstractCompiler compiler) { return new HotSwapCompilerPass() { @Override public void process(Node externs, Node root) { Preconditions.checkNotNull(topScope); Preconditions.checkNotNull(getTypedScopeCreator()); TypeCheck check = makeTypeCheck(compiler); check.process(externs, root); compiler.getErrorManager().setTypedPercent(check.getTypedPercent()); } @Override public void hotSwapScript(Node scriptRoot) { makeTypeCheck(compiler).check(scriptRoot, false); } }; } }; /** * Checks possible execution paths of the program for problems: missing return * statements and dead code. */ final HotSwapPassFactory checkControlFlow = new HotSwapPassFactory("checkControlFlow", true) { @Override protected HotSwapCompilerPass createInternal(AbstractCompiler compiler) { List<Callback> callbacks = Lists.newArrayList(); if (options.checkUnreachableCode.isOn()) { callbacks.add( new CheckUnreachableCode(compiler, options.checkUnreachableCode)); } if (options.checkMissingReturn.isOn() && options.checkTypes) { callbacks.add( new CheckMissingReturn(compiler, options.checkMissingReturn)); } return combineChecks(compiler, callbacks); } }; /** Checks access controls. Depends on type-inference. */ final HotSwapPassFactory checkAccessControls = new HotSwapPassFactory("checkAccessControls", true) { @Override protected HotSwapCompilerPass createInternal(AbstractCompiler compiler) { return new CheckAccessControls(compiler); } }; /** Executes the given callbacks with a {@link CombinedCompilerPass}. */ private static HotSwapCompilerPass combineChecks(AbstractCompiler compiler, List<Callback> callbacks) { Preconditions.checkArgument(callbacks.size() > 0); Callback[] array = callbacks.toArray(new Callback[callbacks.size()]); return new CombinedCompilerPass(compiler, array); } /** A compiler pass that resolves types in the global scope. */ class GlobalTypeResolver implements HotSwapCompilerPass { private final AbstractCompiler compiler; GlobalTypeResolver(AbstractCompiler compiler) { this.compiler = compiler; } @Override public void process(Node externs, Node root) { if (topScope == null) { regenerateGlobalTypedScope(compiler, root.getParent()); } else { compiler.getTypeRegistry().resolveTypesInScope(topScope); } } @Override public void hotSwapScript(Node scriptRoot) { patchGlobalTypedScope(compiler, scriptRoot); } } /** Checks global name usage. */ final PassFactory checkGlobalNames = new PassFactory("Check names", true) { @Override protected CompilerPass createInternal(final AbstractCompiler compiler) { return new CompilerPass() { @Override public void process(Node externs, Node jsRoot) { // Create a global namespace for analysis by check passes. // Note that this class does all heavy computation lazily, // so it's OK to create it here. namespaceForChecks = new GlobalNamespace(compiler, jsRoot); new CheckGlobalNames(compiler, options.checkGlobalNamesLevel) .injectNamespace(namespaceForChecks).process(externs, jsRoot); } }; } }; /** Checks that the code is ES5 or Caja compliant. */ final PassFactory checkStrictMode = new PassFactory("checkStrictMode", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new StrictModeCheck(compiler, !options.checkSymbols, // don't check variables twice !options.checkCaja); // disable eval check if not Caja } }; /** Process goog.tweak.getTweak() calls. */ final PassFactory processTweaks = new PassFactory("processTweaks", true) { @Override protected CompilerPass createInternal(final AbstractCompiler compiler) { return new CompilerPass() { @Override public void process(Node externs, Node jsRoot) { new ProcessTweaks(compiler, options.getTweakProcessing().shouldStrip(), options.getTweakReplacements()).process(externs, jsRoot); } }; } }; /** Override @define-annotated constants. */ final PassFactory processDefines = new PassFactory("processDefines", true) { @Override protected CompilerPass createInternal(final AbstractCompiler compiler) { return new CompilerPass() { @Override public void process(Node externs, Node jsRoot) { Map<String, Node> replacements = getAdditionalReplacements(options); replacements.putAll(options.getDefineReplacements()); new ProcessDefines(compiler, replacements) .injectNamespace(namespaceForChecks).process(externs, jsRoot); // Kill the namespace in the other class // so that it can be garbage collected after all passes // are through with it. namespaceForChecks = null; } }; } }; /** Checks that all constants are not modified */ final PassFactory checkConsts = new PassFactory("checkConsts", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new ConstCheck(compiler); } }; /** Computes the names of functions for later analysis. */ final PassFactory computeFunctionNames = new PassFactory("computeFunctionNames", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return ((functionNames = new FunctionNames(compiler))); } }; /** Skips Caja-private properties in for-in loops */ final PassFactory ignoreCajaProperties = new PassFactory("ignoreCajaProperties", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new IgnoreCajaProperties(compiler); } }; /** Inserts runtime type assertions for debugging. */ final PassFactory runtimeTypeCheck = new PassFactory("runtimeTypeCheck", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new RuntimeTypeCheck(compiler, options.runtimeTypeCheckLogFunction); } }; /** Generates unique ids. */ final PassFactory replaceIdGenerators = new PassFactory("replaceIdGenerators", true) { @Override protected CompilerPass createInternal(final AbstractCompiler compiler) { return new CompilerPass() { @Override public void process(Node externs, Node root) { ReplaceIdGenerators pass = new ReplaceIdGenerators(compiler, options.idGenerators); pass.process(externs, root); idGeneratorMap = pass.getIdGeneratorMap(); } }; } }; /** Replace strings. */ final PassFactory replaceStrings = new PassFactory("replaceStrings", true) { @Override protected CompilerPass createInternal(final AbstractCompiler compiler) { return new CompilerPass() { @Override public void process(Node externs, Node root) { ReplaceStrings pass = new ReplaceStrings( compiler, options.replaceStringsPlaceholderToken, options.replaceStringsFunctionDescriptions, options.replaceStringsReservedStrings); pass.process(externs, root); stringMap = pass.getStringMap(); } }; } }; /** Optimizes the "arguments" array. */ final PassFactory optimizeArgumentsArray = new PassFactory("optimizeArgumentsArray", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new OptimizeArgumentsArray(compiler); } }; /** Remove variables set to goog.abstractMethod. */ final PassFactory closureCodeRemoval = new PassFactory("closureCodeRemoval", true) { @Override protected CompilerPass createInternal(final AbstractCompiler compiler) { return new ClosureCodeRemoval(compiler, options.removeAbstractMethods, options.removeClosureAsserts); } }; /** Special case optimizations for closure functions. */ final PassFactory closureOptimizePrimitives = new PassFactory("closureOptimizePrimitives", true) { @Override protected CompilerPass createInternal(final AbstractCompiler compiler) { return new ClosureOptimizePrimitives(compiler); } }; /** Collapses names in the global scope. */ final PassFactory collapseProperties = new PassFactory("collapseProperties", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new CollapseProperties( compiler, options.collapsePropertiesOnExternTypes, !isInliningForbidden()); } }; /** Rewrite properties as variables. */ final PassFactory collapseObjectLiterals = new PassFactory("collapseObjectLiterals", false) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new InlineObjectLiterals( compiler, compiler.getUniqueNameIdSupplier()); } }; /** * Try to infer the actual types, which may be narrower * than the declared types. */ final PassFactory tightenTypesBuilder = new PassFactory("tightenTypes", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { if (!options.checkTypes) { return new ErrorPass(compiler, TIGHTEN_TYPES_WITHOUT_TYPE_CHECK); } tightenTypes = new TightenTypes(compiler); return tightenTypes; } }; /** Devirtualize property names based on type information. */ final PassFactory disambiguateProperties = new PassFactory("disambiguateProperties", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { if (tightenTypes == null) { return DisambiguateProperties.forJSTypeSystem(compiler); } else { return DisambiguateProperties.forConcreteTypeSystem( compiler, tightenTypes); } } }; /** * Chain calls to functions that return this. */ final PassFactory chainCalls = new PassFactory("chainCalls", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new ChainCalls(compiler); } }; /** * Rewrite instance methods as static methods, to make them easier * to inline. */ final PassFactory devirtualizePrototypeMethods = new PassFactory("devirtualizePrototypeMethods", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new DevirtualizePrototypeMethods(compiler); } }; /** * Optimizes unused function arguments, unused return values, and inlines * constant parameters. Also runs RemoveUnusedVars. */ final PassFactory optimizeCallsAndRemoveUnusedVars = new PassFactory("optimizeCalls_and_removeUnusedVars", false) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { OptimizeCalls passes = new OptimizeCalls(compiler); if (options.optimizeReturns) { // Remove unused return values. passes.addPass(new OptimizeReturns(compiler)); } if (options.optimizeParameters) { // Remove all parameters that are constants or unused. passes.addPass(new OptimizeParameters(compiler)); } if (options.optimizeCalls) { boolean removeOnlyLocals = options.removeUnusedLocalVars && !options.removeUnusedVars; boolean preserveAnonymousFunctionNames = options.anonymousFunctionNaming != AnonymousFunctionNamingPolicy.OFF; passes.addPass( new RemoveUnusedVars(compiler, !removeOnlyLocals, preserveAnonymousFunctionNames, true)); } return passes; } }; /** * Look for function calls that are pure, and annotate them * that way. */ final PassFactory markPureFunctions = new PassFactory("markPureFunctions", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new PureFunctionIdentifier.Driver( compiler, options.debugFunctionSideEffectsPath, false); } }; /** * Look for function calls that have no side effects, and annotate them * that way. */ final PassFactory markNoSideEffectCalls = new PassFactory("markNoSideEffectCalls", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new MarkNoSideEffectCalls(compiler); } }; /** Inlines variables heuristically. */ final PassFactory inlineVariables = new PassFactory("inlineVariables", false) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { if (isInliningForbidden()) { // In old renaming schemes, inlining a variable can change whether // or not a property is renamed. This is bad, and those old renaming // schemes need to die. return new ErrorPass(compiler, CANNOT_USE_PROTOTYPE_AND_VAR); } else { InlineVariables.Mode mode; if (options.inlineVariables) { mode = InlineVariables.Mode.ALL; } else if (options.inlineLocalVariables) { mode = InlineVariables.Mode.LOCALS_ONLY; } else { throw new IllegalStateException("No variable inlining option set."); } return new InlineVariables(compiler, mode, true); } } }; /** Inlines variables that are marked as constants. */ final PassFactory inlineConstants = new PassFactory("inlineConstants", false) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new InlineVariables( compiler, InlineVariables.Mode.CONSTANTS_ONLY, true); } }; /** * Perform local control flow optimizations. */ final PassFactory minimizeExitPoints = new PassFactory("minimizeExitPoints", false) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new MinimizeExitPoints(compiler); } }; /** * Use data flow analysis to remove dead branches. */ final PassFactory removeUnreachableCode = new PassFactory("removeUnreachableCode", false) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new UnreachableCodeElimination(compiler, true); } }; /** * Remove prototype properties that do not appear to be used. */ final PassFactory removeUnusedPrototypeProperties = new PassFactory("removeUnusedPrototypeProperties", false) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new RemoveUnusedPrototypeProperties( compiler, options.removeUnusedPrototypePropertiesInExterns, !options.removeUnusedVars); } }; /** * Process smart name processing - removes unused classes and does referencing * starting with minimum set of names. */ final PassFactory smartNamePass = new PassFactory("smartNamePass", true) { @Override protected CompilerPass createInternal(final AbstractCompiler compiler) { return new CompilerPass() { @Override public void process(Node externs, Node root) { NameAnalyzer na = new NameAnalyzer(compiler, false); na.process(externs, root); String reportPath = options.reportPath; if (reportPath != null) { try { Files.write(na.getHtmlReport(), new File(reportPath), Charsets.UTF_8); } catch (IOException e) { compiler.report(JSError.make(REPORT_PATH_IO_ERROR, reportPath)); } } if (options.smartNameRemoval) { na.removeUnreferenced(); } } }; } }; /** * Process smart name processing - removes unused classes and does referencing * starting with minimum set of names. */ final PassFactory smartNamePass2 = new PassFactory("smartNamePass", true) { @Override protected CompilerPass createInternal(final AbstractCompiler compiler) { return new CompilerPass() { @Override public void process(Node externs, Node root) { NameAnalyzer na = new NameAnalyzer(compiler, false); na.process(externs, root); na.removeUnreferenced(); } }; } }; /** Inlines simple methods, like getters */ final PassFactory inlineSimpleMethods = new PassFactory("inlineSimpleMethods", false) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new InlineSimpleMethods(compiler); } }; /** Kills dead assignments. */ final PassFactory deadAssignmentsElimination = new PassFactory("deadAssignmentsElimination", false) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new DeadAssignmentsElimination(compiler); } }; /** Inlines function calls. */ final PassFactory inlineFunctions = new PassFactory("inlineFunctions", false) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { boolean enableBlockInlining = !isInliningForbidden(); return new InlineFunctions( compiler, compiler.getUniqueNameIdSupplier(), options.inlineFunctions, options.inlineLocalFunctions, enableBlockInlining, options.isAssumeStrictThis() || options.getLanguageIn() == LanguageMode.ECMASCRIPT5_STRICT); } }; /** Removes variables that are never used. */ final PassFactory removeUnusedVars = new PassFactory("removeUnusedVars", false) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { boolean removeOnlyLocals = options.removeUnusedLocalVars && !options.removeUnusedVars; boolean preserveAnonymousFunctionNames = options.anonymousFunctionNaming != AnonymousFunctionNamingPolicy.OFF; return new RemoveUnusedVars( compiler, !removeOnlyLocals, preserveAnonymousFunctionNames, false); } }; /** * Move global symbols to a deeper common module */ final PassFactory crossModuleCodeMotion = new PassFactory("crossModuleCodeMotion", false) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new CrossModuleCodeMotion(compiler, compiler.getModuleGraph()); } }; /** * Move methods to a deeper common module */ final PassFactory crossModuleMethodMotion = new PassFactory("crossModuleMethodMotion", false) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new CrossModuleMethodMotion( compiler, crossModuleIdGenerator, // Only move properties in externs if we're not treating // them as exports. options.removeUnusedPrototypePropertiesInExterns); } }; /** * Specialize the initial module at the cost of later modules */ final PassFactory specializeInitialModule = new PassFactory("specializeInitialModule", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new SpecializeModule(compiler, devirtualizePrototypeMethods, inlineFunctions, removeUnusedPrototypeProperties); } }; /** A data-flow based variable inliner. */ final PassFactory flowSensitiveInlineVariables = new PassFactory("flowSensitiveInlineVariables", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new FlowSensitiveInlineVariables(compiler); } }; /** Uses register-allocation algorithms to use fewer variables. */ final PassFactory coalesceVariableNames = new PassFactory("coalesceVariableNames", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new CoalesceVariableNames(compiler, options.generatePseudoNames); } }; /** * Some simple, local collapses (e.g., {@code var x; var y;} becomes * {@code var x,y;}. */ final PassFactory exploitAssign = new PassFactory("expointAssign", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new PeepholeOptimizationsPass(compiler, new ExploitAssigns()); } }; /** * Some simple, local collapses (e.g., {@code var x; var y;} becomes * {@code var x,y;}. */ final PassFactory collapseVariableDeclarations = new PassFactory("collapseVariableDeclarations", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new CollapseVariableDeclarations(compiler); } }; /** * Simple global collapses of variable declarations. */ final PassFactory groupVariableDeclarations = new PassFactory("groupVariableDeclarations", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new GroupVariableDeclarations(compiler); } }; /** * Extracts common sub-expressions. */ final PassFactory extractPrototypeMemberDeclarations = new PassFactory("extractPrototypeMemberDeclarations", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new ExtractPrototypeMemberDeclarations(compiler); } }; /** Rewrites common function definitions to be more compact. */ final PassFactory rewriteFunctionExpressions = new PassFactory("rewriteFunctionExpressions", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new FunctionRewriter(compiler); } }; /** Collapses functions to not use the VAR keyword. */ final PassFactory collapseAnonymousFunctions = new PassFactory("collapseAnonymousFunctions", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new CollapseAnonymousFunctions(compiler); } }; /** Moves function declarations to the top, to simulate actual hoisting. */ final PassFactory moveFunctionDeclarations = new PassFactory("moveFunctionDeclarations", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new MoveFunctionDeclarations(compiler); } }; final PassFactory nameUnmappedAnonymousFunctions = new PassFactory("nameAnonymousFunctions", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new NameAnonymousFunctions(compiler); } }; final PassFactory nameMappedAnonymousFunctions = new PassFactory("nameAnonymousFunctions", true) { @Override protected CompilerPass createInternal(final AbstractCompiler compiler) { return new CompilerPass() { @Override public void process(Node externs, Node root) { NameAnonymousFunctionsMapped naf = new NameAnonymousFunctionsMapped(compiler); naf.process(externs, root); anonymousFunctionNameMap = naf.getFunctionMap(); } }; } }; final PassFactory operaCompoundAssignFix = new PassFactory("operaCompoundAssignFix", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new OperaCompoundAssignFix(compiler); } }; /** Alias external symbols. */ final PassFactory aliasExternals = new PassFactory("aliasExternals", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new AliasExternals(compiler, compiler.getModuleGraph(), options.unaliasableGlobals, options.aliasableGlobals); } }; /** * Alias string literals with global variables, to avoid creating lots of * transient objects. */ final PassFactory aliasStrings = new PassFactory("aliasStrings", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new AliasStrings( compiler, compiler.getModuleGraph(), options.aliasAllStrings ? null : options.aliasableStrings, options.aliasStringsBlacklist, options.outputJsStringUsage); } }; /** Aliases common keywords (true, false) */ final PassFactory aliasKeywords = new PassFactory("aliasKeywords", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new AliasKeywords(compiler); } }; /** Handling for the ObjectPropertyString primitive. */ final PassFactory objectPropertyStringPostprocess = new PassFactory("ObjectPropertyStringPostprocess", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new ObjectPropertyStringPostprocess(compiler); } }; /** * Renames properties so that the two properties that never appear on * the same object get the same name. */ final PassFactory ambiguateProperties = new PassFactory("ambiguateProperties", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new AmbiguateProperties( compiler, options.anonymousFunctionNaming.getReservedCharacters()); } }; /** * Mark the point at which the normalized AST assumptions no longer hold. */ final PassFactory markUnnormalized = new PassFactory("markUnnormalized", true) { @Override protected CompilerPass createInternal(final AbstractCompiler compiler) { return new CompilerPass() { @Override public void process(Node externs, Node root) { compiler.setLifeCycleStage(LifeCycleStage.RAW); } }; } }; /** Denormalize the AST for code generation. */ final PassFactory denormalize = new PassFactory("denormalize", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new Denormalize(compiler); } }; /** Inverting name normalization. */ final PassFactory invertContextualRenaming = new PassFactory("invertNames", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return MakeDeclaredNamesUnique.getContextualRenameInverter(compiler); } }; /** * Renames properties. */ final PassFactory renameProperties = new PassFactory("renameProperties", true) { @Override protected CompilerPass createInternal(final AbstractCompiler compiler) { VariableMap map = null; if (options.inputPropertyMapSerialized != null) { try { map = VariableMap.fromBytes(options.inputPropertyMapSerialized); } catch (ParseException e) { return new ErrorPass(compiler, JSError.make(INPUT_MAP_PROP_PARSE, e.getMessage())); } } final VariableMap prevPropertyMap = map; return new CompilerPass() { @Override public void process(Node externs, Node root) { propertyMap = runPropertyRenaming( compiler, prevPropertyMap, externs, root); } }; } }; private VariableMap runPropertyRenaming( AbstractCompiler compiler, VariableMap prevPropertyMap, Node externs, Node root) { char[] reservedChars = options.anonymousFunctionNaming.getReservedCharacters(); switch (options.propertyRenaming) { case HEURISTIC: RenamePrototypes rproto = new RenamePrototypes(compiler, false, reservedChars, prevPropertyMap); rproto.process(externs, root); return rproto.getPropertyMap(); case AGGRESSIVE_HEURISTIC: RenamePrototypes rproto2 = new RenamePrototypes(compiler, true, reservedChars, prevPropertyMap); rproto2.process(externs, root); return rproto2.getPropertyMap(); case ALL_UNQUOTED: RenameProperties rprop = new RenameProperties( compiler, options.propertyAffinity, options.generatePseudoNames, prevPropertyMap, reservedChars); rprop.process(externs, root); return rprop.getPropertyMap(); default: throw new IllegalStateException( "Unrecognized property renaming policy"); } } /** Renames variables. */ final PassFactory renameVars = new PassFactory("renameVars", true) { @Override protected CompilerPass createInternal(final AbstractCompiler compiler) { VariableMap map = null; if (options.inputVariableMapSerialized != null) { try { map = VariableMap.fromBytes(options.inputVariableMapSerialized); } catch (ParseException e) { return new ErrorPass(compiler, JSError.make(INPUT_MAP_VAR_PARSE, e.getMessage())); } } final VariableMap prevVariableMap = map; return new CompilerPass() { @Override public void process(Node externs, Node root) { variableMap = runVariableRenaming( compiler, prevVariableMap, externs, root); } }; } }; private VariableMap runVariableRenaming( AbstractCompiler compiler, VariableMap prevVariableMap, Node externs, Node root) { char[] reservedChars = options.anonymousFunctionNaming.getReservedCharacters(); boolean preserveAnonymousFunctionNames = options.anonymousFunctionNaming != AnonymousFunctionNamingPolicy.OFF; RenameVars rn = new RenameVars( compiler, options.renamePrefix, options.variableRenaming == VariableRenamingPolicy.LOCAL, preserveAnonymousFunctionNames, options.generatePseudoNames, options.shadowVariables, prevVariableMap, reservedChars, exportedNames); rn.process(externs, root); return rn.getVariableMap(); } /** Renames labels */ final PassFactory renameLabels = new PassFactory("renameLabels", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new RenameLabels(compiler); } }; /** Convert bracket access to dot access */ final PassFactory convertToDottedProperties = new PassFactory("convertToDottedProperties", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new ConvertToDottedProperties(compiler); } }; /** Checks that all variables are defined. */ final PassFactory sanityCheckAst = new PassFactory("sanityCheckAst", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new AstValidator(); } }; /** Checks that all variables are defined. */ final PassFactory sanityCheckVars = new PassFactory("sanityCheckVars", true) { @Override protected CompilerPass createInternal(AbstractCompiler compiler) { return new VarCheck(compiler, true); } }; /** Adds instrumentations according to an instrumentation template. */ final PassFactory instrumentFunctions = new PassFactory("instrumentFunctions", true) { @Override protected CompilerPass createInternal(final AbstractCompiler compiler) { return new CompilerPass() { @Override public void process(Node externs, Node root) { try { FileReader templateFile = new FileReader(options.instrumentationTemplate); (new InstrumentFunctions( compiler, functionNames, options.instrumentationTemplate, options.appNameStr, templateFile)).process(externs, root); } catch (IOException e) { compiler.report( JSError.make(AbstractCompiler.READ_ERROR, options.instrumentationTemplate)); } } }; } }; /** * Create a no-op pass that can only run once. Used to break up loops. */ private static PassFactory createEmptyPass(String name) { return new PassFactory(name, true) { @Override protected CompilerPass createInternal(final AbstractCompiler compiler) { return runInSerial(); } }; } /** * Runs custom passes that are designated to run at a particular time. */ private PassFactory getCustomPasses( final CustomPassExecutionTime executionTime) { return new PassFactory("runCustomPasses", true) { @Override protected CompilerPass createInternal(final AbstractCompiler compiler) { return runInSerial(options.customPasses.get(executionTime)); } }; } /** * All inlining is forbidden in heuristic renaming mode, because inlining * will ruin the invariants that it depends on. */ private boolean isInliningForbidden() { return options.propertyRenaming == PropertyRenamingPolicy.HEURISTIC || options.propertyRenaming == PropertyRenamingPolicy.AGGRESSIVE_HEURISTIC; } /** Create a compiler pass that runs the given passes in serial. */ private static CompilerPass runInSerial(final CompilerPass ... passes) { return runInSerial(Lists.newArrayList(passes)); } /** Create a compiler pass that runs the given passes in serial. */ private static CompilerPass runInSerial( final Collection<CompilerPass> passes) { return new CompilerPass() { @Override public void process(Node externs, Node root) { for (CompilerPass pass : passes) { pass.process(externs, root); } } }; } @VisibleForTesting static Map<String, Node> getAdditionalReplacements( CompilerOptions options) { Map<String, Node> additionalReplacements = Maps.newHashMap(); if (options.markAsCompiled || options.closurePass) { additionalReplacements.put(COMPILED_CONSTANT_NAME, new Node(Token.TRUE)); } if (options.closurePass && options.locale != null) { additionalReplacements.put(CLOSURE_LOCALE_CONSTANT_NAME, Node.newString(options.locale)); } return additionalReplacements; } final PassFactory printNameReferenceGraph = new PassFactory("printNameReferenceGraph", true) { @Override protected CompilerPass createInternal(final AbstractCompiler compiler) { return new CompilerPass() { @Override public void process(Node externs, Node jsRoot) { NameReferenceGraphConstruction gc = new NameReferenceGraphConstruction(compiler); gc.process(externs, jsRoot); String graphFileName = options.nameReferenceGraphPath; try { Files.write(DotFormatter.toDot(gc.getNameReferenceGraph()), new File(graphFileName), Charsets.UTF_8); } catch (IOException e) { compiler.report( JSError.make( NAME_REF_GRAPH_FILE_ERROR, e.getMessage(), graphFileName)); } } }; } }; final PassFactory printNameReferenceReport = new PassFactory("printNameReferenceReport", true) { @Override protected CompilerPass createInternal(final AbstractCompiler compiler) { return new CompilerPass() { @Override public void process(Node externs, Node jsRoot) { NameReferenceGraphConstruction gc = new NameReferenceGraphConstruction(compiler); String reportFileName = options.nameReferenceReportPath; try { NameReferenceGraphReport report = new NameReferenceGraphReport(gc.getNameReferenceGraph()); Files.write(report.getHtmlReport(), new File(reportFileName), Charsets.UTF_8); } catch (IOException e) { compiler.report( JSError.make( NAME_REF_REPORT_FILE_ERROR, e.getMessage(), reportFileName)); } } }; } }; /** * A pass-factory that is good for {@code HotSwapCompilerPass} passes. */ abstract static class HotSwapPassFactory extends PassFactory { HotSwapPassFactory(String name, boolean isOneTimePass) { super(name, isOneTimePass); } @Override protected abstract HotSwapCompilerPass createInternal(AbstractCompiler compiler); @Override HotSwapCompilerPass getHotSwapPass(AbstractCompiler compiler) { return this.createInternal(compiler); } } }
Automated g4 rollback. *** Reason for rollback *** Breaks apps script. *** Original change description *** Implement a configuration Environment for JSAnalyzer Current implementation supports configuring the Passes Next phase is to collect the output. R=acleung Revision created by MOE tool push_codebase. MOE_MIGRATION=2459 git-svn-id: 818616af560c21f974e3119d89e3310384da871a@1232 b0f006be-c8cd-11de-a2e8-8d36a3108c74
src/com/google/javascript/jscomp/DefaultPassConfig.java
Java
apache-2.0
af0f267ce455322ea6a3d187046a49847cdb217b
0
fstahnke/arx,RaffaelBild/arx,arx-deidentifier/arx,jgaupp/arx,kentoa/arx,kbabioch/arx,bitraten/arx,jgaupp/arx,bitraten/arx,fstahnke/arx,kbabioch/arx,kentoa/arx,arx-deidentifier/arx,RaffaelBild/arx
package org.deidentifier.arx.gui; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.util.Arrays; import java.util.Comparator; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.TreeMap; import org.deidentifier.arx.gui.view.SWTUtil; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.DeviceData; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.List; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.MessageBox; import org.eclipse.swt.widgets.Shell; /** * Code based on: https://www.eclipse.org/articles/swt-design-2/sleak.htm * */ public class DebugResourceLeaks { class Resource { Object resource; Error error; int occurrences; @Override protected Resource clone() { Resource resource = new Resource(); resource.error = error; resource.resource = this.resource; resource.occurrences = occurrences; return resource; } } public static void main(String[] args) { DebugResourceLeaks sleak = new DebugResourceLeaks(); Display display = sleak.open(); Main.main(display, new String[0]); } private Display display; private Shell shell; private Label objectStatistics; private Label objectStackTrace; private List listNewObjects; private List listEqualObjects; private Resource[] resources; private Resource[] resourcesSameStackTrace; private void collectAll() { DeviceData info = display.getDeviceData(); if (!info.tracking) { MessageBox dialog = new MessageBox(shell, SWT.ICON_WARNING | SWT.OK); dialog.setText(shell.getText()); dialog.setMessage("Warning: Device is not tracking resource allocation"); dialog.open(); } Object[] objects = info.objects; Error[] errors = info.errors; resources = new Resource[objects.length]; for (int i = 0; i < resources.length; i++) { Resource resource = new Resource(); resource.error = errors[i]; resource.resource = objects[i]; resource.occurrences = 1; resources[i] = resource; } Map<String, Integer> objectTypesTimes = new TreeMap<String, Integer>(); Map<String, Resource> objectSameStackTrace = new HashMap<String, Resource>(); for (int i = 0; i < resources.length; i++) { String className = resources[i].resource.getClass().getSimpleName(); Integer count = objectTypesTimes.get(className); if (count == null) { objectTypesTimes.put(className, 1); } else { objectTypesTimes.put(className, count + 1); } String stackTrace = getStackTrace(resources[i].error); if (!objectSameStackTrace.containsKey(stackTrace)) { Resource resource = resources[i].clone(); resource.occurrences = 1; objectSameStackTrace.put(stackTrace, resource); } else { Resource resource = objectSameStackTrace.get(stackTrace); resource.occurrences++; } } resourcesSameStackTrace = new Resource[objectSameStackTrace.size()]; int idx = 0; for (Entry<String, Resource> entry : objectSameStackTrace.entrySet()) { resourcesSameStackTrace[idx] = entry.getValue(); idx++; } Arrays.sort(resourcesSameStackTrace, new Comparator<Resource>() { @Override public int compare(Resource o1, Resource o2) { return o2.occurrences - o1.occurrences; } }); StringBuilder statistics = new StringBuilder(); for (Entry<String, Integer> entry : objectTypesTimes.entrySet()) { statistics.append(entry.getKey()); statistics.append(": "); statistics.append(entry.getValue()); statistics.append("\n"); } statistics.append("Total: "); statistics.append(resources.length); statistics.append("\n"); // Display listNewObjects.removeAll(); for (int i = 0; i < resources.length; i++) { listNewObjects.add(resources[i].resource.getClass().getSimpleName() + "(" + resources[i].resource.hashCode() + ")"); } listEqualObjects.removeAll(); for (int i = 0; i < resourcesSameStackTrace.length; i++) { listEqualObjects.add(resourcesSameStackTrace[i].resource.getClass().getSimpleName() + "(" + resourcesSameStackTrace[i].resource.hashCode() + ")" + "[" + resourcesSameStackTrace[i].occurrences + "x]"); } objectStatistics.setText(statistics.toString()); } private String getStackTrace(Error error) { ByteArrayOutputStream stream = new ByteArrayOutputStream(); PrintStream s = new PrintStream(stream); error.printStackTrace(s); return stream.toString(); } private Display open() { DeviceData data = new DeviceData(); data.tracking = true; Display display = new Display(data); this.display = display; shell = new Shell(display); shell.setText("Resources"); shell.setLayout(SWTUtil.createGridLayout(2)); Button collect = new Button(shell, SWT.PUSH); collect.setText("Collect data"); collect.addListener(SWT.Selection, new Listener() { @Override public void handleEvent(Event event) { collectAll(); } }); final GridData d = new GridData(); d.grabExcessHorizontalSpace = true; d.horizontalSpan = 2; collect.setLayoutData(d); listNewObjects = new List(shell, SWT.BORDER | SWT.V_SCROLL); listNewObjects.addListener(SWT.Selection, new Listener() { @Override public void handleEvent(Event event) { selectObject(); } }); listNewObjects.setLayoutData(SWTUtil.createFillGridData()); listEqualObjects = new List(shell, SWT.BORDER | SWT.V_SCROLL); listEqualObjects.addListener(SWT.Selection, new Listener() { @Override public void handleEvent(Event event) { selectEqualObject(); } }); listEqualObjects.setLayoutData(SWTUtil.createFillGridData()); objectStackTrace = new Label(shell, SWT.BORDER); objectStackTrace.setText(""); objectStackTrace.setLayoutData(SWTUtil.createFillGridData()); objectStatistics = new Label(shell, SWT.BORDER); objectStatistics.setText("0 object(s)"); objectStatistics.setLayoutData(SWTUtil.createFillGridData()); shell.open(); return display; } private void selectEqualObject() { int index = listEqualObjects.getSelectionIndex(); if (index == -1) { return; } objectStackTrace.setText(getStackTrace(resourcesSameStackTrace[index].error)); objectStackTrace.setVisible(true); } private void selectObject() { int index = listNewObjects.getSelectionIndex(); if (index == -1) { return; } objectStackTrace.setText(getStackTrace(resources[index].error)); objectStackTrace.setVisible(true); } }
src/gui/org/deidentifier/arx/gui/DebugResourceLeaks.java
package org.deidentifier.arx.gui; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.TreeMap; import org.deidentifier.arx.gui.view.SWTUtil; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.DeviceData; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.List; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.MessageBox; import org.eclipse.swt.widgets.Shell; import cern.colt.GenericSorting; import cern.colt.Swapper; import cern.colt.function.IntComparator; /** * Code based on: https://www.eclipse.org/articles/swt-design-2/sleak.htm * */ public class DebugResourceLeaks { public static void main(String[] args) { DebugResourceLeaks sleak = new DebugResourceLeaks(); Display display = sleak.open(); Main.main(display, new String[0]); } private Display display; private Shell shell; private Label objectStatistics; private Label objectStackTrace; private List listNewObjects; private List listEqualObjects; private Object[] newObjects; private Error[] newErrors; private Object[] equalObjects; private Error[] equalErrors; private void collectAll() { DeviceData info = display.getDeviceData(); if (!info.tracking) { MessageBox dialog = new MessageBox(shell, SWT.ICON_WARNING | SWT.OK); dialog.setText(shell.getText()); dialog.setMessage("Warning: Device is not tracking resource allocation"); dialog.open(); } newObjects = info.objects; newErrors = info.errors; Map<String, Integer> objectTypesTimes = new TreeMap<String, Integer>(); Map<String, Integer> objectSameStackTrace = new HashMap<String, Integer>(); final Map<Integer, Integer> objectSameStackTraceTimes = new HashMap<Integer, Integer>(); for (int i = 0; i < newObjects.length; i++) { String className = newObjects[i].getClass().getSimpleName(); Integer count = objectTypesTimes.get(className); if (count == null) { objectTypesTimes.put(className, 1); } else { objectTypesTimes.put(className, count + 1); } String stackTrace = getStackTrace(newErrors[i]); if (!objectSameStackTrace.containsKey(stackTrace)) { objectSameStackTrace.put(stackTrace, i); objectSameStackTraceTimes.put(i, 1); } else { Integer objectIDX = objectSameStackTrace.get(stackTrace); objectSameStackTraceTimes.put(objectIDX, objectSameStackTraceTimes.get(objectIDX) + 1); } } equalObjects = new Object[objectSameStackTrace.size()]; equalErrors = new Error[objectSameStackTrace.size()]; final int[] equalOccurrence = new int[objectSameStackTrace.size()]; int idx = 0; for (Entry<String, Integer> entry : objectSameStackTrace.entrySet()) { equalObjects[idx] = newObjects[entry.getValue()]; equalErrors[idx] = newErrors[entry.getValue()]; equalOccurrence[idx] = objectSameStackTraceTimes.get(entry.getValue()); idx++; } final IntComparator c = new IntComparator() { @Override public int compare(final int arg0, final int arg1) { return equalOccurrence[arg1] - equalOccurrence[arg0]; } }; final Swapper s = new Swapper() { @Override public void swap(final int arg0, final int arg1) { // Swap objects Object tempObject = equalObjects[arg0]; equalObjects[arg0] = equalObjects[arg1]; equalObjects[arg1] = tempObject; // Swap errors Error tempError = equalErrors[arg0]; equalErrors[arg0] = equalErrors[arg1]; equalErrors[arg1] = tempError; // Swap occurrences int tempOccurence = equalOccurrence[arg0]; equalOccurrence[arg0] = equalOccurrence[arg1]; equalOccurrence[arg1] = tempOccurence; } }; // No need to swap and rebuild the subset views GenericSorting.mergeSort(0, equalObjects.length, c, s); StringBuilder statistics = new StringBuilder(); for (Entry<String, Integer> entry : objectTypesTimes.entrySet()) { statistics.append(entry.getKey()); statistics.append(": "); statistics.append(entry.getValue()); statistics.append("\n"); } statistics.append("Total: "); statistics.append(newObjects.length); statistics.append("\n"); // Display listNewObjects.removeAll(); for (int i = 0; i < newObjects.length; i++) { listNewObjects.add(newObjects[i].getClass().getSimpleName() + "(" + newObjects[i].hashCode() + ")"); } listEqualObjects.removeAll(); for (int i = 0; i < equalObjects.length; i++) { listEqualObjects.add(equalObjects[i].getClass().getSimpleName() + "(" + equalObjects[i].hashCode() + ")" + "[" + equalOccurrence[i] + "x]"); } objectStatistics.setText(statistics.toString()); } private String getStackTrace(Error error) { ByteArrayOutputStream stream = new ByteArrayOutputStream(); PrintStream s = new PrintStream(stream); error.printStackTrace(s); return stream.toString(); } private Display open() { DeviceData data = new DeviceData(); data.tracking = true; Display display = new Display(data); this.display = display; shell = new Shell(display); shell.setText("Resources"); shell.setLayout(SWTUtil.createGridLayout(2)); Button collect = new Button(shell, SWT.PUSH); collect.setText("Collect data"); collect.addListener(SWT.Selection, new Listener() { @Override public void handleEvent(Event event) { collectAll(); } }); final GridData d = new GridData(); d.grabExcessHorizontalSpace = true; d.horizontalSpan = 2; collect.setLayoutData(d); listNewObjects = new List(shell, SWT.BORDER | SWT.V_SCROLL); listNewObjects.addListener(SWT.Selection, new Listener() { @Override public void handleEvent(Event event) { selectObject(); } }); listNewObjects.setLayoutData(SWTUtil.createFillGridData()); listEqualObjects = new List(shell, SWT.BORDER | SWT.V_SCROLL); listEqualObjects.addListener(SWT.Selection, new Listener() { @Override public void handleEvent(Event event) { selectEqualObject(); } }); listEqualObjects.setLayoutData(SWTUtil.createFillGridData()); objectStackTrace = new Label(shell, SWT.BORDER); objectStackTrace.setText(""); objectStackTrace.setLayoutData(SWTUtil.createFillGridData()); objectStatistics = new Label(shell, SWT.BORDER); objectStatistics.setText("0 object(s)"); objectStatistics.setLayoutData(SWTUtil.createFillGridData()); shell.open(); return display; } private void selectEqualObject() { int index = listEqualObjects.getSelectionIndex(); if (index == -1) { return; } objectStackTrace.setText(getStackTrace(equalErrors[index])); objectStackTrace.setVisible(true); } private void selectObject() { int index = listNewObjects.getSelectionIndex(); if (index == -1) { return; } objectStackTrace.setText(getStackTrace(newErrors[index])); objectStackTrace.setVisible(true); } }
Refactor debug resource leaks class
src/gui/org/deidentifier/arx/gui/DebugResourceLeaks.java
Refactor debug resource leaks class
Java
apache-2.0
caecfc0b3d9fd3f91a840a3027a1980d664f2339
0
pabloalba/SaveTheBunny
package es.seastorm.merlin; public class Constants { public static float WIDTH = 1280; public static float HEIGHT = 720; public static int FLOOR_SIZE = 80; public static int LABYRINT_WIDTH = 9; public static int LABYRINT_HEIGHT = 9; public static int ANIMAL_BUNNY = 5; public static int ANIMAL_FOX = 0; public static int ANIMAL_DOG1 = 1; public static int ANIMAL_DOG2 = 2; public static int ANIMAL_BURROW = 6; public static final String TEXTURE_ATLAS_OBJECTS = "images/merlin-images.pack.atlas"; public static final String PREFERENCES = "merlin.prefs"; public static final int DIRECTION_UP = 0; public static final int DIRECTION_RIGHT = 1; public static final int DIRECTION_DOWN = 2; public static final int DIRECTION_LEFT = 3; public static final int DIRECTION_PASS = 4; public static String[][] LEVEL_LIST = { { "{enemy:[1],minMoves:10,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:2,y:5},enemyPosition:{x:3,y:4},exitPosition:{x:6,y:5}}", "{enemy:[1],minMoves:5,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:5,y:5},enemyPosition:{x:5,y:2},exitPosition:{x:5,y:4}}", "{enemy:[1],minMoves:5,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:3,y:5},enemyPosition:{x:3,y:3},exitPosition:{x:5,y:5}}", "{enemy:[1],minMoves:4,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:4,y:5},enemyPosition:{x:4,y:3},exitPosition:{x:3,y:4}}", "{enemy:[1],minMoves:8,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:4,y:3},enemyPosition:{x:4,y:2},exitPosition:{x:5,y:3}}", "{enemy:[1],minMoves:9,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:3,y:3},enemyPosition:{x:5,y:2},exitPosition:{x:5,y:2}}", "{enemy:[1],minMoves:12,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:3,y:4},enemyPosition:{x:4,y:3},exitPosition:{x:5,y:2}}", "{enemy:[1],minMoves:6,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:1,y:3},enemyPosition:{x:6,y:5},exitPosition:{x:4,y:4}}", "{enemy:[1],minMoves:7,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLef:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:3,y:2},enemyPosition:{x:2,y:5},exitPosition:{x:2,y:3}}", "{enemy:[2],minMoves:11,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:3,y:2},enemyPosition:{x:2,y:2},exitPosition:{x:2,y:4}}", "{enemy:[2],minMoves:9,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:2,y:6},enemyPosition:{x:2,y:1},exitPosition:{x:4,y:3}}", "{enemy:[2],minMoves:13,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:3,y:5},enemyPosition:{x:3,y:7},exitPosition:{x:5,y:6}}", "{enemy:[1],minMoves:23,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:1,y:8},enemyPosition:{x:8,y:5},exitPosition:{x:5,y:4},enemyPosition2:{x:0,y:0}}", "{enemy:[1],minMoves:21,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:4,y:5},enemyPosition:{x:5,y:1},exitPosition:{x:5,y:3},enemyPosition2:{x:0,y:0}}", "{enemy:[1],minMoves:27,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:3,y:3},enemyPosition:{x:6,y:4},exitPosition:{x:5,y:2},enemyPosition2:{x:1,y:1}}", "{enemy:[1],minMoves:26,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:7,y:7},enemyPosition:{x:3,y:7},exitPosition:{x:3,y:7},enemyPosition2:{x:0,y:0}}", "{enemy:[2],minMoves:25,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:5,y:6},enemyPosition:{x:1,y:5},exitPosition:{x:4,y:1},enemyPosition2:{x:0,y:0}}", "{enemy:[1],minMoves:20,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:6,y:3},enemyPosition:{x:6,y:2},exitPosition:{x:3,y:3},enemyPosition2:{x:0,y:0}}", "{enemy:[2],minMoves:24,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:1,y:5},enemyPosition:{x:2,y:1},exitPosition:{x:2,y:4},enemyPosition2:{x:0,y:0}}", "{enemy:[2],minMoves:21,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:5,y:2},enemyPosition:{x:5,y:3},exitPosition:{x:3,y:3},enemyPosition2:{x:0,y:0}}", "{enemy:[1],minMoves:21,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:3,y:5},enemyPosition:{x:5,y:4},exitPosition:{x:4,y:2},enemyPosition2:{x:0,y:0}}", "{enemy:[2],minMoves:23,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:6,y:4},enemyPosition:{x:1,y:3},exitPosition:{x:3,y:6},enemyPosition2:{x:0,y:0}}", "{enemy:[2],minMoves:23,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:3,y:6},enemyPosition:{x:5,y:5},exitPosition:{x:5,y:5},enemyPosition2:{x:0,y:0}}", "{enemy:[2],minMoves:22,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:3,y:2},enemyPosition:{x:5,y:4},exitPosition:{x:4,y:2},enemyPosition2:{x:0,y:0}}", "{enemy:[1],minMoves:40,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:3,y:3},enemyPosition:{x:3,y:6},exitPosition:{x:6,y:2},enemyPosition2:{x:1,y:1}}", "{enemy:[1],minMoves:20,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:3,y:3},enemyPosition:{x:2,y:3},exitPosition:{x:2,y:2},enemyPosition2:{x:0,y:0}}", "{enemy:[2],minMoves:24,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:3,y:4},enemyPosition:{x:5,y:3},exitPosition:{x:4,y:5},enemyPosition2:{x:0,y:0}}", "{enemy:[1],minMoves:21,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:2,y:4},enemyPosition:{x:5,y:1},exitPosition:{x:5,y:2},enemyPosition2:{x:0,y:0}}", "{enemy:[2],minMoves:21,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:2,y:2},enemyPosition:{x:2,y:6},exitPosition:{x:3,y:4},enemyPosition2:{x:0,y:0}}", "{enemy:[2],minMoves:24,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:3,y:4},enemyPosition:{x:6,y:3},exitPosition:{x:6,y:5},enemyPosition2:{x:0,y:0}}", "{enemy:[1],minMoves:59,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:1,y:2},enemyPosition:{x:5,y:4},exitPosition:{x:5,y:1},enemyPosition2:{x:1,y:1}}", "{enemy:[1],minMoves:21,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:6,y:3},enemyPosition:{x:4,y:5},exitPosition:{x:3,y:5},enemyPosition2:{x:0,y:0}}", "{enemy:[1],minMoves:20,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:4,y:6},enemyPosition:{x:0,y:3},exitPosition:{x:2,y:4},enemyPosition2:{x:0,y:0}}", "{enemy:[2],minMoves:20,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:4,y:6},enemyPosition:{x:5,y:1},exitPosition:{x:6,y:3},enemyPosition2:{x:0,y:0}}", "{enemy:[1],minMoves:63,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:5,y:6},enemyPosition:{x:1,y:6},exitPosition:{x:2,y:1},enemyPosition2:{x:1,y:1}}", "{enemy:[1],minMoves:79,squares:[[{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:2,y:2},enemyPosition:{x:1,y:1},exitPosition:{x:0,y:1},enemyPosition2:{x:1,y:1}}" }, { "{enemy:[0],minMoves:11,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:fals e,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:3,y:3},enemyPosition:{x:6,y:2},exitPosition:{x:6,y:6}}", "{enemy:[0],minMoves:21,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:2,y:5},enemyPosition:{x:3,y:2},exitPosition:{x:3,y:3},enemyPosition2:{x:1,y:1}}", "{enemy:[0],minMoves:23,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:2,y:5},enemyPosition:{x:5,y:5},exitPosition:{x:6,y:6},enemyPosition2:{x:1,y:1}}", "{enemy:[0],minMoves:20,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:6,y:2},enemyPosition:{x:1,y:6},exitPosition:{x:3,y:1},enemyPosition2:{x:1,y:1}}", "{enemy:[0],minMoves:21,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:6,y:1},enemyPosition:{x:5,y:3},exitPosition:{x:6,y:4},enemyPosition2:{x:1,y:1}}", "{enemy:[0],minMoves:22,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:4,y:5},enemyPosition:{x:1,y:4},exitPosition:{x:2,y:1},enemyPosition2:{x:1,y:1}}", "{enemy:[0],minMoves:21,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:5,y:4},enemyPosition:{x:3,y:6},exitPosition:{x:5,y:7},enemyPosition2:{x:1,y:1}}", "{enemy:[0],minMoves:22,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:6,y:3},enemyPosition:{x:6,y:7},exitPosition:{x:2,y:7},enemyPosition2:{x:1,y:1}}", "{enemy:[0],minMoves:20,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:4,y:2},enemyPosition:{x:6,y:6},exitPosition:{x:2,y:4},enemyPosition2:{x:1,y:1}}", "{enemy:[0],minMoves:21,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:3,y:4},enemyPosition:{x:4,y:2},exitPosition:{x:3,y:3},enemyPosition2:{x:1,y:1}}", "{enemy:[0],minMoves:21,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:4,y:5},enemyPosition:{x:3,y:5},exitPosition:{x:3,y:5},enemyPosition2:{x:1,y:1}}", "{enemy:[0],minMoves:20,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:4,y:4},enemyPosition:{x:1,y:1},exitPosition:{x:7,y:1},enemyPosition2:{x:1,y:1}}", "{enemy:[0],minMoves:22,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:6,y:1},enemyPosition:{x:4,y:3},exitPosition:{x:1,y:4},enemyPosition2:{x:1,y:1}}", "{enemy:[0],minMoves:23,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:3,y:2},enemyPosition:{x:5,y:6},exitPosition:{x:6,y:7},enemyPosition2:{x:1,y:1}}", "{enemy:[0],minMoves:20,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:6,y:6},enemyPosition:{x:3,y:5},exitPosition:{x:3,y:5},enemyPosition2:{x:1,y:1}}", "{enemy:[0],minMoves:20,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:2,y:6},enemyPosition:{x:6,y:6},exitPosition:{x:6,y:5},enemyPosition2:{x:1,y:1}}", "{enemy:[0],minMoves:20,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:4,y:5},enemyPosition:{x:1,y:7},exitPosition:{x:4,y:7},enemyPosition2:{x:1,y:1}}", "{enemy:[0],minMoves:20,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:2,y:3},enemyPosition:{x:1,y:2},exitPosition:{x:5,y:1},enemyPosition2:{x:1,y:1}}", }, { "{enemy:[0,1],minMoves:6,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:6,y:6},enemyPosition:{x:2,y:5},exitPosition:{x:4,y:2},enemyPosition2:{x:2,y:6}}", "{enemy:[0,1],minMoves:2,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:2,y:5},enemyPosition:{x:6,y:4},exitPosition:{x:4,y:5},enemyPosition2:{x:3,y:3}}", "{enemy:[1,2],minMoves:6,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:6,y:4},enemyPosition:{x:4,y:6},exitPosition:{x:2,y:2},enemyPosition2:{x:5,y:6}}", "{enemy:[1,2],minMoves:8,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:6,y:6},enemyPosition:{x:2,y:2},exitPosition:{x:2,y:4},enemyPosition2:{x:5,y:3}}", "{enemy:[1,2],minMoves:6,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:4,y:6},enemyPosition:{x:2,y:6},exitPosition:{x:5,y:4},enemyPosition2:{x:5,y:2}}", "{enemy:[1,2],minMoves:16,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:3,y:4},enemyPosition:{x:5,y:3},exitPosition:{x:6,y:3},enemyPosition2:{x:5,y:4}}", "{enemy:[1,2],minMoves:17,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:3,y:5},enemyPosition:{x:1,y:3},exitPosition:{x:2,y:1},enemyPosition2:{x:1,y:1}}", "{enemy:[1,2],minMoves:18,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:3,y:5},enemyPosition:{x:5,y:2},exitPosition:{x:2,y:3},enemyPosition2:{x:2,y:2}}", "{enemy:[1,2],minMoves:20,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:5,y:1},enemyPosition:{x:6,y:7},exitPosition:{x:1,y:5},enemyPosition2:{x:2,y:7}}", "{enemy:[1,2],minMoves:17,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:5,y:6},enemyPosition:{x:6,y:1},exitPosition:{x:4,y:2},enemyPosition2:{x:4,y:1}}", "{enemy:[1,2],minMoves:17,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:0,y:5},enemyPosition:{x:5,y:1},exitPosition:{x:6,y:7},enemyPosition2:{x:6,y:1}}", "{enemy:[1,2],minMoves:16,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:6,y:1},enemyPosition:{x:5,y:6},exitPosition:{x:4,y:7},enemyPosition2:{x:6,y:4}}", "{enemy:[0,2],minMoves:21,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:3,y:5},enemyPosition:{x:2,y:4},exitPosition:{x:2,y:3},enemyPosition2:{x:2,y:3}}", "{enemy:[0,1],minMoves:16,squares:[[{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:0,y:0},enemyPosition:{x:3,y:6},exitPosition:{x:7,y:1},enemyPosition2:{x:4,y:5}}", "{enemy:[0,1],minMoves:18,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:3,y:5},enemyPosition:{x:7,y:3},exitPosition:{x:1,y:1},enemyPosition2:{x:3,y:1}}", "{enemy:[0,1],minMoves:18,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:6,y:1},enemyPosition:{x:3,y:5},exitPosition:{x:4,y:5},enemyPosition2:{x:1,y:6}}", "{enemy:[0,1],minMoves:25,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:7,y:2},enemyPosition:{x:6,y:1},exitPosition:{x:7,y:1},enemyPosition2:{x:2,y:0}}", "{enemy:[1,2],minMoves:34,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:2,y:3},enemyPosition:{x:5,y:5},exitPosition:{x:2,y:6},enemyPosition2:{x:6,y:5}}", "{enemy:[1,2],minMoves:22,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:4,y:6},enemyPosition:{x:2,y:5},exitPosition:{x:3,y:5},enemyPosition2:{x:2,y:6}}", "{enemy:[1,2],minMoves:21,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:7,y:7},enemyPosition:{x:1,y:7},exitPosition:{x:2,y:7},enemyPosition2:{x:2,y:2}}", "{enemy:[0,1],minMoves:20,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:2,y:3},enemyPosition:{x:5,y:4},exitPosition:{x:6,y:5},enemyPosition2:{x:6,y:5}}", "{enemy:[0,1],minMoves:21,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:4,y:5},enemyPosition:{x:6,y:4},exitPosition:{x:6,y:6},enemyPosition2:{x:6,y:6}}", "{enemy:[0,2],minMoves:28,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:3,y:4},enemyPosition:{x:6,y:6},exitPosition:{x:1,y:7},enemyPosition2:{x:3,y:5}}", "{enemy:[0,2],minMoves:23,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:4,y:3},enemyPosition:{x:3,y:1},exitPosition:{x:6,y:5},enemyPosition2:{x:5,y:1}}", "{enemy:[1,2],minMoves:21,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:4,y:5},enemyPosition:{x:6,y:5},exitPosition:{x:6,y:6},enemyPosition2:{x:6,y:6}}", "{enemy:[1,2],minMoves:20,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:2,y:2},enemyPosition:{x:2,y:4},exitPosition:{x:6,y:6},enemyPosition2:{x:2,y:6}}", "{enemy:[0,1],minMoves:23,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:5,y:7},enemyPosition:{x:4,y:1},exitPosition:{x:1,y:5},enemyPosition2:{x:2,y:4}}", "{enemy:[0,1],minMoves:29,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:5,y:6},enemyPosition:{x:3,y:4},exitPosition:{x:2,y:2},enemyPosition2:{x:4,y:2}}", "{enemy:[0,2],minMoves:23,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:4,y:5},enemyPosition:{x:6,y:4},exitPosition:{x:6,y:6},enemyPosition2:{x:6,y:6}}", "{enemy:[0,1],minMoves:23,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:4,y:2},enemyPosition:{x:2,y:6},exitPosition:{x:5,y:6},enemyPosition2:{x:6,y:4}}", "{enemy:[1,2],minMoves:23,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:6,y:1},enemyPosition:{x:3,y:6},exitPosition:{x:1,y:6},enemyPosition2:{x:1,y:5}}", "{enemy:[0,2],minMoves:23,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:3,y:4},enemyPosition:{x:6,y:5},exitPosition:{x:6,y:6},enemyPosition2:{x:4,y:6}}", "{enemy:[0,1],minMoves:29,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:5,y:6},enemyPosition:{x:3,y:4},exitPosition:{x:2,y:2},enemyPosition2:{x:4,y:2}}", "{enemy:[0,2],minMoves:20,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:2,y:2},enemyPosition:{x:3,y:3},exitPosition:{x:1,y:1},enemyPosition2:{x:1,y:1}}", "{enemy:[0,2],minMoves:28,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:5,y:6},enemyPosition:{x:4,y:2},exitPosition:{x:1,y:2},enemyPosition2:{x:1,y:2}}", "{enemy:[1,2],minMoves:21,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:3,y:5},enemyPosition:{x:5,y:1},exitPosition:{x:2,y:1},enemyPosition2:{x:3,y:1}}", }, { "{enemy:[1],minMoves:20,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:3,y:4},enemyPosition:{x:2,y:4},exitPosition:{x:2,y:2}}", "{enemy:[2],minMoves:16,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:3,y:4},enemyPosition:{x:4,y:2},exitPosition:{x:4,y:3}}", "{enemy:[1],minMoves:12,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:4,y:4},enemyPosition:{x:3,y:3},exitPosition:{x:2,y:4}}", "{enemy:[1,2],minMoves:20,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:1,y:6},enemyPosition:{x:1,y:1},exitPosition:{x:6,y:3},enemyPosition2:{x:6,y:1}}", "{enemy:[0],minMoves:39,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:0,y:1},enemyPosition:{x:5,y:7},exitPosition:{x:1,y:5}}", "{enemy:[2],minMoves:21,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:4,y:3},enemyPosition:{x:6,y:5},exitPosition:{x:5,y:3}}", "{enemy:[1],minMoves:22,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:0,y:5},enemyPosition:{x:0,y:0},exitPosition:{x:6,y:1}}", "{enemy:[2],minMoves:27,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:1,y:4},enemyPosition:{x:6,y:6},exitPosition:{x:7,y:1}}", "{enemy:[2],minMoves:20,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:4,y:4},enemyPosition:{x:5,y:3},exitPosition:{x:6,y:4}}", "{enemy:[0,2],minMoves:20,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:3,y:3},enemyPosition:{x:5,y:5},exitPosition:{x:2,y:6},enemyPosition2:{x:3,y:5}}", "{enemy:[2],minMoves:21,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:1,y:0},enemyPosition:{x:6,y:6},exitPosition:{x:4,y:0}}", "{enemy:[0],minMoves:23,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:6,y:6},enemyPosition:{x:2,y:4},exitPosition:{x:4,y:1}}", "{enemy:[1],minMoves:21,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:3,y:4},enemyPosition:{x:3,y:2},exitPosition:{x:6,y:2}}", "{enemy:[1],minMoves:43,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:5,y:4},enemyPosition:{x:6,y:6},exitPosition:{x:5,y:6}}", "{enemy:[2],minMoves:20,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:3,y:5},enemyPosition:{x:1,y:6},exitPosition:{x:1,y:6}}", "{enemy:[0],minMoves:22,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:4,y:5},enemyPosition:{x:4,y:6},exitPosition:{x:3,y:4}}", "{enemy:[2],minMoves:20,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:3,y:4},enemyPosition:{x:3,y:6},exitPosition:{x:3,y:6}}", "{enemy:[1],minMoves:20,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:5,y:5},enemyPosition:{x:6,y:5},exitPosition:{x:4,y:2}}", "{enemy:[2],minMoves:21,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:0,y:5},enemyPosition:{x:6,y:6},exitPosition:{x:6,y:7}}", "{enemy:[2],minMoves:21,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:6,y:6},enemyPosition:{x:4,y:2},exitPosition:{x:6,y:3}}", "{enemy:[0,1],minMoves:20,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:5,y:6},enemyPosition:{x:3,y:1},exitPosition:{x:4,y:2},enemyPosition2:{x:2,y:2}}", "{enemy:[2],minMoves:20,squares:[[{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:5,y:7},enemyPosition:{x:2,y:3},exitPosition:{x:4,y:8}}", "{enemy:[2],minMoves:21,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:5,y:5},enemyPosition:{x:5,y:6},exitPosition:{x:6,y:5}}", "{enemy:[2],minMoves:20,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:6,y:4},enemyPosition:{x:4,y:6},exitPosition:{x:4,y:6}}", "{enemy:[0],minMoves:26,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:6,y:7},enemyPosition:{x:4,y:2},exitPosition:{x:5,y:2}}", "{enemy:[1],minMoves:21,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:6,y:6},enemyPosition:{x:4,y:3},exitPosition:{x:5,y:2}}", "{enemy:[2],minMoves:20,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:6,y:5},enemyPosition:{x:2,y:4},exitPosition:{x:2,y:3}}", "{enemy:[0,1],minMoves:22,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:1,y:1},enemyPosition:{x:2,y:6},exitPosition:{x:1,y:4},enemyPosition2:{x:2,y:4}}", "{enemy:[1],minMoves:24,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:2,y:1},enemyPosition:{x:7,y:1},exitPosition:{x:3,y:2}}", "{enemy:[0],minMoves:20,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:7,y:4},enemyPosition:{x:1,y:4},exitPosition:{x:1,y:6}}", "{enemy:[1],minMoves:30,squares:[[{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:2,y:6},enemyPosition:{x:6,y:2},exitPosition:{x:6,y:1}}", "{enemy:[2],minMoves:21,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:7,y:6},enemyPosition:{x:3,y:3},exitPosition:{x:1,y:5}}", "{enemy:[1],minMoves:43,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:2,y:7},enemyPosition:{x:4,y:6},exitPosition:{x:7,y:7}}", "{enemy:[2],minMoves:20,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:4,y:3},enemyPosition:{x:5,y:2},exitPosition:{x:6,y:4}}", "{enemy:[1],minMoves:22,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:7,y:5},enemyPosition:{x:6,y:7},exitPosition:{x:5,y:6}}", "{enemy:[2],minMoves:23,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:5,y:2},enemyPosition:{x:3,y:6},exitPosition:{x:5,y:4}}", "{enemy:[0],minMoves:21,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:4,y:2},enemyPosition:{x:6,y:5},exitPosition:{x:5,y:4}}", "{enemy:[1],minMoves:34,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:4,y:7},enemyPosition:{x:1,y:7},exitPosition:{x:2,y:5}}", "{enemy:[2],minMoves:24,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:3,y:5},enemyPosition:{x:7,y:7},exitPosition:{x:6,y:4}}", "{enemy:[1],minMoves:22,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:4,y:4},enemyPosition:{x:2,y:3},exitPosition:{x:3,y:1}}", "{enemy:[0],minMoves:23,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:1,y:1},enemyPosition:{x:3,y:2},exitPosition:{x:3,y:3}}", "{enemy:[1],minMoves:21,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:4,y:3},enemyPosition:{x:2,y:5},exitPosition:{x:3,y:5}}", "{enemy:[2],minMoves:33,squares:[[{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:4,y:1},enemyPosition:{x:0,y:5},exitPosition:{x:0,y:0}}", "{enemy:[1],minMoves:24,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:5,y:4},enemyPosition:{x:6,y:4},exitPosition:{x:6,y:5}}", "{enemy:[2],minMoves:34,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:2,y:7},enemyPosition:{x:6,y:3},exitPosition:{x:6,y:5}}", "{enemy:[1],minMoves:22,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:1,y:4},enemyPosition:{x:2,y:3},exitPosition:{x:2,y:3}}", "{enemy:[1],minMoves:21,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:5,y:5},enemyPosition:{x:6,y:7},exitPosition:{x:7,y:4}}", "{enemy:[1,2],minMoves:20,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:1,y:3},enemyPosition:{x:6,y:1},exitPosition:{x:5,y:1},enemyPosition2:{x:3,y:2}}", "{enemy:[1],minMoves:22,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:7,y:2},enemyPosition:{x:5,y:5},exitPosition:{x:0,y:5}}", "{enemy:[2],minMoves:24,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:6,y:1},enemyPosition:{x:0,y:1},exitPosition:{x:3,y:2}}", "{enemy:[0],minMoves:26,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:4,y:2},enemyPosition:{x:8,y:3},exitPosition:{x:6,y:8}}", "{enemy:[2],minMoves:32,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:3,y:2},enemyPosition:{x:7,y:6},exitPosition:{x:6,y:2}}", "{enemy:[1],minMoves:20,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:6,y:2},enemyPosition:{x:7,y:3},exitPosition:{x:6,y:4}}", "{enemy:[1],minMoves:25,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:5,y:2},enemyPosition:{x:1,y:7},exitPosition:{x:2,y:7}}", "{enemy:[2],minMoves:24,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:5,y:1},enemyPosition:{x:6,y:1},exitPosition:{x:7,y:5}}", "{enemy:[2],minMoves:22,squares:[[{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true}]],width:9,height:9,playerPosition:{x:6,y:6},enemyPosition:{x:0,y:0},exitPosition:{x:0,y:3}}", "{enemy:[1],minMoves:24,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:4,y:4},enemyPosition:{x:7,y:3},exitPosition:{x:6,y:0}}", "{enemy:[2],minMoves:20,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:3,y:2},enemyPosition:{x:5,y:2},exitPosition:{x:5,y:2}}", "{enemy:[2],minMoves:35,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:true}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:3,y:2},enemyPosition:{x:2,y:0},exitPosition:{x:0,y:0}}", "{enemy:[1],minMoves:32,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:1,y:6},enemyPosition:{x:6,y:3},exitPosition:{x:2,y:4}}", "{enemy:[2],minMoves:21,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:4,y:2},enemyPosition:{x:7,y:7},exitPosition:{x:7,y:6}}", "{enemy:[1,2],minMoves:20,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:5,y:2},enemyPosition:{x:1,y:4},exitPosition:{x:2,y:5},enemyPosition2:{x:2,y:4}}", "{enemy:[1],minMoves:20,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:4,y:4},enemyPosition:{x:2,y:6},exitPosition:{x:2,y:6}}", "{enemy:[2],minMoves:21,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:3,y:6},enemyPosition:{x:5,y:5},exitPosition:{x:4,y:6}}", "{enemy:[1],minMoves:20,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:3,y:1},enemyPosition:{x:7,y:4},exitPosition:{x:7,y:3}}", "{enemy:[2],minMoves:24,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:5,y:5},enemyPosition:{x:2,y:6},exitPosition:{x:2,y:5}}", "{enemy:[1],minMoves:23,squares:[[{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:true}]],width:9,height:9,playerPosition:{x:6,y:3},enemyPosition:{x:4,y:8},exitPosition:{x:1,y:8}}", "{enemy:[2],minMoves:20,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:1,y:4},enemyPosition:{x:5,y:7},exitPosition:{x:7,y:2}}", "{enemy:[0,1],minMoves:24,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:4,y:6},enemyPosition:{x:6,y:1},exitPosition:{x:3,y:1},enemyPosition2:{x:5,y:2}}", "{enemy:[1],minMoves:21,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:5,y:4},enemyPosition:{x:4,y:2},exitPosition:{x:5,y:2}}", "{enemy:[0],minMoves:33,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:6,y:7},enemyPosition:{x:8,y:4},exitPosition:{x:8,y:2}}", "{enemy:[1],minMoves:24,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:7,y:5},enemyPosition:{x:2,y:1},exitPosition:{x:2,y:1}}", "{enemy:[2],minMoves:22,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:2,y:1},enemyPosition:{x:3,y:7},exitPosition:{x:4,y:7}}", "{enemy:[1],minMoves:25,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:6,y:3},enemyPosition:{x:2,y:6},exitPosition:{x:5,y:6}}", "{enemy:[1],minMoves:27,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:7,y:1},enemyPosition:{x:7,y:4},exitPosition:{x:7,y:7}}", "{enemy:[2],minMoves:33,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:0,y:8},enemyPosition:{x:0,y:2},exitPosition:{x:2,y:4}}", "{enemy:[1],minMoves:23,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:2,y:4},enemyPosition:{x:7,y:5},exitPosition:{x:6,y:6}}", "{enemy:[0],minMoves:23,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:2,y:1},enemyPosition:{x:3,y:7},exitPosition:{x:0,y:4}}", "{enemy:[0,1],minMoves:20,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:2,y:2},enemyPosition:{x:4,y:6},exitPosition:{x:2,y:3},enemyPosition2:{x:3,y:4}}", "{enemy:[2],minMoves:26,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:6,y:4},enemyPosition:{x:7,y:7},exitPosition:{x:7,y:3}}", "{enemy:[1],minMoves:20,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:3,y:5},enemyPosition:{x:2,y:5},exitPosition:{x:2,y:6}}", "{enemy:[2],minMoves:30,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:6,y:1},enemyPosition:{x:2,y:2},exitPosition:{x:2,y:1}}", "{enemy:[0,1],minMoves:24,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:2,y:5},enemyPosition:{x:5,y:3},exitPosition:{x:6,y:6},enemyPosition2:{x:4,y:4}}", "{enemy:[1],minMoves:20,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:6,y:0},enemyPosition:{x:0,y:5},exitPosition:{x:0,y:6}}", "{enemy:[1],minMoves:20,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:1,y:4},enemyPosition:{x:1,y:6},exitPosition:{x:2,y:6}}", "{enemy:[0],minMoves:20,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:6,y:5},enemyPosition:{x:2,y:2},exitPosition:{x:3,y:2}}", "{enemy:[1],minMoves:24,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:6,y:4},enemyPosition:{x:3,y:5},exitPosition:{x:1,y:3}}", "{enemy:[0,1],minMoves:20,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:4,y:3},enemyPosition:{x:5,y:7},exitPosition:{x:6,y:7},enemyPosition2:{x:6,y:5}}", "{enemy:[0],minMoves:30,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:5,y:6},enemyPosition:{x:2,y:7},exitPosition:{x:5,y:8}}", "{enemy:[2],minMoves:27,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:2,y:1},enemyPosition:{x:6,y:2},exitPosition:{x:6,y:3}}" } }; }
core/src/es/seastorm/merlin/Constants.java
package es.seastorm.merlin; public class Constants { public static float WIDTH = 1280; public static float HEIGHT = 720; public static int FLOOR_SIZE = 80; public static int LABYRINT_WIDTH = 9; public static int LABYRINT_HEIGHT = 9; public static int ANIMAL_BUNNY = 5; public static int ANIMAL_FOX = 0; public static int ANIMAL_DOG1 = 1; public static int ANIMAL_DOG2 = 2; public static int ANIMAL_BURROW = 6; public static final String TEXTURE_ATLAS_OBJECTS = "images/merlin-images.pack.atlas"; public static final String PREFERENCES = "merlin.prefs"; public static final int DIRECTION_UP = 0; public static final int DIRECTION_RIGHT = 1; public static final int DIRECTION_DOWN = 2; public static final int DIRECTION_LEFT = 3; public static final int DIRECTION_PASS = 4; public static String[][] LEVEL_LIST = { { "{enemy:[1],minMoves:10,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:2,y:5},enemyPosition:{x:3,y:4},exitPosition:{x:6,y:5}}", "{enemy:[1],minMoves:5,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:5,y:5},enemyPosition:{x:5,y:2},exitPosition:{x:5,y:4}}", "{enemy:[1],minMoves:5,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:3,y:5},enemyPosition:{x:3,y:3},exitPosition:{x:5,y:5}}", "{enemy:[1],minMoves:4,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:4,y:5},enemyPosition:{x:4,y:3},exitPosition:{x:3,y:4}}", "{enemy:[1],minMoves:8,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:4,y:3},enemyPosition:{x:4,y:2},exitPosition:{x:5,y:3}}", "{enemy:[1],minMoves:9,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:3,y:3},enemyPosition:{x:5,y:2},exitPosition:{x:5,y:2}}", "{enemy:[1],minMoves:12,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:3,y:4},enemyPosition:{x:4,y:3},exitPosition:{x:5,y:2}}", "{enemy:[1],minMoves:6,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:1,y:3},enemyPosition:{x:6,y:5},exitPosition:{x:4,y:4}}", "{enemy:[1],minMoves:7,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLef:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:3,y:2},enemyPosition:{x:2,y:5},exitPosition:{x:2,y:3}}", "{enemy:[2],minMoves:11,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:3,y:2},enemyPosition:{x:2,y:2},exitPosition:{x:2,y:4}}", "{enemy:[2],minMoves:9,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:2,y:6},enemyPosition:{x:2,y:1},exitPosition:{x:4,y:3}}", "{enemy:[2],minMoves:13,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:3,y:5},enemyPosition:{x:3,y:7},exitPosition:{x:5,y:6}}", "{enemy:[1],minMoves:23,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:1,y:8},enemyPosition:{x:8,y:5},exitPosition:{x:5,y:4},enemyPosition2:{x:0,y:0}}", "{enemy:[1],minMoves:21,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:4,y:5},enemyPosition:{x:5,y:1},exitPosition:{x:5,y:3},enemyPosition2:{x:0,y:0}}", "{enemy:[1],minMoves:27,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:3,y:3},enemyPosition:{x:6,y:4},exitPosition:{x:5,y:2},enemyPosition2:{x:1,y:1}}", "{enemy:[1],minMoves:26,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:7,y:7},enemyPosition:{x:3,y:7},exitPosition:{x:3,y:7},enemyPosition2:{x:0,y:0}}", "{enemy:[2],minMoves:25,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:5,y:6},enemyPosition:{x:1,y:5},exitPosition:{x:4,y:1},enemyPosition2:{x:0,y:0}}", "{enemy:[1],minMoves:20,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:6,y:3},enemyPosition:{x:6,y:2},exitPosition:{x:3,y:3},enemyPosition2:{x:0,y:0}}", "{enemy:[2],minMoves:24,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:1,y:5},enemyPosition:{x:2,y:1},exitPosition:{x:2,y:4},enemyPosition2:{x:0,y:0}}", "{enemy:[2],minMoves:21,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:5,y:2},enemyPosition:{x:5,y:3},exitPosition:{x:3,y:3},enemyPosition2:{x:0,y:0}}", "{enemy:[1],minMoves:21,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:3,y:5},enemyPosition:{x:5,y:4},exitPosition:{x:4,y:2},enemyPosition2:{x:0,y:0}}", "{enemy:[2],minMoves:23,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:6,y:4},enemyPosition:{x:1,y:3},exitPosition:{x:3,y:6},enemyPosition2:{x:0,y:0}}", "{enemy:[2],minMoves:23,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:3,y:6},enemyPosition:{x:5,y:5},exitPosition:{x:5,y:5},enemyPosition2:{x:0,y:0}}", "{enemy:[2],minMoves:22,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:3,y:2},enemyPosition:{x:5,y:4},exitPosition:{x:4,y:2},enemyPosition2:{x:0,y:0}}", "{enemy:[1],minMoves:40,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:3,y:3},enemyPosition:{x:3,y:6},exitPosition:{x:6,y:2},enemyPosition2:{x:1,y:1}}", "{enemy:[1],minMoves:20,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:3,y:3},enemyPosition:{x:2,y:3},exitPosition:{x:2,y:2},enemyPosition2:{x:0,y:0}}", "{enemy:[2],minMoves:24,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:3,y:4},enemyPosition:{x:5,y:3},exitPosition:{x:4,y:5},enemyPosition2:{x:0,y:0}}", "{enemy:[1],minMoves:21,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:2,y:4},enemyPosition:{x:5,y:1},exitPosition:{x:5,y:2},enemyPosition2:{x:0,y:0}}", "{enemy:[2],minMoves:21,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:2,y:2},enemyPosition:{x:2,y:6},exitPosition:{x:3,y:4},enemyPosition2:{x:0,y:0}}", "{enemy:[2],minMoves:24,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:3,y:4},enemyPosition:{x:6,y:3},exitPosition:{x:6,y:5},enemyPosition2:{x:0,y:0}}", "{enemy:[1],minMoves:59,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:1,y:2},enemyPosition:{x:5,y:4},exitPosition:{x:5,y:1},enemyPosition2:{x:1,y:1}}", "{enemy:[1],minMoves:21,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:6,y:3},enemyPosition:{x:4,y:5},exitPosition:{x:3,y:5},enemyPosition2:{x:0,y:0}}", "{enemy:[1],minMoves:20,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:4,y:6},enemyPosition:{x:0,y:3},exitPosition:{x:2,y:4},enemyPosition2:{x:0,y:0}}", "{enemy:[2],minMoves:20,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:4,y:6},enemyPosition:{x:5,y:1},exitPosition:{x:6,y:3},enemyPosition2:{x:0,y:0}}", "{enemy:[1],minMoves:63,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:5,y:6},enemyPosition:{x:1,y:6},exitPosition:{x:2,y:1},enemyPosition2:{x:1,y:1}}", "{enemy:[1],minMoves:79,squares:[[{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:2,y:2},enemyPosition:{x:1,y:1},exitPosition:{x:0,y:1},enemyPosition2:{x:1,y:1}}" }, { "{enemy:[0],minMoves:11,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:fals e,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:3,y:3},enemyPosition:{x:6,y:2},exitPosition:{x:6,y:6}}", "{enemy:[0],minMoves:12,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:4,y:3},enemyPosition:{x:6,y:6},exitPosition:{x:4,y:5}}", "{enemy:[0],minMoves:13,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:3,y:2},enemyPosition:{x:3,y:5},exitPosition:{x:4,y:6}}", "{enemy:[0],minMoves:20,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:0,y:8},enemyPosition:{x:8,y:0},exitPosition:{x:2,y:2}}", "{enemy:[0],minMoves:13,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true}]],width:9,height:9,playerPosition:{x:8,y:4},enemyPosition:{x:0,y:7},exitPosition:{x:3,y:8}}", "{enemy:[0],minMoves:20,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRi ght:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:5,y:4},enemyPosition:{x:3,y:6},exitPosition:{x:2,y:7}}", "{enemy:[0],minMoves:25,squares:[[{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:1,y:6},enemyPosition:{x:2,y:4},exitPosition:{x:0,y:4}}", "{enemy:[0],minMoves:23,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:4,y:8},enemyPosition:{x:2,y:7},exitPosition:{x:4,y:5}}", "{enemy:[0],minMoves:22,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRigh t:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:5,y:3},enemyPosition:{x:1,y:5},exitPosition:{x:1,y:7}}", "{enemy:[0],minMoves:23,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:2,y:2},enemyPosition:{x:6,y:2},exitPosition:{x:6,y:5}}", "{enemy:[0],minMoves:31,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:2,y:7},enemyPosition:{x:2,y:1},exitPosition:{x:1,y:1}}", "{enemy:[0],minMoves:22,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:6,y:3},enemyPosition:{x:6,y:2},exitPosition:{x:5,y:2}}", "{enemy:[0],minMoves:23,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:2,y:2},enemyPosition:{x:3,y:4},exitPosition:{x:2,y:5}}", "{enemy:[0],minMoves:38,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:7,y:5},enemyPosition:{x:1,y:7},exitPosition:{x:1,y:7}}", "{enemy:[0],minMoves:20,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:5,y:4},enemyPosition:{x:4,y:2},exitPosition:{x:5,y:2}}", "{enemy:[0],minMoves:25,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:2,y:5},enemyPosition:{x:4,y:2},exitPosition:{x:7,y:4}}", "{enemy:[0],minMoves:21,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:3,y:5},enemyPosition:{x:4,y:2},exitPosition:{x:5,y:2}}", "{enemy:[0],minMoves:23,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:1,y:1},enemyPosition:{x:4,y:1},exitPosition:{x:4,y:3}}", "{enemy:[0],minMoves:43,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:0,y:2},enemyPosition:{x:5,y:7},exitPosition:{x:1,y:7}}", "{enemy:[0],minMoves:20,squares:[[{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:3,y:3},enemyPosition:{x:7,y:6},exitPosition:{x:7,y:1}}", "{enemy:[0],minMoves:24,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:3,y:5},enemyPosition:{x:1,y:3},exitPosition:{x:2,y:2}}", "{enemy:[0],minMoves:22,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:7,y:4},enemyPosition:{x:1,y:1},exitPosition:{x:4,y:1}}", "{enemy:[0],minMoves:20,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:2,y:8},enemyPosition:{x:2,y:0},exitPosition:{x:2,y:0}}", "{enemy:[0],minMoves:20,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:1,y:3},enemyPosition:{x:2,y:1},exitPosition:{x:3,y:1}}", "{enemy:[0],minMoves:21,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:2,y:5},enemyPosition:{x:3,y:3},exitPosition:{x:2,y:4}}", "{enemy:[0],minMoves:23,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:2,y:4},enemyPosition:{x:3,y:2},exitPosition:{x:4,y:3}}", "{enemy:[0],minMoves:20,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:2,y:3},enemyPosition:{x:5,y:1},exitPosition:{x:4,y:1}}", "{enemy:[0],minMoves:28,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:0,y:6},enemyPosition:{x:7,y:6},exitPosition:{x:6,y:7}}", "{enemy:[0],minMoves:20,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:2,y:8},enemyPosition:{x:8,y:5},exitPosition:{x:8,y:4}}", "{enemy:[0],minMoves:21,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:5,y:6},enemyPosition:{x:2,y:2},exitPosition:{x:2,y:2}}", "{enemy:[0],minMoves:24,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:7,y:8},enemyPosition:{x:8,y:6},exitPosition:{x:5,y:5}}", "{enemy:[0],minMoves:22,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:6,y:6},enemyPosition:{x:2,y:4},exitPosition:{x:7,y:4}}", "{enemy:[0],minMoves:21,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:7,y:4},enemyPosition:{x:2,y:1},exitPosition:{x:3,y:5}}", "{enemy:[0],minMoves:24,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:5,y:2},enemyPosition:{x:4,y:4},exitPosition:{x:5,y:4}}", "{enemy:[0],minMoves:23,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLef t:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true}]],width:9,height:9,playerPosition:{x:7,y:2},enemyPosition:{x:0,y:8},exitPosition:{x:6,y:8}}", "{enemy:[0],minMoves:27,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:3,y:5},enemyPosition:{x:1,y:5},exitPosition:{x:2,y:7}}", }, { "{enemy:[0,1],minMoves:6,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:6,y:6},enemyPosition:{x:2,y:5},exitPosition:{x:4,y:2},enemyPosition2:{x:2,y:6}}", "{enemy:[0,1],minMoves:2,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:2,y:5},enemyPosition:{x:6,y:4},exitPosition:{x:4,y:5},enemyPosition2:{x:3,y:3}}", "{enemy:[1,2],minMoves:6,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:6,y:4},enemyPosition:{x:4,y:6},exitPosition:{x:2,y:2},enemyPosition2:{x:5,y:6}}", "{enemy:[1,2],minMoves:8,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:6,y:6},enemyPosition:{x:2,y:2},exitPosition:{x:2,y:4},enemyPosition2:{x:5,y:3}}", "{enemy:[1,2],minMoves:6,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:4,y:6},enemyPosition:{x:2,y:6},exitPosition:{x:5,y:4},enemyPosition2:{x:5,y:2}}", "{enemy:[1,2],minMoves:16,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:3,y:4},enemyPosition:{x:5,y:3},exitPosition:{x:6,y:3},enemyPosition2:{x:5,y:4}}", "{enemy:[1,2],minMoves:17,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:3,y:5},enemyPosition:{x:1,y:3},exitPosition:{x:2,y:1},enemyPosition2:{x:1,y:1}}", "{enemy:[1,2],minMoves:18,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:3,y:5},enemyPosition:{x:5,y:2},exitPosition:{x:2,y:3},enemyPosition2:{x:2,y:2}}", "{enemy:[1,2],minMoves:20,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:5,y:1},enemyPosition:{x:6,y:7},exitPosition:{x:1,y:5},enemyPosition2:{x:2,y:7}}", "{enemy:[1,2],minMoves:17,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:5,y:6},enemyPosition:{x:6,y:1},exitPosition:{x:4,y:2},enemyPosition2:{x:4,y:1}}", "{enemy:[1,2],minMoves:17,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:0,y:5},enemyPosition:{x:5,y:1},exitPosition:{x:6,y:7},enemyPosition2:{x:6,y:1}}", "{enemy:[1,2],minMoves:16,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:6,y:1},enemyPosition:{x:5,y:6},exitPosition:{x:4,y:7},enemyPosition2:{x:6,y:4}}", "{enemy:[0,2],minMoves:21,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:3,y:5},enemyPosition:{x:2,y:4},exitPosition:{x:2,y:3},enemyPosition2:{x:2,y:3}}", "{enemy:[0,1],minMoves:16,squares:[[{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:0,y:0},enemyPosition:{x:3,y:6},exitPosition:{x:7,y:1},enemyPosition2:{x:4,y:5}}", "{enemy:[0,1],minMoves:18,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:3,y:5},enemyPosition:{x:7,y:3},exitPosition:{x:1,y:1},enemyPosition2:{x:3,y:1}}", "{enemy:[0,1],minMoves:18,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:6,y:1},enemyPosition:{x:3,y:5},exitPosition:{x:4,y:5},enemyPosition2:{x:1,y:6}}", "{enemy:[0,1],minMoves:25,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:7,y:2},enemyPosition:{x:6,y:1},exitPosition:{x:7,y:1},enemyPosition2:{x:2,y:0}}", "{enemy:[1,2],minMoves:34,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:2,y:3},enemyPosition:{x:5,y:5},exitPosition:{x:2,y:6},enemyPosition2:{x:6,y:5}}", "{enemy:[1,2],minMoves:22,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:4,y:6},enemyPosition:{x:2,y:5},exitPosition:{x:3,y:5},enemyPosition2:{x:2,y:6}}", "{enemy:[1,2],minMoves:21,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:7,y:7},enemyPosition:{x:1,y:7},exitPosition:{x:2,y:7},enemyPosition2:{x:2,y:2}}", "{enemy:[0,1],minMoves:20,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:2,y:3},enemyPosition:{x:5,y:4},exitPosition:{x:6,y:5},enemyPosition2:{x:6,y:5}}", "{enemy:[0,1],minMoves:21,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:4,y:5},enemyPosition:{x:6,y:4},exitPosition:{x:6,y:6},enemyPosition2:{x:6,y:6}}", "{enemy:[0,2],minMoves:28,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:3,y:4},enemyPosition:{x:6,y:6},exitPosition:{x:1,y:7},enemyPosition2:{x:3,y:5}}", "{enemy:[0,2],minMoves:23,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:4,y:3},enemyPosition:{x:3,y:1},exitPosition:{x:6,y:5},enemyPosition2:{x:5,y:1}}", "{enemy:[1,2],minMoves:21,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:4,y:5},enemyPosition:{x:6,y:5},exitPosition:{x:6,y:6},enemyPosition2:{x:6,y:6}}", "{enemy:[1,2],minMoves:20,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:2,y:2},enemyPosition:{x:2,y:4},exitPosition:{x:6,y:6},enemyPosition2:{x:2,y:6}}", "{enemy:[0,1],minMoves:23,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:5,y:7},enemyPosition:{x:4,y:1},exitPosition:{x:1,y:5},enemyPosition2:{x:2,y:4}}", "{enemy:[0,1],minMoves:29,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:5,y:6},enemyPosition:{x:3,y:4},exitPosition:{x:2,y:2},enemyPosition2:{x:4,y:2}}", "{enemy:[0,2],minMoves:23,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:4,y:5},enemyPosition:{x:6,y:4},exitPosition:{x:6,y:6},enemyPosition2:{x:6,y:6}}", "{enemy:[0,1],minMoves:23,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:4,y:2},enemyPosition:{x:2,y:6},exitPosition:{x:5,y:6},enemyPosition2:{x:6,y:4}}", "{enemy:[1,2],minMoves:23,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:6,y:1},enemyPosition:{x:3,y:6},exitPosition:{x:1,y:6},enemyPosition2:{x:1,y:5}}", "{enemy:[0,2],minMoves:23,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:3,y:4},enemyPosition:{x:6,y:5},exitPosition:{x:6,y:6},enemyPosition2:{x:4,y:6}}", "{enemy:[0,1],minMoves:29,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:5,y:6},enemyPosition:{x:3,y:4},exitPosition:{x:2,y:2},enemyPosition2:{x:4,y:2}}", "{enemy:[0,2],minMoves:20,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:2,y:2},enemyPosition:{x:3,y:3},exitPosition:{x:1,y:1},enemyPosition2:{x:1,y:1}}", "{enemy:[0,2],minMoves:28,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:5,y:6},enemyPosition:{x:4,y:2},exitPosition:{x:1,y:2},enemyPosition2:{x:1,y:2}}", "{enemy:[1,2],minMoves:21,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:3,y:5},enemyPosition:{x:5,y:1},exitPosition:{x:2,y:1},enemyPosition2:{x:3,y:1}}", }, { "{enemy:[1],minMoves:20,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:3,y:4},enemyPosition:{x:2,y:4},exitPosition:{x:2,y:2}}", "{enemy:[2],minMoves:16,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:3,y:4},enemyPosition:{x:4,y:2},exitPosition:{x:4,y:3}}", "{enemy:[1],minMoves:12,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:4,y:4},enemyPosition:{x:3,y:3},exitPosition:{x:2,y:4}}", "{enemy:[1,2],minMoves:20,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:1,y:6},enemyPosition:{x:1,y:1},exitPosition:{x:6,y:3},enemyPosition2:{x:6,y:1}}", "{enemy:[0],minMoves:39,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:0,y:1},enemyPosition:{x:5,y:7},exitPosition:{x:1,y:5}}", "{enemy:[2],minMoves:21,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:4,y:3},enemyPosition:{x:6,y:5},exitPosition:{x:5,y:3}}", "{enemy:[1],minMoves:22,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:0,y:5},enemyPosition:{x:0,y:0},exitPosition:{x:6,y:1}}", "{enemy:[2],minMoves:27,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:1,y:4},enemyPosition:{x:6,y:6},exitPosition:{x:7,y:1}}", "{enemy:[2],minMoves:20,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:4,y:4},enemyPosition:{x:5,y:3},exitPosition:{x:6,y:4}}", "{enemy:[0,2],minMoves:20,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:3,y:3},enemyPosition:{x:5,y:5},exitPosition:{x:2,y:6},enemyPosition2:{x:3,y:5}}", "{enemy:[2],minMoves:21,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:1,y:0},enemyPosition:{x:6,y:6},exitPosition:{x:4,y:0}}", "{enemy:[0],minMoves:23,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:6,y:6},enemyPosition:{x:2,y:4},exitPosition:{x:4,y:1}}", "{enemy:[1],minMoves:21,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:3,y:4},enemyPosition:{x:3,y:2},exitPosition:{x:6,y:2}}", "{enemy:[1],minMoves:43,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:5,y:4},enemyPosition:{x:6,y:6},exitPosition:{x:5,y:6}}", "{enemy:[2],minMoves:20,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:3,y:5},enemyPosition:{x:1,y:6},exitPosition:{x:1,y:6}}", "{enemy:[0],minMoves:22,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:4,y:5},enemyPosition:{x:4,y:6},exitPosition:{x:3,y:4}}", "{enemy:[2],minMoves:20,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:3,y:4},enemyPosition:{x:3,y:6},exitPosition:{x:3,y:6}}", "{enemy:[1],minMoves:20,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:5,y:5},enemyPosition:{x:6,y:5},exitPosition:{x:4,y:2}}", "{enemy:[2],minMoves:21,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:0,y:5},enemyPosition:{x:6,y:6},exitPosition:{x:6,y:7}}", "{enemy:[2],minMoves:21,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:6,y:6},enemyPosition:{x:4,y:2},exitPosition:{x:6,y:3}}", "{enemy:[0,1],minMoves:20,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:5,y:6},enemyPosition:{x:3,y:1},exitPosition:{x:4,y:2},enemyPosition2:{x:2,y:2}}", "{enemy:[2],minMoves:20,squares:[[{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:5,y:7},enemyPosition:{x:2,y:3},exitPosition:{x:4,y:8}}", "{enemy:[2],minMoves:21,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:5,y:5},enemyPosition:{x:5,y:6},exitPosition:{x:6,y:5}}", "{enemy:[2],minMoves:20,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:6,y:4},enemyPosition:{x:4,y:6},exitPosition:{x:4,y:6}}", "{enemy:[0],minMoves:26,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:6,y:7},enemyPosition:{x:4,y:2},exitPosition:{x:5,y:2}}", "{enemy:[1],minMoves:21,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:6,y:6},enemyPosition:{x:4,y:3},exitPosition:{x:5,y:2}}", "{enemy:[2],minMoves:20,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:6,y:5},enemyPosition:{x:2,y:4},exitPosition:{x:2,y:3}}", "{enemy:[0,1],minMoves:22,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:1,y:1},enemyPosition:{x:2,y:6},exitPosition:{x:1,y:4},enemyPosition2:{x:2,y:4}}", "{enemy:[1],minMoves:24,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:2,y:1},enemyPosition:{x:7,y:1},exitPosition:{x:3,y:2}}", "{enemy:[0],minMoves:20,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:7,y:4},enemyPosition:{x:1,y:4},exitPosition:{x:1,y:6}}", "{enemy:[1],minMoves:30,squares:[[{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:2,y:6},enemyPosition:{x:6,y:2},exitPosition:{x:6,y:1}}", "{enemy:[2],minMoves:21,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:7,y:6},enemyPosition:{x:3,y:3},exitPosition:{x:1,y:5}}", "{enemy:[1],minMoves:43,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:2,y:7},enemyPosition:{x:4,y:6},exitPosition:{x:7,y:7}}", "{enemy:[2],minMoves:20,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:4,y:3},enemyPosition:{x:5,y:2},exitPosition:{x:6,y:4}}", "{enemy:[1],minMoves:22,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:7,y:5},enemyPosition:{x:6,y:7},exitPosition:{x:5,y:6}}", "{enemy:[2],minMoves:23,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:5,y:2},enemyPosition:{x:3,y:6},exitPosition:{x:5,y:4}}", "{enemy:[0],minMoves:21,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:4,y:2},enemyPosition:{x:6,y:5},exitPosition:{x:5,y:4}}", "{enemy:[1],minMoves:34,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:4,y:7},enemyPosition:{x:1,y:7},exitPosition:{x:2,y:5}}", "{enemy:[2],minMoves:24,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:3,y:5},enemyPosition:{x:7,y:7},exitPosition:{x:6,y:4}}", "{enemy:[1],minMoves:22,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:4,y:4},enemyPosition:{x:2,y:3},exitPosition:{x:3,y:1}}", "{enemy:[0],minMoves:23,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:1,y:1},enemyPosition:{x:3,y:2},exitPosition:{x:3,y:3}}", "{enemy:[1],minMoves:21,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:4,y:3},enemyPosition:{x:2,y:5},exitPosition:{x:3,y:5}}", "{enemy:[2],minMoves:33,squares:[[{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:4,y:1},enemyPosition:{x:0,y:5},exitPosition:{x:0,y:0}}", "{enemy:[1],minMoves:24,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:5,y:4},enemyPosition:{x:6,y:4},exitPosition:{x:6,y:5}}", "{enemy:[2],minMoves:34,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:2,y:7},enemyPosition:{x:6,y:3},exitPosition:{x:6,y:5}}", "{enemy:[1],minMoves:22,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:1,y:4},enemyPosition:{x:2,y:3},exitPosition:{x:2,y:3}}", "{enemy:[1],minMoves:21,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:5,y:5},enemyPosition:{x:6,y:7},exitPosition:{x:7,y:4}}", "{enemy:[1,2],minMoves:20,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:1,y:3},enemyPosition:{x:6,y:1},exitPosition:{x:5,y:1},enemyPosition2:{x:3,y:2}}", "{enemy:[1],minMoves:22,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:7,y:2},enemyPosition:{x:5,y:5},exitPosition:{x:0,y:5}}", "{enemy:[2],minMoves:24,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:6,y:1},enemyPosition:{x:0,y:1},exitPosition:{x:3,y:2}}", "{enemy:[0],minMoves:26,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:4,y:2},enemyPosition:{x:8,y:3},exitPosition:{x:6,y:8}}", "{enemy:[2],minMoves:32,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:3,y:2},enemyPosition:{x:7,y:6},exitPosition:{x:6,y:2}}", "{enemy:[1],minMoves:20,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:6,y:2},enemyPosition:{x:7,y:3},exitPosition:{x:6,y:4}}", "{enemy:[1],minMoves:25,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:5,y:2},enemyPosition:{x:1,y:7},exitPosition:{x:2,y:7}}", "{enemy:[2],minMoves:24,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:5,y:1},enemyPosition:{x:6,y:1},exitPosition:{x:7,y:5}}", "{enemy:[2],minMoves:22,squares:[[{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true}]],width:9,height:9,playerPosition:{x:6,y:6},enemyPosition:{x:0,y:0},exitPosition:{x:0,y:3}}", "{enemy:[1],minMoves:24,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:4,y:4},enemyPosition:{x:7,y:3},exitPosition:{x:6,y:0}}", "{enemy:[2],minMoves:20,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:3,y:2},enemyPosition:{x:5,y:2},exitPosition:{x:5,y:2}}", "{enemy:[2],minMoves:35,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:true}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:3,y:2},enemyPosition:{x:2,y:0},exitPosition:{x:0,y:0}}", "{enemy:[1],minMoves:32,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:1,y:6},enemyPosition:{x:6,y:3},exitPosition:{x:2,y:4}}", "{enemy:[2],minMoves:21,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:4,y:2},enemyPosition:{x:7,y:7},exitPosition:{x:7,y:6}}", "{enemy:[1,2],minMoves:20,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:5,y:2},enemyPosition:{x:1,y:4},exitPosition:{x:2,y:5},enemyPosition2:{x:2,y:4}}", "{enemy:[1],minMoves:20,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:4,y:4},enemyPosition:{x:2,y:6},exitPosition:{x:2,y:6}}", "{enemy:[2],minMoves:21,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:3,y:6},enemyPosition:{x:5,y:5},exitPosition:{x:4,y:6}}", "{enemy:[1],minMoves:20,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:3,y:1},enemyPosition:{x:7,y:4},exitPosition:{x:7,y:3}}", "{enemy:[2],minMoves:24,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:5,y:5},enemyPosition:{x:2,y:6},exitPosition:{x:2,y:5}}", "{enemy:[1],minMoves:23,squares:[[{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:true}]],width:9,height:9,playerPosition:{x:6,y:3},enemyPosition:{x:4,y:8},exitPosition:{x:1,y:8}}", "{enemy:[2],minMoves:20,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:1,y:4},enemyPosition:{x:5,y:7},exitPosition:{x:7,y:2}}", "{enemy:[0,1],minMoves:24,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:4,y:6},enemyPosition:{x:6,y:1},exitPosition:{x:3,y:1},enemyPosition2:{x:5,y:2}}", "{enemy:[1],minMoves:21,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:5,y:4},enemyPosition:{x:4,y:2},exitPosition:{x:5,y:2}}", "{enemy:[0],minMoves:33,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:6,y:7},enemyPosition:{x:8,y:4},exitPosition:{x:8,y:2}}", "{enemy:[1],minMoves:24,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:7,y:5},enemyPosition:{x:2,y:1},exitPosition:{x:2,y:1}}", "{enemy:[2],minMoves:22,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:2,y:1},enemyPosition:{x:3,y:7},exitPosition:{x:4,y:7}}", "{enemy:[1],minMoves:25,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:6,y:3},enemyPosition:{x:2,y:6},exitPosition:{x:5,y:6}}", "{enemy:[1],minMoves:27,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:7,y:1},enemyPosition:{x:7,y:4},exitPosition:{x:7,y:7}}", "{enemy:[2],minMoves:33,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:0,y:8},enemyPosition:{x:0,y:2},exitPosition:{x:2,y:4}}", "{enemy:[1],minMoves:23,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:2,y:4},enemyPosition:{x:7,y:5},exitPosition:{x:6,y:6}}", "{enemy:[0],minMoves:23,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:2,y:1},enemyPosition:{x:3,y:7},exitPosition:{x:0,y:4}}", "{enemy:[0,1],minMoves:20,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:2,y:2},enemyPosition:{x:4,y:6},exitPosition:{x:2,y:3},enemyPosition2:{x:3,y:4}}", "{enemy:[2],minMoves:26,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:6,y:4},enemyPosition:{x:7,y:7},exitPosition:{x:7,y:3}}", "{enemy:[1],minMoves:20,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:3,y:5},enemyPosition:{x:2,y:5},exitPosition:{x:2,y:6}}", "{enemy:[2],minMoves:30,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:6,y:1},enemyPosition:{x:2,y:2},exitPosition:{x:2,y:1}}", "{enemy:[0,1],minMoves:24,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:2,y:5},enemyPosition:{x:5,y:3},exitPosition:{x:6,y:6},enemyPosition2:{x:4,y:4}}", "{enemy:[1],minMoves:20,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:6,y:0},enemyPosition:{x:0,y:5},exitPosition:{x:0,y:6}}", "{enemy:[1],minMoves:20,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:1,y:4},enemyPosition:{x:1,y:6},exitPosition:{x:2,y:6}}", "{enemy:[0],minMoves:20,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:6,y:5},enemyPosition:{x:2,y:2},exitPosition:{x:3,y:2}}", "{enemy:[1],minMoves:24,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:6,y:4},enemyPosition:{x:3,y:5},exitPosition:{x:1,y:3}}", "{enemy:[0,1],minMoves:20,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:4,y:3},enemyPosition:{x:5,y:7},exitPosition:{x:6,y:7},enemyPosition2:{x:6,y:5}}", "{enemy:[0],minMoves:30,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:5,y:6},enemyPosition:{x:2,y:7},exitPosition:{x:5,y:8}}", "{enemy:[2],minMoves:27,squares:[[{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:true},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:true,limitLeft:true,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:true,limitLeft:false,limitRight:false},{limitUp:true,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:true,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true},{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:true,limitRight:false},{limitUp:false,limitDown:false,limitLeft:false,limitRight:false},{limitUp:false,limitDown:true,limitLeft:false,limitRight:false}],[{limitUp:true,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:false,limitLeft:false,limitRight:true},{limitUp:false,limitDown:true,limitLeft:false,limitRight:true}]],width:9,height:9,playerPosition:{x:2,y:1},enemyPosition:{x:6,y:2},exitPosition:{x:6,y:3}}" } }; }
Change fox levels
core/src/es/seastorm/merlin/Constants.java
Change fox levels
Java
apache-2.0
752d23f719ae73266fe504558934efee5833314c
0
tateshitah/jspwiki,tateshitah/jspwiki,tateshitah/jspwiki,tateshitah/jspwiki
/* JSPWiki - a JSP-based WikiWiki clone. Copyright (C) 2001-2002 Janne Jalkanen ([email protected]) 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. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package com.ecyrd.jspwiki; import java.io.*; import java.util.*; import org.apache.log4j.*; import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.Cookie; import javax.servlet.http.HttpSession; import com.ecyrd.jspwiki.plugin.PluginManager; import com.ecyrd.jspwiki.rss.RSSGenerator; import com.ecyrd.jspwiki.providers.WikiPageProvider; import com.ecyrd.jspwiki.providers.ProviderException; import com.ecyrd.jspwiki.attachment.AttachmentManager; import com.ecyrd.jspwiki.attachment.Attachment; import com.ecyrd.jspwiki.auth.AuthorizationManager; import com.ecyrd.jspwiki.auth.UserManager; import com.ecyrd.jspwiki.auth.UserProfile; import com.ecyrd.jspwiki.filters.PageFilter; import com.ecyrd.jspwiki.util.PriorityList; import com.ecyrd.jspwiki.util.ClassUtil; /** * Provides Wiki services to the JSP page. * * <P> * This is the main interface through which everything should go. * * <P> * Using this class: Always get yourself an instance from JSP page * by using the WikiEngine.getInstance() method. Never create a new * WikiEngine() from scratch, unless you're writing tests. * * @author Janne Jalkanen */ public class WikiEngine { private static final Category log = Category.getInstance(WikiEngine.class); /** True, if log4j has been configured. */ // FIXME: If you run multiple applications, the first application // to run defines where the log goes. Not what we want. private static boolean c_configured = false; /** Stores properties. */ private Properties m_properties; public static final String PROP_INTERWIKIREF = "jspwiki.interWikiRef."; /** If true, then the user name will be stored with the page data.*/ public static final String PROP_STOREUSERNAME= "jspwiki.storeUserName"; /** Define the used encoding. Currently supported are ISO-8859-1 and UTF-8 */ public static final String PROP_ENCODING = "jspwiki.encoding"; /** The name for the base URL to use in all references. */ public static final String PROP_BASEURL = "jspwiki.baseURL"; /** Property name for the "spaces in titles" -hack. */ public static final String PROP_BEAUTIFYTITLE = "jspwiki.breakTitleWithSpaces"; /** The name of the cookie that gets stored to the user browser. */ public static final String PREFS_COOKIE_NAME = "JSPWikiUserProfile"; /** Property name for the "match english plurals" -hack. */ public static final String PROP_MATCHPLURALS = "jspwiki.translatorReader.matchEnglishPlurals"; /** Property name for the template that is used. */ public static final String PROP_TEMPLATEDIR = "jspwiki.templateDir"; /** Property name for the default front page. */ public static final String PROP_FRONTPAGE = "jspwiki.frontPage"; /** Stores an internal list of engines per each ServletContext */ private static Hashtable c_engines = new Hashtable(); /** Should the user info be saved with the page data as well? */ private boolean m_saveUserInfo = true; /** If true, uses UTF8 encoding for all data */ private boolean m_useUTF8 = true; /** If true, we'll also consider english plurals (+s) a match. */ private boolean m_matchEnglishPlurals = true; /** Stores the base URL. */ private String m_baseURL; /** Store the file path to the basic URL. When we're not running as a servlet, it defaults to the user's current directory. */ private String m_rootPath = System.getProperty("user.dir"); /** Stores references between wikipages. */ private ReferenceManager m_referenceManager = null; /** Stores the Plugin manager */ private PluginManager m_pluginManager; /** Stores the Variable manager */ private VariableManager m_variableManager; /** Stores the Attachment manager */ private AttachmentManager m_attachmentManager = null; /** Stores the Page manager */ private PageManager m_pageManager = null; /** Stores the authorization manager */ private AuthorizationManager m_authorizationManager = null; /** Stores the user manager.*/ private UserManager m_userManager = null; /** Does all our diffs for us. */ private DifferenceEngine m_differenceEngine; /** Generates RSS feed when requested. */ private RSSGenerator m_rssGenerator; /** Stores the relative URL to the global RSS feed. */ private String m_rssURL; /** Store the ServletContext that we're in. This may be null if WikiEngine is not running inside a servlet container (i.e. when testing). */ private ServletContext m_servletContext = null; /** If true, all titles will be cleaned. */ private boolean m_beautifyTitle = false; /** Stores the template path. This is relative to "templates". */ private String m_templateDir; /** The default front page name. Defaults to "Main". */ private String m_frontPage; /** The time when this engine was started. */ private Date m_startTime; private PriorityList m_pageFilters = new PriorityList(); private boolean m_isConfigured = false; // Flag. /** * Gets a WikiEngine related to this servlet. Since this method * is only called from JSP pages (and JspInit()) to be specific, * we throw a RuntimeException if things don't work. * * @throws InternalWikiException in case something fails. This * is a RuntimeException, so be prepared for it. */ // FIXME: It seems that this does not work too well, jspInit() // does not react to RuntimeExceptions, or something... public static synchronized WikiEngine getInstance( ServletConfig config ) throws InternalWikiException { ServletContext context = config.getServletContext(); String appid = Integer.toString(context.hashCode()); //FIXME: Kludge, use real type. config.getServletContext().log( "Application "+appid+" requests WikiEngine."); WikiEngine engine = (WikiEngine) c_engines.get( appid ); if( engine == null ) { context.log(" Assigning new log to "+appid); try { engine = new WikiEngine( config.getServletContext() ); } catch( Exception e ) { context.log( "ERROR: Failed to create a Wiki engine" ); throw new InternalWikiException( "No wiki engine, check logs." ); } c_engines.put( appid, engine ); } return engine; } /** * Instantiate the WikiEngine using a given set of properties. * Use this constructor for testing purposes only. */ public WikiEngine( Properties properties ) throws WikiException { initialize( properties ); } /** * Instantiate using this method when you're running as a servlet and * WikiEngine will figure out where to look for the property * file. * Do not use this method - use WikiEngine.getInstance() instead. */ protected WikiEngine( ServletContext context ) throws WikiException { m_servletContext = context; InputStream propertyStream = context.getResourceAsStream("/WEB-INF/jspwiki.properties"); Properties props = new Properties(); try { // // Note: May be null, if JSPWiki has been deployed in a WAR file. // m_rootPath = context.getRealPath("/"); props.load( propertyStream ); initialize( props ); log.debug("Root path for this Wiki is: '"+m_rootPath+"'"); } catch( Exception e ) { context.log( Release.APPNAME+": Unable to load and setup properties from jspwiki.properties. "+e.getMessage() ); } finally { try { propertyStream.close(); } catch( IOException e ) { context.log("Unable to close property stream - something must be seriously wrong."); } } } /** * Does all the real initialization. */ private void initialize( Properties props ) throws WikiException { m_startTime = new Date(); m_properties = props; // // Initialized log4j. However, make sure that // we don't initialize it multiple times. Also, if // all of the log4j statements have been removed from // the property file, we do not do any property setting // either.q // if( !c_configured ) { if( props.getProperty("log4j.rootCategory") != null ) { PropertyConfigurator.configure( props ); } c_configured = true; } log.info("*******************************************"); log.info("JSPWiki "+Release.VERSTR+" starting. Whee!"); log.debug("Configuring WikiEngine..."); m_saveUserInfo = TextUtil.getBooleanProperty( props, PROP_STOREUSERNAME, m_saveUserInfo ); m_useUTF8 = "UTF-8".equals( props.getProperty( PROP_ENCODING, "ISO-8859-1" ) ); m_baseURL = props.getProperty( PROP_BASEURL, "" ); m_beautifyTitle = TextUtil.getBooleanProperty( props, PROP_BEAUTIFYTITLE, m_beautifyTitle ); m_matchEnglishPlurals = TextUtil.getBooleanProperty( props, PROP_MATCHPLURALS, m_matchEnglishPlurals ); m_templateDir = props.getProperty( PROP_TEMPLATEDIR, "default" ); m_frontPage = props.getProperty( PROP_FRONTPAGE, "Main" ); // // Initialize the important modules. Any exception thrown by the // managers means that we will not start up. // try { m_pageManager = new PageManager( this, props ); m_pluginManager = new PluginManager( props ); m_differenceEngine = new DifferenceEngine( props, getContentEncoding() ); m_attachmentManager = new AttachmentManager( this, props ); m_variableManager = new VariableManager( props ); m_authorizationManager = new AuthorizationManager( this, props ); m_userManager = new UserManager( this, props ); initPageFilters( props ); initReferenceManager(); } catch( Exception e ) { // RuntimeExceptions may occur here, even if they shouldn't. log.error( "Failed to start managers.", e ); throw new WikiException( "Failed to start managers: "+e.getMessage() ); } // // Initialize the good-to-have-but-not-fatal modules. // try { if( TextUtil.getBooleanProperty( props, RSSGenerator.PROP_GENERATE_RSS, false ) ) { m_rssGenerator = new RSSGenerator( this, props ); } } catch( Exception e ) { log.error( "Unable to start RSS generator - JSPWiki will still work, "+ "but there will be no RSS feed.", e ); } // FIXME: I wonder if this should be somewhere else. if( m_rssGenerator != null ) { new RSSThread().start(); } log.info("WikiEngine configured."); m_isConfigured = true; } /** * Initializes the reference manager. Scans all existing WikiPages for * internal links and adds them to the ReferenceManager object. */ private void initReferenceManager() { m_pluginManager.enablePlugins( false ); long start = System.currentTimeMillis(); log.info( "Starting cross reference scan of WikiPages" ); try { Collection pages = m_pageManager.getAllPages(); pages.addAll( m_attachmentManager.getAllAttachments() ); // Build a new manager with default key lists. if( m_referenceManager == null ) { m_referenceManager = new ReferenceManager( this, pages ); } // Scan the existing pages from disk and update references in the manager. Iterator it = pages.iterator(); while( it.hasNext() ) { WikiPage page = (WikiPage)it.next(); if( page instanceof Attachment ) { // We cannot build a reference list from the contents // of attachments, so we skip them. } else { String content = m_pageManager.getPageText( page.getName(), WikiPageProvider.LATEST_VERSION ); Collection links = scanWikiLinks( page, content ); Collection attachments = m_attachmentManager.listAttachments( page ); for( Iterator atti = attachments.iterator(); atti.hasNext(); ) { links.add( ((Attachment)(atti.next())).getName() ); } m_referenceManager.updateReferences( page.getName(), links ); } } } catch( ProviderException e ) { log.fatal("PageProvider is unable to list pages: ", e); } log.info( "Cross reference scan done (" + (System.currentTimeMillis()-start) + " ms)" ); m_pluginManager.enablePlugins( true ); } public static final String PROP_PAGEFILTER = "jspwiki.pageFilter."; private void initPageFilters( Properties props ) { for( Enumeration enum = props.propertyNames(); enum.hasMoreElements(); ) { String name = (String) enum.nextElement(); if( name.startsWith( PROP_PAGEFILTER ) ) { String className = props.getProperty( name ); try { String pr = name.substring( PROP_PAGEFILTER.length() ); int priority = Integer.parseInt( pr ); Class cl = ClassUtil.findClass( "com.ecyrd.jspwiki.filters", className ); PageFilter filter = (PageFilter)cl.newInstance(); filter.initialize( props ); m_pageFilters.add( filter, priority ); log.info("Added page filter "+cl.getName()+" with priority "+priority); } catch( NumberFormatException e ) { log.error("Priority must be an integer: "+name); } catch( ClassNotFoundException e ) { log.error("Unable to find the filter class: "+className); } catch( InstantiationException e ) { log.error("Cannot create filter class: "+className); } catch( IllegalAccessException e ) { log.error("You are not allowed to access class: "+className); } catch( ClassCastException e ) { log.error("Suggested class is not a PageFilter: "+className); } } } } /** * Throws an exception if a property is not found. */ public static String getRequiredProperty( Properties props, String key ) throws NoRequiredPropertyException { String value = props.getProperty(key); if( value == null ) { throw new NoRequiredPropertyException( "Required property not found", key ); } return value; } /** * Internal method for getting a property. This is used by the * TranslatorReader for example. */ public Properties getWikiProperties() { return m_properties; } /** * @since 1.8.0 */ public String getPluginSearchPath() { // FIXME: This method should not be here, probably. return m_properties.getProperty( PluginManager.PROP_SEARCHPATH ); } /** * Returns the current template directory. * * @since 1.9.20 */ public String getTemplateDir() { return m_templateDir; } /** * Returns the base URL. Always prepend this to any reference * you make. * * @since 1.6.1 */ public String getBaseURL() { return m_baseURL; } /** * Returns the moment when this engine was started. * * @since 2.0.15. */ public Date getStartTime() { return m_startTime; } /** * Returns the basic URL to a page, without any modifications. * You may add any parameters to this. * * @since 2.0.3 */ public String getViewURL( String pageName ) {/* pageName = encodeName( pageName ); String srcString = "%uWiki.jsp?page=%p"; srcString = TextUtil.replaceString( srcString, "%u", m_baseURL ); srcString = TextUtil.replaceString( srcString, "%p", pageName ); return srcString; */ if( pageName == null ) return m_baseURL+"Wiki.jsp"; return m_baseURL+"Wiki.jsp?page="+encodeName(pageName); } /** * Returns the basic URL to an editor. * * @since 2.0.3 */ public String getEditURL( String pageName ) { return m_baseURL+"Edit.jsp?page="+encodeName(pageName); } /** * Returns the basic attachment URL. * @since 2.0.42. */ public String getAttachmentURL( String attName ) { return m_baseURL+"attach?page="+encodeName(attName); } /** * Returns the default front page, if no page is used. */ public String getFrontPage() { return m_frontPage; } /** * Returns the ServletContext that this particular WikiEngine was * initialized with. <B>It may return null</B>, if the WikiEngine is not * running inside a servlet container! * * @since 1.7.10 * @return ServletContext of the WikiEngine, or null. */ public ServletContext getServletContext() { return m_servletContext; } /** * This is a safe version of the Servlet.Request.getParameter() routine. * Unfortunately, the default version always assumes that the incoming * character set is ISO-8859-1, even though it was something else. * This means that we need to make a new string using the correct * encoding. * <P> * For more information, see: * <A HREF="http://www.jguru.com/faq/view.jsp?EID=137049">JGuru FAQ</A>. * <P> * Incidentally, this is almost the same as encodeName(), below. * I am not yet entirely sure if it's safe to merge the code. * * @since 1.5.3 */ public String safeGetParameter( ServletRequest request, String name ) { try { String res = request.getParameter( name ); if( res != null ) { res = new String(res.getBytes("ISO-8859-1"), getContentEncoding() ); } return res; } catch( UnsupportedEncodingException e ) { log.fatal( "Unsupported encoding", e ); return ""; } } /** * Returns the query string (the portion after the question mark). * * @return The query string. If the query string is null, * returns an empty string. * * @since 2.1.3 */ public String safeGetQueryString( HttpServletRequest request ) { if (request == null) { return ""; } try { String res = request.getQueryString(); if( res != null ) { res = new String(res.getBytes("ISO-8859-1"), getContentEncoding() ); // // Ensure that the 'page=xyz' attribute is removed // FIXME: Is it really the mandate of this routine to // do that? // int pos1 = res.indexOf("page="); if (pos1 >= 0) { String tmpRes = res.substring(0, pos1); int pos2 = res.indexOf("&",pos1) + 1; if ( (pos2 > 0) && (pos2 < res.length()) ) { tmpRes = tmpRes + res.substring(pos2); } res = tmpRes; } } return res; } catch( UnsupportedEncodingException e ) { log.fatal( "Unsupported encoding", e ); return ""; } } /** * Returns an URL to some other Wiki that we know. * * @return null, if no such reference was found. */ public String getInterWikiURL( String wikiName ) { return m_properties.getProperty(PROP_INTERWIKIREF+wikiName); } /** * Returns a collection of all supported InterWiki links. */ public Collection getAllInterWikiLinks() { Vector v = new Vector(); for( Enumeration i = m_properties.propertyNames(); i.hasMoreElements(); ) { String prop = (String) i.nextElement(); if( prop.startsWith( PROP_INTERWIKIREF ) ) { v.add( prop.substring( prop.lastIndexOf(".")+1 ) ); } } return v; } /** * Returns a collection of all image types that get inlined. */ public Collection getAllInlinedImagePatterns() { return TranslatorReader.getImagePatterns( this ); } /** * If the page is a special page, then returns a direct URL * to that page. Otherwise returns null. * <P> * Special pages are non-existant references to other pages. * For example, you could define a special page reference * "RecentChanges" which would always be redirected to "RecentChanges.jsp" * instead of trying to find a Wiki page called "RecentChanges". */ public String getSpecialPageReference( String original ) { String propname = "jspwiki.specialPage."+original; String specialpage = m_properties.getProperty( propname ); return specialpage; } /** * Returns the name of the application. */ // FIXME: Should use servlet context as a default instead of a constant. public String getApplicationName() { String appName = m_properties.getProperty("jspwiki.applicationName"); if( appName == null ) return Release.APPNAME; return appName; } /** * Beautifies the title of the page by appending spaces in suitable * places. * * @since 1.7.11 */ public String beautifyTitle( String title ) { if( m_beautifyTitle ) { return TextUtil.beautifyString( title ); } return title; } /** * Returns true, if the requested page (or an alias) exists. Will consider * any version as existing. Will also consider attachments. * * @param page WikiName of the page. */ public boolean pageExists( String page ) { Attachment att = null; try { if( getSpecialPageReference(page) != null ) return true; if( getFinalPageName( page ) != null ) { return true; } att = getAttachmentManager().getAttachmentInfo( (WikiContext)null, page ); } catch( ProviderException e ) { log.debug("pageExists() failed to find attachments",e); } return att != null; } /** * Returns true, if the requested page (or an alias) exists with the * requested version. * * @param page Page name */ public boolean pageExists( String page, int version ) throws ProviderException { if( getSpecialPageReference(page) != null ) return true; String finalName = getFinalPageName( page ); WikiPage p = null; if( finalName != null ) { // // Go and check if this particular version of this page // exists. // p = m_pageManager.getPageInfo( finalName, version ); } if( p == null ) { try { p = getAttachmentManager().getAttachmentInfo( (WikiContext)null, page, version ); } catch( ProviderException e ) { log.debug("pageExists() failed to find attachments",e); } } return (p != null); } /** * Returns true, if the requested page (or an alias) exists, with the * specified version in the WikiPage. * * @since 2.0 */ public boolean pageExists( WikiPage page ) throws ProviderException { if( page != null ) { return pageExists( page.getName(), page.getVersion() ); } return false; } /** * Returns the correct page name, or null, if no such * page can be found. Aliases are considered. * <P> * In some cases, page names can refer to other pages. For example, * when you have matchEnglishPlurals set, then a page name "Foobars" * will be transformed into "Foobar", should a page "Foobars" not exist, * but the page "Foobar" would. This method gives you the correct * page name to refer to. * <P> * This facility can also be used to rewrite any page name, for example, * by using aliases. It can also be used to check the existence of any * page. * * @since 2.0 * @param page Page name. * @return The rewritten page name, or null, if the page does not exist. */ public String getFinalPageName( String page ) throws ProviderException { boolean isThere = simplePageExists( page ); if( !isThere && m_matchEnglishPlurals ) { if( page.endsWith("s") ) { page = page.substring( 0, page.length()-1 ); } else { page += "s"; } isThere = simplePageExists( page ); } return isThere ? page : null ; } /** * Just queries the existing pages directly from the page manager. * We also check overridden pages from jspwiki.properties */ private boolean simplePageExists( String page ) throws ProviderException { if( getSpecialPageReference(page) != null ) return true; return m_pageManager.pageExists( page ); } /** * Turns a WikiName into something that can be * called through using an URL. * * @since 1.4.1 */ public String encodeName( String pagename ) { if( m_useUTF8 ) return TextUtil.urlEncodeUTF8( pagename ); else return java.net.URLEncoder.encode( pagename ); } public String decodeName( String pagerequest ) { if( m_useUTF8 ) return TextUtil.urlDecodeUTF8( pagerequest ); else return java.net.URLDecoder.decode( pagerequest ); } /** * Returns the IANA name of the character set encoding we're * supposed to be using right now. * * @since 1.5.3 */ public String getContentEncoding() { if( m_useUTF8 ) return "UTF-8"; return "ISO-8859-1"; } /** * Returns the unconverted text of a page. * * @param page WikiName of the page to fetch. */ public String getText( String page ) { return getText( page, WikiPageProvider.LATEST_VERSION ); } /** * Returns the unconverted text of the given version of a page, * if it exists. This method also replaces the HTML entities. * * @param page WikiName of the page to fetch * @param version Version of the page to fetch */ public String getText( String page, int version ) { String result = getPureText( page, version ); // // Replace ampersand first, or else all quotes and stuff // get replaced as well with &quot; etc. // result = TextUtil.replaceString( result, "&", "&amp;" ); result = TextUtil.replaceEntities( result ); return result; } /** * Returns the pure text of a page, no conversions. * * @param version If WikiPageProvider.LATEST_VERSION, then uses the * latest version. */ // FIXME: Should throw an exception on unknown page/version? public String getPureText( String page, int version ) { String result = null; try { result = m_pageManager.getPageText( page, version ); } catch( ProviderException e ) { // FIXME } finally { if( result == null ) result = ""; } return result; } /** * @since 2.1.13. */ public String getPureText( WikiPage page ) { return getPureText( page.getName(), page.getVersion() ); } /** * Returns plain text (with HTML entities replaced). This should * be the main entry point for getText(). * * @since 1.9.15. */ public String getText( WikiContext context, WikiPage page ) { return getText( page.getName(), page.getVersion() ); } /** * Returns the converted HTML of the page using a different * context than the default context. */ public String getHTML( WikiContext context, WikiPage page ) { String pagedata = null; pagedata = getPureText( page.getName(), page.getVersion() ); String res = textToHTML( context, pagedata ); return res; } /** * Returns the converted HTML of the page. * * @param page WikiName of the page to convert. */ public String getHTML( String page ) { return getHTML( page, WikiPageProvider.LATEST_VERSION ); } /** * Returns the converted HTML of the page's specific version. * The version must be a positive integer, otherwise the current * version is returned. * * @param pagename WikiName of the page to convert. * @param version Version number to fetch * @deprecated */ public String getHTML( String pagename, int version ) { WikiPage page = new WikiPage( pagename ); page.setVersion( version ); WikiContext context = new WikiContext( this, page ); String res = getHTML( context, page ); return res; } /** * Converts raw page data to HTML. * * @param pagedata Raw page data to convert to HTML */ public String textToHTML( WikiContext context, String pagedata ) { return textToHTML( context, pagedata, null, null ); } /** * Reads a WikiPageful of data from a String and returns all links * internal to this Wiki in a Collection. */ protected Collection scanWikiLinks( WikiPage page, String pagedata ) { LinkCollector localCollector = new LinkCollector(); textToHTML( new WikiContext(this,page), pagedata, localCollector, null, localCollector, false ); return localCollector.getLinks(); } /** * Just convert WikiText to HTML. */ public String textToHTML( WikiContext context, String pagedata, StringTransmutator localLinkHook, StringTransmutator extLinkHook ) { return textToHTML( context, pagedata, localLinkHook, extLinkHook, null, true ); } /** * Helper method for doing the HTML translation. */ private String textToHTML( WikiContext context, String pagedata, StringTransmutator localLinkHook, StringTransmutator extLinkHook, StringTransmutator attLinkHook, boolean parseAccessRules ) { String result = ""; if( pagedata == null ) { log.error("NULL pagedata to textToHTML()"); return null; } TranslatorReader in = null; Collection links = null; try { pagedata = doPreTranslateFiltering( context, pagedata ); in = new TranslatorReader( context, new StringReader( pagedata ) ); in.addLocalLinkHook( localLinkHook ); in.addExternalLinkHook( extLinkHook ); in.addAttachmentLinkHook( attLinkHook ); if( !parseAccessRules ) in.disableAccessRules(); result = FileUtil.readContents( in ); result = doPostTranslateFiltering( context, result ); } catch( IOException e ) { log.error("Failed to scan page data: ", e); } finally { try { if( in != null ) in.close(); } catch( Exception e ) { log.fatal("Closing failed",e); } } return( result ); } /** * Updates all references for the given page. */ public void updateReferences( WikiPage page ) { String pageData = getPureText( page.getName(), WikiProvider.LATEST_VERSION ); m_referenceManager.updateReferences( page.getName(), scanWikiLinks( page, pageData ) ); } private String doPreTranslateFiltering( WikiContext context, String pageData ) { for( Iterator i = m_pageFilters.iterator(); i.hasNext(); ) { PageFilter f = (PageFilter) i.next(); pageData = f.preTranslate( context, pageData ); } return pageData; } private String doPostTranslateFiltering( WikiContext context, String pageData ) { for( Iterator i = m_pageFilters.iterator(); i.hasNext(); ) { PageFilter f = (PageFilter) i.next(); pageData = f.postTranslate( context, pageData ); } return pageData; } private String doPreSaveFiltering( WikiContext context, String pageData ) { for( Iterator i = m_pageFilters.iterator(); i.hasNext(); ) { PageFilter f = (PageFilter) i.next(); pageData = f.preSave( context, pageData ); } return pageData; } private void doPostSaveFiltering( WikiContext context, String pageData ) { for( Iterator i = m_pageFilters.iterator(); i.hasNext(); ) { PageFilter f = (PageFilter) i.next(); f.postSave( context, pageData ); } } /** * Writes the WikiText of a page into the * page repository. * * @since 2.1.28 * @param context The current WikiContext * @param text The Wiki markup for the page. */ public void saveText( WikiContext context, String text ) { WikiPage page = context.getPage(); if( page.getAuthor() == null ) { UserProfile wup = context.getCurrentUser(); if( wup != null ) page.setAuthor( wup.getName() ); } text = TextUtil.normalizePostData(text); text = doPreSaveFiltering( context, text ); // Hook into cross reference collection. m_referenceManager.updateReferences( page.getName(), scanWikiLinks( page, text ) ); try { m_pageManager.putPageText( page, text ); doPostSaveFiltering( context, text ); } catch( ProviderException e ) { log.error( "Unable to put page", e ); } } /** * Retrieves the user name. It will check if user has been authenticated, * or he has a cookie with his username set. The cookie takes precedence, * which allows the wiki master to set up a site with a single master * password. Note that this behaviour will be changed in 2.1 or thereabouts. * Earlier versions than 1.9.42 preferred the authenticated name over * the cookie name. * * @param request HttpServletRequest that was called. * @return The WikiName of the user, or null, if no username was set. */ // FIXME: This is a terrible time waster, parsing the // textual data every time it is used. /* // FIXME: Not used public String getUserName( HttpServletRequest request ) { if( request == null ) { return null; } // Get the user authentication - if he's not been authenticated // we then check from cookies. String author = request.getRemoteUser(); // // Try to fetch something from a cookie. // Cookie[] cookies = request.getCookies(); if( cookies != null ) { for( int i = 0; i < cookies.length; i++ ) { if( cookies[i].getName().equals( PREFS_COOKIE_NAME ) ) { UserProfile p = m_userManager.getUserProfile(cookies[i].getValue()); author = p.getName(); break; } } } // // Make sure that the author name is okay and a valid WikiName. // if( author != null ) { author = TranslatorReader.cleanLink( author ); } return author; } */ /** * If no author name has been set, then use the * IP address, if allowed. If no IP address is allowed, * then returns a default. * * @return Returns any sort of user name. Never returns null. */ // FIXME: Not used /* public String getValidUserName( HttpServletRequest request ) { return m_userManager.getUserProfile(request).getName(); } */ /** * @param request The HTTP Servlet request associated with this * transaction. * @since 1.5.1 * @deprecated */ /* public void saveText( WikiPage page, String text, HttpServletRequest request ) { text = TextUtil.normalizePostData(text); // Error protection or if the user info has been disabled. if( request == null || m_saveUserInfo == false ) { saveText( page, text ); } else { // Hook into cross reference collection. // Notice that this is definitely after the saveText() call above, // since it can be called externally and we only want this done once. m_referenceManager.updateReferences( page.getName(), scanWikiLinks( page, text ) ); String author = getValidUserName( request ); page.setAuthor( author ); try { m_pageManager.putPageText( page, text ); } catch( ProviderException e ) { log.error("Unable to put page: ", e); } } } */ /** * Returns the number of pages in this Wiki */ public int getPageCount() { return m_pageManager.getTotalPageCount(); } /** * Returns the provider name */ public String getCurrentProvider() { return m_pageManager.getProvider().getClass().getName(); } /** * return information about current provider. * @since 1.6.4 */ public String getCurrentProviderInfo() { return m_pageManager.getProviderDescription(); } /** * Returns a Collection of WikiPages, sorted in time * order of last change. */ // FIXME: Should really get a Date object and do proper comparisons. // This is terribly wasteful. public Collection getRecentChanges() { try { Collection pages = m_pageManager.getAllPages(); Collection atts = m_attachmentManager.getAllAttachments(); TreeSet sortedPages = new TreeSet( new PageTimeComparator() ); sortedPages.addAll( pages ); sortedPages.addAll( atts ); return sortedPages; } catch( ProviderException e ) { log.error( "Unable to fetch all pages: ",e); return null; } } /** * Parses an incoming search request, then * does a search. * <P> * Search language is simple: prepend a word * with a + to force a word to be included (all files * not containing that word are automatically rejected), * '-' to cause the rejection of all those files that contain * that word. */ // FIXME: does not support phrase searches yet, but for them // we need a version which reads the whole page into the memory // once. // // FIXME: Should also have attributes attached. // public Collection findPages( String query ) { StringTokenizer st = new StringTokenizer( query, " \t," ); QueryItem[] items = new QueryItem[st.countTokens()]; int word = 0; log.debug("Expecting "+items.length+" items"); // // Parse incoming search string // while( st.hasMoreTokens() ) { log.debug("Item "+word); String token = st.nextToken().toLowerCase(); items[word] = new QueryItem(); switch( token.charAt(0) ) { case '+': items[word].type = QueryItem.REQUIRED; token = token.substring(1); log.debug("Required word: "+token); break; case '-': items[word].type = QueryItem.FORBIDDEN; token = token.substring(1); log.debug("Forbidden word: "+token); break; default: items[word].type = QueryItem.REQUESTED; log.debug("Requested word: "+token); break; } items[word++].word = token; } Collection results = m_pageManager.findPages( items ); return results; } /** * Return a bunch of information from the web page. */ public WikiPage getPage( String pagereq ) { return getPage( pagereq, WikiProvider.LATEST_VERSION ); } /** * Returns specific information about a Wiki page. * @since 1.6.7. */ public WikiPage getPage( String pagereq, int version ) { try { WikiPage p = m_pageManager.getPageInfo( pagereq, version ); if( p == null ) { p = m_attachmentManager.getAttachmentInfo( (WikiContext)null, pagereq ); } return p; } catch( ProviderException e ) { log.error( "Unable to fetch page info",e); return null; } } /** * Returns a Collection of WikiPages containing the * version history of a page. */ public List getVersionHistory( String page ) { List c = null; try { c = m_pageManager.getVersionHistory( page ); if( c == null ) { c = m_attachmentManager.getVersionHistory( page ); } } catch( ProviderException e ) { log.error("FIXME"); } return c; } /** * Returns a diff of two versions of a page. * * @param page Page to return * @param version1 Version number of the old page. If * WikiPageProvider.LATEST_VERSION (-1), then uses current page. * @param version2 Version number of the new page. If * WikiPageProvider.LATEST_VERSION (-1), then uses current page. * * @return A HTML-ized difference between two pages. If there is no difference, * returns an empty string. */ public String getDiff( String page, int version1, int version2 ) { String page1 = getPureText( page, version1 ); String page2 = getPureText( page, version2 ); // Kludge to make diffs for new pages to work this way. if( version1 == WikiPageProvider.LATEST_VERSION ) { page1 = ""; } String diff = m_differenceEngine.makeDiff( page1, page2 ); diff = TextUtil.replaceEntities( diff ); try { if( diff.length() > 0 ) { diff = m_differenceEngine.colorizeDiff( diff ); } } catch( IOException e ) { log.error("Failed to colorize diff result.", e); } return diff; } /** * Attempts to locate a Wiki class, defaulting to the defaultPackage * in case the actual class could not be located. * * @param className Class to search for. * @param defaultPackage A default package to try if the class * cannot be directly located. May be null. * @throws ClassNotFoundException if the class could not be located. */ /* public static Class findWikiClass( String className, String defaultPackage ) throws ClassNotFoundException { Class tryClass; if( className == null ) { throw new ClassNotFoundException("Null className!"); } // // Attempt to use a shortcut, if possible. // try { tryClass = Class.forName( className ); } catch( ClassNotFoundException e ) { // FIXME: This causes "null" names to be searched for twice, which // is a performance penalty and not very nice. if( defaultPackage == null ) defaultPackage = ""; if( !defaultPackage.endsWith(".") ) defaultPackage += "."; tryClass = Class.forName( defaultPackage+className ); } return tryClass; } */ /** * Returns this object's ReferenceManager. * @since 1.6.1 */ // (FIXME: We may want to protect this, though...) public ReferenceManager getReferenceManager() { return m_referenceManager; } /** * Returns the current plugin manager. * @since 1.6.1 */ public PluginManager getPluginManager() { return m_pluginManager; } public VariableManager getVariableManager() { return m_variableManager; } /** * Returns the current PageManager. */ public PageManager getPageManager() { return m_pageManager; } /** * Returns the current AttachmentManager. * @since 1.9.31. */ public AttachmentManager getAttachmentManager() { return m_attachmentManager; } /** * Returns the currently used authorization manager. */ public AuthorizationManager getAuthorizationManager() { return m_authorizationManager; } /** * Returns the currently used user manager. */ public UserManager getUserManager() { return m_userManager; } /** * Shortcut to create a WikiContext from the Wiki page. * * @since 2.1.15. */ // FIXME: We need to have a version which takes a fixed page // name as well, or check it elsewhere. public WikiContext createContext( HttpServletRequest request, String requestContext ) { if( !m_isConfigured ) { throw new InternalWikiException("WikiEngine has not been properly started. It is likely that the configuration is faulty. Please check all logs for the possible reason."); } String pagereq = safeGetParameter( request, "page" ); String template = safeGetParameter( request, "skin" ); if( pagereq == null || pagereq.length() == 0 ) { pagereq = getFrontPage(); } int version = WikiProvider.LATEST_VERSION; String rev = request.getParameter("version"); if( rev != null ) { version = Integer.parseInt( rev ); } WikiPage wikipage = getPage( pagereq, version ); if( wikipage == null ) { wikipage = new WikiPage( pagereq ); } if( template == null ) { template = (String)wikipage.getAttribute( PROP_TEMPLATEDIR ); // FIXME: Most definitely this should be checked for // existence, or else it is possible to create pages that // cannot be shown. if( template == null || template.length() == 0 ) { template = getTemplateDir(); } } WikiContext context = new WikiContext( this, wikipage ); context.setRequestContext( requestContext ); context.setHttpRequest( request ); context.setTemplate( template ); UserProfile user = getUserManager().getUserProfile( request ); context.setCurrentUser( user ); return context; } /** * Returns the URL of the global RSS file. May be null, if the * RSS file generation is not operational. * @since 1.7.10 */ public String getGlobalRSSURL() { if( m_rssURL != null ) { return getBaseURL()+m_rssURL; } return null; } /** * Runs the RSS generation thread. * FIXME: MUST be somewhere else, this is not a good place. */ private class RSSThread extends Thread { public void run() { try { String fileName = m_properties.getProperty( RSSGenerator.PROP_RSSFILE, "rss.rdf" ); int rssInterval = TextUtil.parseIntParameter( m_properties.getProperty( RSSGenerator.PROP_INTERVAL ), 3600 ); log.debug("RSS file will be at "+fileName); log.debug("RSS refresh interval (seconds): "+rssInterval); while(true) { Writer out = null; Reader in = null; try { // // Generate RSS file, output it to // default "rss.rdf". // log.info("Regenerating RSS feed to "+fileName); String feed = m_rssGenerator.generate(); File file = new File( m_rootPath, fileName ); in = new StringReader(feed); out = new BufferedWriter( new OutputStreamWriter( new FileOutputStream(file), "UTF-8") ); FileUtil.copyContents( in, out ); m_rssURL = fileName; } catch( IOException e ) { log.error("Cannot generate RSS feed to "+fileName, e ); m_rssURL = null; } finally { try { if( in != null ) in.close(); if( out != null ) out.close(); } catch( IOException e ) { log.fatal("Could not close I/O for RSS", e ); break; } } Thread.sleep(rssInterval*1000L); } // while } catch(InterruptedException e) { log.error("RSS thread interrupted, no more RSS feeds", e); } // // Signal: no more RSS feeds. // m_rssURL = null; } } }
src/com/ecyrd/jspwiki/WikiEngine.java
/* JSPWiki - a JSP-based WikiWiki clone. Copyright (C) 2001-2002 Janne Jalkanen ([email protected]) 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. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package com.ecyrd.jspwiki; import java.io.*; import java.util.*; import org.apache.log4j.*; import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.Cookie; import javax.servlet.http.HttpSession; import com.ecyrd.jspwiki.plugin.PluginManager; import com.ecyrd.jspwiki.rss.RSSGenerator; import com.ecyrd.jspwiki.providers.WikiPageProvider; import com.ecyrd.jspwiki.providers.ProviderException; import com.ecyrd.jspwiki.attachment.AttachmentManager; import com.ecyrd.jspwiki.attachment.Attachment; import com.ecyrd.jspwiki.auth.AuthorizationManager; import com.ecyrd.jspwiki.auth.UserManager; import com.ecyrd.jspwiki.auth.UserProfile; import com.ecyrd.jspwiki.filters.PageFilter; import com.ecyrd.jspwiki.util.PriorityList; import com.ecyrd.jspwiki.util.ClassUtil; /** * Provides Wiki services to the JSP page. * * <P> * This is the main interface through which everything should go. * * <P> * Using this class: Always get yourself an instance from JSP page * by using the WikiEngine.getInstance() method. Never create a new * WikiEngine() from scratch, unless you're writing tests. * * @author Janne Jalkanen */ public class WikiEngine { private static final Category log = Category.getInstance(WikiEngine.class); /** True, if log4j has been configured. */ // FIXME: If you run multiple applications, the first application // to run defines where the log goes. Not what we want. private static boolean c_configured = false; /** Stores properties. */ private Properties m_properties; public static final String PROP_INTERWIKIREF = "jspwiki.interWikiRef."; /** If true, then the user name will be stored with the page data.*/ public static final String PROP_STOREUSERNAME= "jspwiki.storeUserName"; /** Define the used encoding. Currently supported are ISO-8859-1 and UTF-8 */ public static final String PROP_ENCODING = "jspwiki.encoding"; /** The name for the base URL to use in all references. */ public static final String PROP_BASEURL = "jspwiki.baseURL"; /** Property name for the "spaces in titles" -hack. */ public static final String PROP_BEAUTIFYTITLE = "jspwiki.breakTitleWithSpaces"; /** The name of the cookie that gets stored to the user browser. */ public static final String PREFS_COOKIE_NAME = "JSPWikiUserProfile"; /** Property name for the "match english plurals" -hack. */ public static final String PROP_MATCHPLURALS = "jspwiki.translatorReader.matchEnglishPlurals"; /** Property name for the template that is used. */ public static final String PROP_TEMPLATEDIR = "jspwiki.templateDir"; /** Property name for the default front page. */ public static final String PROP_FRONTPAGE = "jspwiki.frontPage"; /** Stores an internal list of engines per each ServletContext */ private static Hashtable c_engines = new Hashtable(); /** Should the user info be saved with the page data as well? */ private boolean m_saveUserInfo = true; /** If true, uses UTF8 encoding for all data */ private boolean m_useUTF8 = true; /** If true, we'll also consider english plurals (+s) a match. */ private boolean m_matchEnglishPlurals = true; /** Stores the base URL. */ private String m_baseURL; /** Store the file path to the basic URL. When we're not running as a servlet, it defaults to the user's current directory. */ private String m_rootPath = System.getProperty("user.dir"); /** Stores references between wikipages. */ private ReferenceManager m_referenceManager = null; /** Stores the Plugin manager */ private PluginManager m_pluginManager; /** Stores the Variable manager */ private VariableManager m_variableManager; /** Stores the Attachment manager */ private AttachmentManager m_attachmentManager = null; /** Stores the Page manager */ private PageManager m_pageManager = null; /** Stores the authorization manager */ private AuthorizationManager m_authorizationManager = null; /** Stores the user manager.*/ private UserManager m_userManager = null; /** Does all our diffs for us. */ private DifferenceEngine m_differenceEngine; /** Generates RSS feed when requested. */ private RSSGenerator m_rssGenerator; /** Stores the relative URL to the global RSS feed. */ private String m_rssURL; /** Store the ServletContext that we're in. This may be null if WikiEngine is not running inside a servlet container (i.e. when testing). */ private ServletContext m_servletContext = null; /** If true, all titles will be cleaned. */ private boolean m_beautifyTitle = false; /** Stores the template path. This is relative to "templates". */ private String m_templateDir; /** The default front page name. Defaults to "Main". */ private String m_frontPage; /** The time when this engine was started. */ private Date m_startTime; private PriorityList m_pageFilters = new PriorityList(); private boolean m_isConfigured = false; // Flag. /** * Gets a WikiEngine related to this servlet. Since this method * is only called from JSP pages (and JspInit()) to be specific, * we throw a RuntimeException if things don't work. * * @throws InternalWikiException in case something fails. This * is a RuntimeException, so be prepared for it. */ // FIXME: It seems that this does not work too well, jspInit() // does not react to RuntimeExceptions, or something... public static synchronized WikiEngine getInstance( ServletConfig config ) throws InternalWikiException { ServletContext context = config.getServletContext(); String appid = Integer.toString(context.hashCode()); //FIXME: Kludge, use real type. config.getServletContext().log( "Application "+appid+" requests WikiEngine."); WikiEngine engine = (WikiEngine) c_engines.get( appid ); if( engine == null ) { context.log(" Assigning new log to "+appid); try { engine = new WikiEngine( config.getServletContext() ); } catch( Exception e ) { context.log( "ERROR: Failed to create a Wiki engine" ); throw new InternalWikiException( "No wiki engine, check logs." ); } c_engines.put( appid, engine ); } return engine; } /** * Instantiate the WikiEngine using a given set of properties. * Use this constructor for testing purposes only. */ public WikiEngine( Properties properties ) throws WikiException { initialize( properties ); } /** * Instantiate using this method when you're running as a servlet and * WikiEngine will figure out where to look for the property * file. * Do not use this method - use WikiEngine.getInstance() instead. */ protected WikiEngine( ServletContext context ) throws WikiException { m_servletContext = context; InputStream propertyStream = context.getResourceAsStream("/WEB-INF/jspwiki.properties"); Properties props = new Properties(); try { // // Note: May be null, if JSPWiki has been deployed in a WAR file. // m_rootPath = context.getRealPath("/"); props.load( propertyStream ); initialize( props ); log.debug("Root path for this Wiki is: '"+m_rootPath+"'"); } catch( Exception e ) { context.log( Release.APPNAME+": Unable to load and setup properties from jspwiki.properties. "+e.getMessage() ); } } /** * Does all the real initialization. */ private void initialize( Properties props ) throws WikiException { m_startTime = new Date(); m_properties = props; // // Initialized log4j. However, make sure that // we don't initialize it multiple times. Also, if // all of the log4j statements have been removed from // the property file, we do not do any property setting // either.q // if( !c_configured ) { if( props.getProperty("log4j.rootCategory") != null ) { PropertyConfigurator.configure( props ); } c_configured = true; } log.info("*******************************************"); log.info("JSPWiki "+Release.VERSTR+" starting. Whee!"); log.debug("Configuring WikiEngine..."); m_saveUserInfo = TextUtil.getBooleanProperty( props, PROP_STOREUSERNAME, m_saveUserInfo ); m_useUTF8 = "UTF-8".equals( props.getProperty( PROP_ENCODING, "ISO-8859-1" ) ); m_baseURL = props.getProperty( PROP_BASEURL, "" ); m_beautifyTitle = TextUtil.getBooleanProperty( props, PROP_BEAUTIFYTITLE, m_beautifyTitle ); m_matchEnglishPlurals = TextUtil.getBooleanProperty( props, PROP_MATCHPLURALS, m_matchEnglishPlurals ); m_templateDir = props.getProperty( PROP_TEMPLATEDIR, "default" ); m_frontPage = props.getProperty( PROP_FRONTPAGE, "Main" ); // // Initialize the important modules. Any exception thrown by the // managers means that we will not start up. // try { m_pageManager = new PageManager( this, props ); m_pluginManager = new PluginManager( props ); m_differenceEngine = new DifferenceEngine( props, getContentEncoding() ); m_attachmentManager = new AttachmentManager( this, props ); m_variableManager = new VariableManager( props ); m_authorizationManager = new AuthorizationManager( this, props ); m_userManager = new UserManager( this, props ); initPageFilters( props ); initReferenceManager(); } catch( Exception e ) { // RuntimeExceptions may occur here, even if they shouldn't. log.error( "Failed to start managers.", e ); throw new WikiException( "Failed to start managers: "+e.getMessage() ); } // // Initialize the good-to-have-but-not-fatal modules. // try { if( TextUtil.getBooleanProperty( props, RSSGenerator.PROP_GENERATE_RSS, false ) ) { m_rssGenerator = new RSSGenerator( this, props ); } } catch( Exception e ) { log.error( "Unable to start RSS generator - JSPWiki will still work, "+ "but there will be no RSS feed.", e ); } // FIXME: I wonder if this should be somewhere else. if( m_rssGenerator != null ) { new RSSThread().start(); } log.info("WikiEngine configured."); m_isConfigured = true; } /** * Initializes the reference manager. Scans all existing WikiPages for * internal links and adds them to the ReferenceManager object. */ private void initReferenceManager() { m_pluginManager.enablePlugins( false ); long start = System.currentTimeMillis(); log.info( "Starting cross reference scan of WikiPages" ); try { Collection pages = m_pageManager.getAllPages(); pages.addAll( m_attachmentManager.getAllAttachments() ); // Build a new manager with default key lists. if( m_referenceManager == null ) { m_referenceManager = new ReferenceManager( this, pages ); } // Scan the existing pages from disk and update references in the manager. Iterator it = pages.iterator(); while( it.hasNext() ) { WikiPage page = (WikiPage)it.next(); if( page instanceof Attachment ) { // We cannot build a reference list from the contents // of attachments, so we skip them. } else { String content = m_pageManager.getPageText( page.getName(), WikiPageProvider.LATEST_VERSION ); Collection links = scanWikiLinks( page, content ); Collection attachments = m_attachmentManager.listAttachments( page ); for( Iterator atti = attachments.iterator(); atti.hasNext(); ) { links.add( ((Attachment)(atti.next())).getName() ); } m_referenceManager.updateReferences( page.getName(), links ); } } } catch( ProviderException e ) { log.fatal("PageProvider is unable to list pages: ", e); } log.info( "Cross reference scan done (" + (System.currentTimeMillis()-start) + " ms)" ); m_pluginManager.enablePlugins( true ); } public static final String PROP_PAGEFILTER = "jspwiki.pageFilter."; private void initPageFilters( Properties props ) { for( Enumeration enum = props.propertyNames(); enum.hasMoreElements(); ) { String name = (String) enum.nextElement(); if( name.startsWith( PROP_PAGEFILTER ) ) { String className = props.getProperty( name ); try { String pr = name.substring( PROP_PAGEFILTER.length() ); int priority = Integer.parseInt( pr ); Class cl = ClassUtil.findClass( "com.ecyrd.jspwiki.filters", className ); PageFilter filter = (PageFilter)cl.newInstance(); filter.initialize( props ); m_pageFilters.add( filter, priority ); log.info("Added page filter "+cl.getName()+" with priority "+priority); } catch( NumberFormatException e ) { log.error("Priority must be an integer: "+name); } catch( ClassNotFoundException e ) { log.error("Unable to find the filter class: "+className); } catch( InstantiationException e ) { log.error("Cannot create filter class: "+className); } catch( IllegalAccessException e ) { log.error("You are not allowed to access class: "+className); } catch( ClassCastException e ) { log.error("Suggested class is not a PageFilter: "+className); } } } } /** * Throws an exception if a property is not found. */ public static String getRequiredProperty( Properties props, String key ) throws NoRequiredPropertyException { String value = props.getProperty(key); if( value == null ) { throw new NoRequiredPropertyException( "Required property not found", key ); } return value; } /** * Internal method for getting a property. This is used by the * TranslatorReader for example. */ public Properties getWikiProperties() { return m_properties; } /** * @since 1.8.0 */ public String getPluginSearchPath() { // FIXME: This method should not be here, probably. return m_properties.getProperty( PluginManager.PROP_SEARCHPATH ); } /** * Returns the current template directory. * * @since 1.9.20 */ public String getTemplateDir() { return m_templateDir; } /** * Returns the base URL. Always prepend this to any reference * you make. * * @since 1.6.1 */ public String getBaseURL() { return m_baseURL; } /** * Returns the moment when this engine was started. * * @since 2.0.15. */ public Date getStartTime() { return m_startTime; } /** * Returns the basic URL to a page, without any modifications. * You may add any parameters to this. * * @since 2.0.3 */ public String getViewURL( String pageName ) {/* pageName = encodeName( pageName ); String srcString = "%uWiki.jsp?page=%p"; srcString = TextUtil.replaceString( srcString, "%u", m_baseURL ); srcString = TextUtil.replaceString( srcString, "%p", pageName ); return srcString; */ if( pageName == null ) return m_baseURL+"Wiki.jsp"; return m_baseURL+"Wiki.jsp?page="+encodeName(pageName); } /** * Returns the basic URL to an editor. * * @since 2.0.3 */ public String getEditURL( String pageName ) { return m_baseURL+"Edit.jsp?page="+encodeName(pageName); } /** * Returns the basic attachment URL. * @since 2.0.42. */ public String getAttachmentURL( String attName ) { return m_baseURL+"attach?page="+encodeName(attName); } /** * Returns the default front page, if no page is used. */ public String getFrontPage() { return m_frontPage; } /** * Returns the ServletContext that this particular WikiEngine was * initialized with. <B>It may return null</B>, if the WikiEngine is not * running inside a servlet container! * * @since 1.7.10 * @return ServletContext of the WikiEngine, or null. */ public ServletContext getServletContext() { return m_servletContext; } /** * This is a safe version of the Servlet.Request.getParameter() routine. * Unfortunately, the default version always assumes that the incoming * character set is ISO-8859-1, even though it was something else. * This means that we need to make a new string using the correct * encoding. * <P> * For more information, see: * <A HREF="http://www.jguru.com/faq/view.jsp?EID=137049">JGuru FAQ</A>. * <P> * Incidentally, this is almost the same as encodeName(), below. * I am not yet entirely sure if it's safe to merge the code. * * @since 1.5.3 */ public String safeGetParameter( ServletRequest request, String name ) { try { String res = request.getParameter( name ); if( res != null ) { res = new String(res.getBytes("ISO-8859-1"), getContentEncoding() ); } return res; } catch( UnsupportedEncodingException e ) { log.fatal( "Unsupported encoding", e ); return ""; } } /** * Returns the query string (the portion after the question mark). * * @return The query string. If the query string is null, * returns an empty string. * * @since 2.1.3 */ public String safeGetQueryString( HttpServletRequest request ) { if (request == null) { return ""; } try { String res = request.getQueryString(); if( res != null ) { res = new String(res.getBytes("ISO-8859-1"), getContentEncoding() ); // // Ensure that the 'page=xyz' attribute is removed // FIXME: Is it really the mandate of this routine to // do that? // int pos1 = res.indexOf("page="); if (pos1 >= 0) { String tmpRes = res.substring(0, pos1); int pos2 = res.indexOf("&",pos1) + 1; if ( (pos2 > 0) && (pos2 < res.length()) ) { tmpRes = tmpRes + res.substring(pos2); } res = tmpRes; } } return res; } catch( UnsupportedEncodingException e ) { log.fatal( "Unsupported encoding", e ); return ""; } } /** * Returns an URL to some other Wiki that we know. * * @return null, if no such reference was found. */ public String getInterWikiURL( String wikiName ) { return m_properties.getProperty(PROP_INTERWIKIREF+wikiName); } /** * Returns a collection of all supported InterWiki links. */ public Collection getAllInterWikiLinks() { Vector v = new Vector(); for( Enumeration i = m_properties.propertyNames(); i.hasMoreElements(); ) { String prop = (String) i.nextElement(); if( prop.startsWith( PROP_INTERWIKIREF ) ) { v.add( prop.substring( prop.lastIndexOf(".")+1 ) ); } } return v; } /** * Returns a collection of all image types that get inlined. */ public Collection getAllInlinedImagePatterns() { return TranslatorReader.getImagePatterns( this ); } /** * If the page is a special page, then returns a direct URL * to that page. Otherwise returns null. * <P> * Special pages are non-existant references to other pages. * For example, you could define a special page reference * "RecentChanges" which would always be redirected to "RecentChanges.jsp" * instead of trying to find a Wiki page called "RecentChanges". */ public String getSpecialPageReference( String original ) { String propname = "jspwiki.specialPage."+original; String specialpage = m_properties.getProperty( propname ); return specialpage; } /** * Returns the name of the application. */ // FIXME: Should use servlet context as a default instead of a constant. public String getApplicationName() { String appName = m_properties.getProperty("jspwiki.applicationName"); if( appName == null ) return Release.APPNAME; return appName; } /** * Beautifies the title of the page by appending spaces in suitable * places. * * @since 1.7.11 */ public String beautifyTitle( String title ) { if( m_beautifyTitle ) { return TextUtil.beautifyString( title ); } return title; } /** * Returns true, if the requested page (or an alias) exists. Will consider * any version as existing. Will also consider attachments. * * @param page WikiName of the page. */ public boolean pageExists( String page ) { Attachment att = null; try { if( getSpecialPageReference(page) != null ) return true; if( getFinalPageName( page ) != null ) { return true; } att = getAttachmentManager().getAttachmentInfo( (WikiContext)null, page ); } catch( ProviderException e ) { log.debug("pageExists() failed to find attachments",e); } return att != null; } /** * Returns true, if the requested page (or an alias) exists with the * requested version. * * @param page Page name */ public boolean pageExists( String page, int version ) throws ProviderException { if( getSpecialPageReference(page) != null ) return true; String finalName = getFinalPageName( page ); WikiPage p = null; if( finalName != null ) { // // Go and check if this particular version of this page // exists. // p = m_pageManager.getPageInfo( finalName, version ); } if( p == null ) { try { p = getAttachmentManager().getAttachmentInfo( (WikiContext)null, page, version ); } catch( ProviderException e ) { log.debug("pageExists() failed to find attachments",e); } } return (p != null); } /** * Returns true, if the requested page (or an alias) exists, with the * specified version in the WikiPage. * * @since 2.0 */ public boolean pageExists( WikiPage page ) throws ProviderException { if( page != null ) { return pageExists( page.getName(), page.getVersion() ); } return false; } /** * Returns the correct page name, or null, if no such * page can be found. Aliases are considered. * <P> * In some cases, page names can refer to other pages. For example, * when you have matchEnglishPlurals set, then a page name "Foobars" * will be transformed into "Foobar", should a page "Foobars" not exist, * but the page "Foobar" would. This method gives you the correct * page name to refer to. * <P> * This facility can also be used to rewrite any page name, for example, * by using aliases. It can also be used to check the existence of any * page. * * @since 2.0 * @param page Page name. * @return The rewritten page name, or null, if the page does not exist. */ public String getFinalPageName( String page ) throws ProviderException { boolean isThere = simplePageExists( page ); if( !isThere && m_matchEnglishPlurals ) { if( page.endsWith("s") ) { page = page.substring( 0, page.length()-1 ); } else { page += "s"; } isThere = simplePageExists( page ); } return isThere ? page : null ; } /** * Just queries the existing pages directly from the page manager. * We also check overridden pages from jspwiki.properties */ private boolean simplePageExists( String page ) throws ProviderException { if( getSpecialPageReference(page) != null ) return true; return m_pageManager.pageExists( page ); } /** * Turns a WikiName into something that can be * called through using an URL. * * @since 1.4.1 */ public String encodeName( String pagename ) { if( m_useUTF8 ) return TextUtil.urlEncodeUTF8( pagename ); else return java.net.URLEncoder.encode( pagename ); } public String decodeName( String pagerequest ) { if( m_useUTF8 ) return TextUtil.urlDecodeUTF8( pagerequest ); else return java.net.URLDecoder.decode( pagerequest ); } /** * Returns the IANA name of the character set encoding we're * supposed to be using right now. * * @since 1.5.3 */ public String getContentEncoding() { if( m_useUTF8 ) return "UTF-8"; return "ISO-8859-1"; } /** * Returns the unconverted text of a page. * * @param page WikiName of the page to fetch. */ public String getText( String page ) { return getText( page, WikiPageProvider.LATEST_VERSION ); } /** * Returns the unconverted text of the given version of a page, * if it exists. This method also replaces the HTML entities. * * @param page WikiName of the page to fetch * @param version Version of the page to fetch */ public String getText( String page, int version ) { String result = getPureText( page, version ); // // Replace ampersand first, or else all quotes and stuff // get replaced as well with &quot; etc. // result = TextUtil.replaceString( result, "&", "&amp;" ); result = TextUtil.replaceEntities( result ); return result; } /** * Returns the pure text of a page, no conversions. * * @param version If WikiPageProvider.LATEST_VERSION, then uses the * latest version. */ // FIXME: Should throw an exception on unknown page/version? public String getPureText( String page, int version ) { String result = null; try { result = m_pageManager.getPageText( page, version ); } catch( ProviderException e ) { // FIXME } finally { if( result == null ) result = ""; } return result; } /** * @since 2.1.13. */ public String getPureText( WikiPage page ) { return getPureText( page.getName(), page.getVersion() ); } /** * Returns plain text (with HTML entities replaced). This should * be the main entry point for getText(). * * @since 1.9.15. */ public String getText( WikiContext context, WikiPage page ) { return getText( page.getName(), page.getVersion() ); } /** * Returns the converted HTML of the page using a different * context than the default context. */ public String getHTML( WikiContext context, WikiPage page ) { String pagedata = null; pagedata = getPureText( page.getName(), page.getVersion() ); String res = textToHTML( context, pagedata ); return res; } /** * Returns the converted HTML of the page. * * @param page WikiName of the page to convert. */ public String getHTML( String page ) { return getHTML( page, WikiPageProvider.LATEST_VERSION ); } /** * Returns the converted HTML of the page's specific version. * The version must be a positive integer, otherwise the current * version is returned. * * @param pagename WikiName of the page to convert. * @param version Version number to fetch * @deprecated */ public String getHTML( String pagename, int version ) { WikiPage page = new WikiPage( pagename ); page.setVersion( version ); WikiContext context = new WikiContext( this, page ); String res = getHTML( context, page ); return res; } /** * Converts raw page data to HTML. * * @param pagedata Raw page data to convert to HTML */ public String textToHTML( WikiContext context, String pagedata ) { return textToHTML( context, pagedata, null, null ); } /** * Reads a WikiPageful of data from a String and returns all links * internal to this Wiki in a Collection. */ protected Collection scanWikiLinks( WikiPage page, String pagedata ) { LinkCollector localCollector = new LinkCollector(); textToHTML( new WikiContext(this,page), pagedata, localCollector, null, localCollector, false ); return localCollector.getLinks(); } /** * Just convert WikiText to HTML. */ public String textToHTML( WikiContext context, String pagedata, StringTransmutator localLinkHook, StringTransmutator extLinkHook ) { return textToHTML( context, pagedata, localLinkHook, extLinkHook, null, true ); } /** * Helper method for doing the HTML translation. */ private String textToHTML( WikiContext context, String pagedata, StringTransmutator localLinkHook, StringTransmutator extLinkHook, StringTransmutator attLinkHook, boolean parseAccessRules ) { String result = ""; if( pagedata == null ) { log.error("NULL pagedata to textToHTML()"); return null; } TranslatorReader in = null; Collection links = null; try { pagedata = doPreTranslateFiltering( context, pagedata ); in = new TranslatorReader( context, new StringReader( pagedata ) ); in.addLocalLinkHook( localLinkHook ); in.addExternalLinkHook( extLinkHook ); in.addAttachmentLinkHook( attLinkHook ); if( !parseAccessRules ) in.disableAccessRules(); result = FileUtil.readContents( in ); result = doPostTranslateFiltering( context, result ); } catch( IOException e ) { log.error("Failed to scan page data: ", e); } finally { try { if( in != null ) in.close(); } catch( Exception e ) { log.fatal("Closing failed",e); } } return( result ); } /** * Updates all references for the given page. */ public void updateReferences( WikiPage page ) { String pageData = getPureText( page.getName(), WikiProvider.LATEST_VERSION ); m_referenceManager.updateReferences( page.getName(), scanWikiLinks( page, pageData ) ); } private String doPreTranslateFiltering( WikiContext context, String pageData ) { for( Iterator i = m_pageFilters.iterator(); i.hasNext(); ) { PageFilter f = (PageFilter) i.next(); pageData = f.preTranslate( context, pageData ); } return pageData; } private String doPostTranslateFiltering( WikiContext context, String pageData ) { for( Iterator i = m_pageFilters.iterator(); i.hasNext(); ) { PageFilter f = (PageFilter) i.next(); pageData = f.postTranslate( context, pageData ); } return pageData; } private String doPreSaveFiltering( WikiContext context, String pageData ) { for( Iterator i = m_pageFilters.iterator(); i.hasNext(); ) { PageFilter f = (PageFilter) i.next(); pageData = f.preSave( context, pageData ); } return pageData; } private void doPostSaveFiltering( WikiContext context, String pageData ) { for( Iterator i = m_pageFilters.iterator(); i.hasNext(); ) { PageFilter f = (PageFilter) i.next(); f.postSave( context, pageData ); } } /** * Writes the WikiText of a page into the * page repository. * * @since 2.1.28 * @param context The current WikiContext * @param text The Wiki markup for the page. */ public void saveText( WikiContext context, String text ) { WikiPage page = context.getPage(); if( page.getAuthor() == null ) { UserProfile wup = context.getCurrentUser(); if( wup != null ) page.setAuthor( wup.getName() ); } text = TextUtil.normalizePostData(text); text = doPreSaveFiltering( context, text ); // Hook into cross reference collection. m_referenceManager.updateReferences( page.getName(), scanWikiLinks( page, text ) ); try { m_pageManager.putPageText( page, text ); doPostSaveFiltering( context, text ); } catch( ProviderException e ) { log.error( "Unable to put page", e ); } } /** * Retrieves the user name. It will check if user has been authenticated, * or he has a cookie with his username set. The cookie takes precedence, * which allows the wiki master to set up a site with a single master * password. Note that this behaviour will be changed in 2.1 or thereabouts. * Earlier versions than 1.9.42 preferred the authenticated name over * the cookie name. * * @param request HttpServletRequest that was called. * @return The WikiName of the user, or null, if no username was set. */ // FIXME: This is a terrible time waster, parsing the // textual data every time it is used. /* // FIXME: Not used public String getUserName( HttpServletRequest request ) { if( request == null ) { return null; } // Get the user authentication - if he's not been authenticated // we then check from cookies. String author = request.getRemoteUser(); // // Try to fetch something from a cookie. // Cookie[] cookies = request.getCookies(); if( cookies != null ) { for( int i = 0; i < cookies.length; i++ ) { if( cookies[i].getName().equals( PREFS_COOKIE_NAME ) ) { UserProfile p = m_userManager.getUserProfile(cookies[i].getValue()); author = p.getName(); break; } } } // // Make sure that the author name is okay and a valid WikiName. // if( author != null ) { author = TranslatorReader.cleanLink( author ); } return author; } */ /** * If no author name has been set, then use the * IP address, if allowed. If no IP address is allowed, * then returns a default. * * @return Returns any sort of user name. Never returns null. */ // FIXME: Not used /* public String getValidUserName( HttpServletRequest request ) { return m_userManager.getUserProfile(request).getName(); } */ /** * @param request The HTTP Servlet request associated with this * transaction. * @since 1.5.1 * @deprecated */ /* public void saveText( WikiPage page, String text, HttpServletRequest request ) { text = TextUtil.normalizePostData(text); // Error protection or if the user info has been disabled. if( request == null || m_saveUserInfo == false ) { saveText( page, text ); } else { // Hook into cross reference collection. // Notice that this is definitely after the saveText() call above, // since it can be called externally and we only want this done once. m_referenceManager.updateReferences( page.getName(), scanWikiLinks( page, text ) ); String author = getValidUserName( request ); page.setAuthor( author ); try { m_pageManager.putPageText( page, text ); } catch( ProviderException e ) { log.error("Unable to put page: ", e); } } } */ /** * Returns the number of pages in this Wiki */ public int getPageCount() { return m_pageManager.getTotalPageCount(); } /** * Returns the provider name */ public String getCurrentProvider() { return m_pageManager.getProvider().getClass().getName(); } /** * return information about current provider. * @since 1.6.4 */ public String getCurrentProviderInfo() { return m_pageManager.getProviderDescription(); } /** * Returns a Collection of WikiPages, sorted in time * order of last change. */ // FIXME: Should really get a Date object and do proper comparisons. // This is terribly wasteful. public Collection getRecentChanges() { try { Collection pages = m_pageManager.getAllPages(); Collection atts = m_attachmentManager.getAllAttachments(); TreeSet sortedPages = new TreeSet( new PageTimeComparator() ); sortedPages.addAll( pages ); sortedPages.addAll( atts ); return sortedPages; } catch( ProviderException e ) { log.error( "Unable to fetch all pages: ",e); return null; } } /** * Parses an incoming search request, then * does a search. * <P> * Search language is simple: prepend a word * with a + to force a word to be included (all files * not containing that word are automatically rejected), * '-' to cause the rejection of all those files that contain * that word. */ // FIXME: does not support phrase searches yet, but for them // we need a version which reads the whole page into the memory // once. // // FIXME: Should also have attributes attached. // public Collection findPages( String query ) { StringTokenizer st = new StringTokenizer( query, " \t," ); QueryItem[] items = new QueryItem[st.countTokens()]; int word = 0; log.debug("Expecting "+items.length+" items"); // // Parse incoming search string // while( st.hasMoreTokens() ) { log.debug("Item "+word); String token = st.nextToken().toLowerCase(); items[word] = new QueryItem(); switch( token.charAt(0) ) { case '+': items[word].type = QueryItem.REQUIRED; token = token.substring(1); log.debug("Required word: "+token); break; case '-': items[word].type = QueryItem.FORBIDDEN; token = token.substring(1); log.debug("Forbidden word: "+token); break; default: items[word].type = QueryItem.REQUESTED; log.debug("Requested word: "+token); break; } items[word++].word = token; } Collection results = m_pageManager.findPages( items ); return results; } /** * Return a bunch of information from the web page. */ public WikiPage getPage( String pagereq ) { return getPage( pagereq, WikiProvider.LATEST_VERSION ); } /** * Returns specific information about a Wiki page. * @since 1.6.7. */ public WikiPage getPage( String pagereq, int version ) { try { WikiPage p = m_pageManager.getPageInfo( pagereq, version ); if( p == null ) { p = m_attachmentManager.getAttachmentInfo( (WikiContext)null, pagereq ); } return p; } catch( ProviderException e ) { log.error( "Unable to fetch page info",e); return null; } } /** * Returns a Collection of WikiPages containing the * version history of a page. */ public List getVersionHistory( String page ) { List c = null; try { c = m_pageManager.getVersionHistory( page ); if( c == null ) { c = m_attachmentManager.getVersionHistory( page ); } } catch( ProviderException e ) { log.error("FIXME"); } return c; } /** * Returns a diff of two versions of a page. * * @param page Page to return * @param version1 Version number of the old page. If * WikiPageProvider.LATEST_VERSION (-1), then uses current page. * @param version2 Version number of the new page. If * WikiPageProvider.LATEST_VERSION (-1), then uses current page. * * @return A HTML-ized difference between two pages. If there is no difference, * returns an empty string. */ public String getDiff( String page, int version1, int version2 ) { String page1 = getPureText( page, version1 ); String page2 = getPureText( page, version2 ); // Kludge to make diffs for new pages to work this way. if( version1 == WikiPageProvider.LATEST_VERSION ) { page1 = ""; } String diff = m_differenceEngine.makeDiff( page1, page2 ); diff = TextUtil.replaceEntities( diff ); try { if( diff.length() > 0 ) { diff = m_differenceEngine.colorizeDiff( diff ); } } catch( IOException e ) { log.error("Failed to colorize diff result.", e); } return diff; } /** * Attempts to locate a Wiki class, defaulting to the defaultPackage * in case the actual class could not be located. * * @param className Class to search for. * @param defaultPackage A default package to try if the class * cannot be directly located. May be null. * @throws ClassNotFoundException if the class could not be located. */ /* public static Class findWikiClass( String className, String defaultPackage ) throws ClassNotFoundException { Class tryClass; if( className == null ) { throw new ClassNotFoundException("Null className!"); } // // Attempt to use a shortcut, if possible. // try { tryClass = Class.forName( className ); } catch( ClassNotFoundException e ) { // FIXME: This causes "null" names to be searched for twice, which // is a performance penalty and not very nice. if( defaultPackage == null ) defaultPackage = ""; if( !defaultPackage.endsWith(".") ) defaultPackage += "."; tryClass = Class.forName( defaultPackage+className ); } return tryClass; } */ /** * Returns this object's ReferenceManager. * @since 1.6.1 */ // (FIXME: We may want to protect this, though...) public ReferenceManager getReferenceManager() { return m_referenceManager; } /** * Returns the current plugin manager. * @since 1.6.1 */ public PluginManager getPluginManager() { return m_pluginManager; } public VariableManager getVariableManager() { return m_variableManager; } /** * Returns the current PageManager. */ public PageManager getPageManager() { return m_pageManager; } /** * Returns the current AttachmentManager. * @since 1.9.31. */ public AttachmentManager getAttachmentManager() { return m_attachmentManager; } /** * Returns the currently used authorization manager. */ public AuthorizationManager getAuthorizationManager() { return m_authorizationManager; } /** * Returns the currently used user manager. */ public UserManager getUserManager() { return m_userManager; } /** * Shortcut to create a WikiContext from the Wiki page. * * @since 2.1.15. */ // FIXME: We need to have a version which takes a fixed page // name as well, or check it elsewhere. public WikiContext createContext( HttpServletRequest request, String requestContext ) { if( !m_isConfigured ) { throw new InternalWikiException("WikiEngine has not been properly started. It is likely that the configuration is faulty. Please check all logs for the possible reason."); } String pagereq = safeGetParameter( request, "page" ); String template = safeGetParameter( request, "skin" ); if( pagereq == null || pagereq.length() == 0 ) { pagereq = getFrontPage(); } int version = WikiProvider.LATEST_VERSION; String rev = request.getParameter("version"); if( rev != null ) { version = Integer.parseInt( rev ); } WikiPage wikipage = getPage( pagereq, version ); if( wikipage == null ) { wikipage = new WikiPage( pagereq ); } if( template == null ) { template = (String)wikipage.getAttribute( PROP_TEMPLATEDIR ); // FIXME: Most definitely this should be checked for // existence, or else it is possible to create pages that // cannot be shown. if( template == null || template.length() == 0 ) { template = getTemplateDir(); } } WikiContext context = new WikiContext( this, wikipage ); context.setRequestContext( requestContext ); context.setHttpRequest( request ); context.setTemplate( template ); UserProfile user = getUserManager().getUserProfile( request ); context.setCurrentUser( user ); return context; } /** * Returns the URL of the global RSS file. May be null, if the * RSS file generation is not operational. * @since 1.7.10 */ public String getGlobalRSSURL() { if( m_rssURL != null ) { return getBaseURL()+m_rssURL; } return null; } /** * Runs the RSS generation thread. * FIXME: MUST be somewhere else, this is not a good place. */ private class RSSThread extends Thread { public void run() { try { String fileName = m_properties.getProperty( RSSGenerator.PROP_RSSFILE, "rss.rdf" ); int rssInterval = TextUtil.parseIntParameter( m_properties.getProperty( RSSGenerator.PROP_INTERVAL ), 3600 ); log.debug("RSS file will be at "+fileName); log.debug("RSS refresh interval (seconds): "+rssInterval); while(true) { Writer out = null; Reader in = null; try { // // Generate RSS file, output it to // default "rss.rdf". // log.info("Regenerating RSS feed to "+fileName); String feed = m_rssGenerator.generate(); File file = new File( m_rootPath, fileName ); in = new StringReader(feed); out = new BufferedWriter( new OutputStreamWriter( new FileOutputStream(file), "UTF-8") ); FileUtil.copyContents( in, out ); m_rssURL = fileName; } catch( IOException e ) { log.error("Cannot generate RSS feed to "+fileName, e ); m_rssURL = null; } finally { try { if( in != null ) in.close(); if( out != null ) out.close(); } catch( IOException e ) { log.fatal("Could not close I/O for RSS", e ); break; } } Thread.sleep(rssInterval*1000L); } // while } catch(InterruptedException e) { log.error("RSS thread interrupted, no more RSS feeds", e); } // // Signal: no more RSS feeds. // m_rssURL = null; } } }
jspwiki.properties were not closed after they had been loaded. This causes problems with WebLogic, e.g. git-svn-id: 6c0206e3b9edd104850923da33ebd73b435d374d@622937 13f79535-47bb-0310-9956-ffa450edef68
src/com/ecyrd/jspwiki/WikiEngine.java
jspwiki.properties were not closed after they had been loaded. This causes problems with WebLogic, e.g.
Java
apache-2.0
69b504d7f952bdfba736ce2b6af88ab4cf90adf1
0
fj11/jmeter,kyroskoh/jmeter,thomsonreuters/jmeter,hizhangqi/jmeter-1,d0k1/jmeter,vherilier/jmeter,vherilier/jmeter,kschroeder/jmeter,irfanah/jmeter,etnetera/jmeter,kyroskoh/jmeter,hemikak/jmeter,ra0077/jmeter,ThiagoGarciaAlves/jmeter,ubikloadpack/jmeter,kschroeder/jmeter,max3163/jmeter,hizhangqi/jmeter-1,irfanah/jmeter,etnetera/jmeter,hemikak/jmeter,DoctorQ/jmeter,irfanah/jmeter,vherilier/jmeter,ubikloadpack/jmeter,liwangbest/jmeter,etnetera/jmeter,d0k1/jmeter,tuanhq/jmeter,hemikak/jmeter,kyroskoh/jmeter,vherilier/jmeter,max3163/jmeter,d0k1/jmeter,tuanhq/jmeter,liwangbest/jmeter,ubikfsabbe/jmeter,ubikloadpack/jmeter,DoctorQ/jmeter,DoctorQ/jmeter,kschroeder/jmeter,thomsonreuters/jmeter,max3163/jmeter,hemikak/jmeter,hizhangqi/jmeter-1,liwangbest/jmeter,ubikloadpack/jmeter,ubikfsabbe/jmeter,ThiagoGarciaAlves/jmeter,thomsonreuters/jmeter,max3163/jmeter,ThiagoGarciaAlves/jmeter,ra0077/jmeter,tuanhq/jmeter,ra0077/jmeter,ra0077/jmeter,d0k1/jmeter,fj11/jmeter,ubikfsabbe/jmeter,fj11/jmeter,etnetera/jmeter,etnetera/jmeter,ubikfsabbe/jmeter
/* * 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.jmeter; import java.awt.event.ActionEvent; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.net.Authenticator; import java.net.MalformedURLException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Enumeration; import java.util.Collection; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.Properties; import java.util.StringTokenizer; import javax.swing.JLabel; import org.apache.commons.cli.avalon.CLArgsParser; import org.apache.commons.cli.avalon.CLOption; import org.apache.commons.cli.avalon.CLOptionDescriptor; import org.apache.commons.cli.avalon.CLUtil; import org.apache.jmeter.control.ReplaceableController; import org.apache.jmeter.engine.ClientJMeterEngine; import org.apache.jmeter.engine.JMeterEngine; import org.apache.jmeter.engine.RemoteJMeterEngineImpl; import org.apache.jmeter.engine.StandardJMeterEngine; import org.apache.jmeter.engine.event.LoopIterationEvent; import org.apache.jmeter.exceptions.IllegalUserActionException; import org.apache.jmeter.gui.GuiPackage; import org.apache.jmeter.gui.action.ActionNames; import org.apache.jmeter.gui.action.ActionRouter; import org.apache.jmeter.gui.action.Load; import org.apache.jmeter.gui.tree.JMeterTreeListener; import org.apache.jmeter.gui.tree.JMeterTreeNode; import org.apache.jmeter.gui.tree.JMeterTreeModel; import org.apache.jmeter.plugin.JMeterPlugin; import org.apache.jmeter.plugin.PluginManager; import org.apache.jmeter.reporters.ResultCollector; import org.apache.jmeter.reporters.Summariser; import org.apache.jmeter.samplers.Remoteable; import org.apache.jmeter.save.SaveService; import org.apache.jmeter.services.FileServer; import org.apache.jmeter.testelement.TestElement; import org.apache.jmeter.testelement.TestListener; import org.apache.jmeter.util.BeanShellInterpreter; import org.apache.jmeter.util.BeanShellServer; import org.apache.jmeter.util.JMeterUtils; import org.apache.jorphan.collections.HashTree; import org.apache.jorphan.gui.ComponentUtil; import org.apache.jorphan.logging.LoggingManager; import org.apache.jorphan.collections.SearchByClass; import org.apache.jorphan.reflect.ClassTools; import org.apache.jorphan.util.JMeterException; import org.apache.jorphan.util.JOrphanUtils; import org.apache.log.Logger; import com.thoughtworks.xstream.converters.ConversionException; /** * @author mstover */ public class JMeter implements JMeterPlugin { private static final Logger log = LoggingManager.getLoggerForClass(); public static final String HTTP_PROXY_PASS = "http.proxyPass"; // $NON-NLS-1$ public static final String HTTP_PROXY_USER = "http.proxyUser"; // $NON-NLS-1$ private static final int PROXY_PASSWORD = 'a';// $NON-NLS-1$ private static final int JMETER_HOME_OPT = 'd';// $NON-NLS-1$ private static final int HELP_OPT = 'h';// $NON-NLS-1$ // jmeter.log private static final int JMLOGFILE_OPT = 'j';// $NON-NLS-1$ // sample result log file private static final int LOGFILE_OPT = 'l';// $NON-NLS-1$ private static final int NONGUI_OPT = 'n';// $NON-NLS-1$ private static final int PROPFILE_OPT = 'p';// $NON-NLS-1$ private static final int PROPFILE2_OPT = 'q';// $NON-NLS-1$ private static final int REMOTE_OPT = 'r';// $NON-NLS-1$ private static final int SERVER_OPT = 's';// $NON-NLS-1$ private static final int TESTFILE_OPT = 't';// $NON-NLS-1$ private static final int PROXY_USERNAME = 'u';// $NON-NLS-1$ private static final int VERSION_OPT = 'v';// $NON-NLS-1$ private static final int SYSTEM_PROPERTY = 'D';// $NON-NLS-1$ private static final int PROXY_HOST = 'H';// $NON-NLS-1$ private static final int JMETER_PROPERTY = 'J';// $NON-NLS-1$ private static final int LOGLEVEL = 'L';// $NON-NLS-1$ private static final int NONPROXY_HOSTS = 'N';// $NON-NLS-1$ private static final int PROXY_PORT = 'P';// $NON-NLS-1$ private static final int REMOTE_OPT_PARAM = 'R';// $NON-NLS-1$ private static final int SYSTEM_PROPFILE = 'S';// $NON-NLS-1$ /** * Define the understood options. Each CLOptionDescriptor contains: * <ul> * <li>The "long" version of the option. Eg, "help" means that "--help" * will be recognised.</li> * <li>The option flags, governing the option's argument(s).</li> * <li>The "short" version of the option. Eg, 'h' means that "-h" will be * recognised.</li> * <li>A description of the option.</li> * </ul> */ private static final CLOptionDescriptor[] options = new CLOptionDescriptor[] { new CLOptionDescriptor("help", CLOptionDescriptor.ARGUMENT_DISALLOWED, HELP_OPT, "print usage information and exit"), new CLOptionDescriptor("version", CLOptionDescriptor.ARGUMENT_DISALLOWED, VERSION_OPT, "print the version information and exit"), new CLOptionDescriptor("propfile", CLOptionDescriptor.ARGUMENT_REQUIRED, PROPFILE_OPT, "the jmeter property file to use"), new CLOptionDescriptor("addprop", CLOptionDescriptor.ARGUMENT_REQUIRED | CLOptionDescriptor.DUPLICATES_ALLOWED, PROPFILE2_OPT, "additional JMeter property file(s)"), new CLOptionDescriptor("testfile", CLOptionDescriptor.ARGUMENT_REQUIRED, TESTFILE_OPT, "the jmeter test(.jmx) file to run"), new CLOptionDescriptor("logfile", CLOptionDescriptor.ARGUMENT_REQUIRED, LOGFILE_OPT, "the file to log samples to"), new CLOptionDescriptor("jmeterlogfile", CLOptionDescriptor.ARGUMENT_REQUIRED, JMLOGFILE_OPT, "jmeter run log file (jmeter.log)"), new CLOptionDescriptor("nongui", CLOptionDescriptor.ARGUMENT_DISALLOWED, NONGUI_OPT, "run JMeter in nongui mode"), new CLOptionDescriptor("server", CLOptionDescriptor.ARGUMENT_DISALLOWED, SERVER_OPT, "run the JMeter server"), new CLOptionDescriptor("proxyHost", CLOptionDescriptor.ARGUMENT_REQUIRED, PROXY_HOST, "Set a proxy server for JMeter to use"), new CLOptionDescriptor("proxyPort", CLOptionDescriptor.ARGUMENT_REQUIRED, PROXY_PORT, "Set proxy server port for JMeter to use"), new CLOptionDescriptor("nonProxyHosts", CLOptionDescriptor.ARGUMENT_REQUIRED, NONPROXY_HOSTS, "Set nonproxy host list (e.g. *.apache.org|localhost)"), new CLOptionDescriptor("username", CLOptionDescriptor.ARGUMENT_REQUIRED, PROXY_USERNAME, "Set username for proxy server that JMeter is to use"), new CLOptionDescriptor("password", CLOptionDescriptor.ARGUMENT_REQUIRED, PROXY_PASSWORD, "Set password for proxy server that JMeter is to use"), new CLOptionDescriptor("jmeterproperty", CLOptionDescriptor.DUPLICATES_ALLOWED | CLOptionDescriptor.ARGUMENTS_REQUIRED_2, JMETER_PROPERTY, "Define additional JMeter properties"), new CLOptionDescriptor("systemproperty", CLOptionDescriptor.DUPLICATES_ALLOWED | CLOptionDescriptor.ARGUMENTS_REQUIRED_2, SYSTEM_PROPERTY, "Define additional system properties"), new CLOptionDescriptor("systemPropertyFile", CLOptionDescriptor.DUPLICATES_ALLOWED | CLOptionDescriptor.ARGUMENT_REQUIRED, SYSTEM_PROPFILE, "additional system property file(s)"), new CLOptionDescriptor("loglevel", CLOptionDescriptor.DUPLICATES_ALLOWED | CLOptionDescriptor.ARGUMENTS_REQUIRED_2, LOGLEVEL, "[category=]level e.g. jorphan=INFO or jmeter.util=DEBUG"), new CLOptionDescriptor("runremote", CLOptionDescriptor.ARGUMENT_DISALLOWED, REMOTE_OPT, "Start remote servers (as defined in remote_hosts)"), new CLOptionDescriptor("remotestart", CLOptionDescriptor.ARGUMENT_REQUIRED, REMOTE_OPT_PARAM, "Start these remote servers (overrides remote_hosts)"), new CLOptionDescriptor("homedir", CLOptionDescriptor.ARGUMENT_REQUIRED, JMETER_HOME_OPT, "the jmeter home directory to use"), }; public JMeter() { } // Hack to allow automated tests to find when test has ended //transient boolean testEnded = false; private JMeter parent; /** * Starts up JMeter in GUI mode */ private void startGui(CLOption testFile) { PluginManager.install(this, true); JMeterTreeModel treeModel = new JMeterTreeModel(); JMeterTreeListener treeLis = new JMeterTreeListener(treeModel); treeLis.setActionHandler(ActionRouter.getInstance()); // NOTUSED: GuiPackage guiPack = GuiPackage.getInstance(treeLis, treeModel); org.apache.jmeter.gui.MainFrame main = new org.apache.jmeter.gui.MainFrame(ActionRouter.getInstance(), treeModel, treeLis); // TODO - set up these items in MainFrame? main.setTitle("Apache JMeter ("+JMeterUtils.getJMeterVersion()+")");// $NON-NLS-1$ main.setIconImage(JMeterUtils.getImage("jmeter.jpg").getImage());// $NON-NLS-1$ ComponentUtil.centerComponentInWindow(main, 80); main.show(); ActionRouter.getInstance().actionPerformed(new ActionEvent(main, 1, ActionNames.ADD_ALL)); String arg; if (testFile != null && (arg = testFile.getArgument()) != null) { FileInputStream reader = null; try { File f = new File(arg); log.info("Loading file: " + f); reader = new FileInputStream(f); HashTree tree = SaveService.loadTree(reader); GuiPackage.getInstance().setTestPlanFile(f.getAbsolutePath()); Load.insertLoadedTree(1, tree); } catch (ConversionException e) { log.error("Failure loading test file", e); JMeterUtils.reportErrorToUser(SaveService.CEtoString(e)); } catch (Exception e) { log.error("Failure loading test file", e); JMeterUtils.reportErrorToUser(e.toString()); } finally { JOrphanUtils.closeQuietly(reader); } } } /** * Takes the command line arguments and uses them to determine how to * startup JMeter. */ public void start(String[] args) { CLArgsParser parser = new CLArgsParser(args, options); if (null != parser.getErrorString()) { System.err.println("Error: " + parser.getErrorString()); System.out.println("Usage"); System.out.println(CLUtil.describeOptions(options).toString()); return; } try { initializeProperties(parser); // Also initialises JMeter logging /* * The following is needed for HTTPClient. * (originally tried doing this in HTTPSampler2, * but it appears that it was done too late when running in GUI mode) * Set the commons logging default to Avalon Logkit, if not already defined */ if (System.getProperty("org.apache.commons.logging.Log") == null) { // $NON-NLS-1$ System.setProperty("org.apache.commons.logging.Log" // $NON-NLS-1$ , "org.apache.commons.logging.impl.LogKitLogger"); // $NON-NLS-1$ } log.info(JMeterUtils.getJMeterCopyright()); log.info("Version " + JMeterUtils.getJMeterVersion()); logProperty("java.version"); //$NON-NLS-1$ logProperty("os.name"); //$NON-NLS-1$ logProperty("os.arch"); //$NON-NLS-1$ logProperty("os.version"); //$NON-NLS-1$ logProperty("file.encoding"); // $NON-NLS-1$ log.info("Default Locale=" + Locale.getDefault().getDisplayName());// $NON-NLS-1$ log.info("JMeter Locale=" + JMeterUtils.getLocale().getDisplayName());// $NON-NLS-1$ log.info("JMeterHome=" + JMeterUtils.getJMeterHome());// $NON-NLS-1$ logProperty("user.dir"," ="); //$NON-NLS-1$ log.info("PWD ="+new File(".").getCanonicalPath());//$NON-NLS-1$ setProxy(parser); updateClassLoader(); if (log.isDebugEnabled()) { String jcp=System.getProperty("java.class.path");// $NON-NLS-1$ String bits[] =jcp.split(File.pathSeparator); log.debug("ClassPath"); for(int i = 0; i<bits.length ;i++){ log.debug(bits[i]); } log.debug(jcp); } // Set some (hopefully!) useful properties long now=System.currentTimeMillis(); JMeterUtils.setProperty("START.MS",Long.toString(now)); Date today=new Date(now); // so it agrees with above // TODO perhaps should share code with __time() function for this... JMeterUtils.setProperty("START.YMD",new SimpleDateFormat("yyyyMMdd").format(today)); JMeterUtils.setProperty("START.HMS",new SimpleDateFormat("HHmmss").format(today)); if (parser.getArgumentById(VERSION_OPT) != null) { System.out.println(JMeterUtils.getJMeterCopyright()); System.out.println("Version " + JMeterUtils.getJMeterVersion()); } else if (parser.getArgumentById(HELP_OPT) != null) { System.out.println(JMeterUtils.getResourceFileAsText("org/apache/jmeter/help.txt"));// $NON-NLS-1$ } else if (parser.getArgumentById(SERVER_OPT) != null) { // We need to check if the JMeter home contains spaces in the path, // because then we will not be able to bind to RMI registry, see // Java bug id 4496398 final String jmHome = JMeterUtils.getJMeterHome(); if(jmHome.indexOf(" ") > -1) {// $NON-NLS-1$ // Just warn user, and exit, no reason to continue, since we will // not be able to bind to RMI registry, until Java bug 4496398 is fixed log.error("JMeter path cannot contain spaces when run in server mode : " + jmHome); throw new RuntimeException("JMeter path cannot contain spaces when run in server mode: "+jmHome); } // Start the server startServer(JMeterUtils.getPropDefault("server_port", 0));// $NON-NLS-1$ startOptionalServers(); } else if (parser.getArgumentById(NONGUI_OPT) == null) { startGui(parser.getArgumentById(TESTFILE_OPT)); startOptionalServers(); } else { CLOption rem=parser.getArgumentById(REMOTE_OPT_PARAM); if (rem==null) rem=parser.getArgumentById(REMOTE_OPT); startNonGui(parser.getArgumentById(TESTFILE_OPT), parser.getArgumentById(LOGFILE_OPT), rem); startOptionalServers(); } } catch (IllegalUserActionException e) { System.out.println(e.getMessage()); System.out.println("Incorrect Usage"); System.out.println(CLUtil.describeOptions(options).toString()); } catch (Throwable e) { if (log != null){ log.fatalError("An error occurred: ",e); } else { e.printStackTrace(); } System.out.println("An error occurred: " + e.getMessage()); System.exit(1); } } // Update classloader if necessary private void updateClassLoader() { updatePath("search_paths",";"); //$NON-NLS-1$//$NON-NLS-2$ updatePath("user.classpath",File.pathSeparator);//$NON-NLS-1$ } private void updatePath(String property, String sep) { String userpath= JMeterUtils.getPropDefault(property,"");// $NON-NLS-1$ if (userpath.length() <= 0) return; log.info(property+"="+userpath); //$NON-NLS-1$ StringTokenizer tok = new StringTokenizer(userpath, sep); while(tok.hasMoreTokens()) { String path=tok.nextToken(); File f=new File(path); if (!f.canRead() && !f.isDirectory()) { log.warn("Can't read "+path); } else { log.info("Adding to classpath: "+path); try { NewDriver.addPath(path); } catch (MalformedURLException e) { log.warn("Error adding: "+path+" "+e.getLocalizedMessage()); } } } } /** * */ private void startOptionalServers() { int bshport = JMeterUtils.getPropDefault("beanshell.server.port", 0);// $NON-NLS-1$ String bshfile = JMeterUtils.getPropDefault("beanshell.server.file", "");// $NON-NLS-1$ $NON-NLS-2$ if (bshport > 0) { log.info("Starting Beanshell server (" + bshport + "," + bshfile + ")"); Runnable t = new BeanShellServer(bshport, bshfile); t.run(); } // Should we run a beanshell script on startup? String bshinit = JMeterUtils.getProperty("beanshell.init.file");// $NON-NLS-1$ if (bshinit != null){ log.info("Run Beanshell on file: "+bshinit); try { BeanShellInterpreter bsi = new BeanShellInterpreter();//bshinit,log); bsi.source(bshinit); } catch (ClassNotFoundException e) { log.warn("Could not start Beanshell: "+e.getLocalizedMessage()); } catch (JMeterException e) { log.warn("Could not process Beanshell file: "+e.getLocalizedMessage()); } } int mirrorPort=JMeterUtils.getPropDefault("mirror.server.port", 0);// $NON-NLS-1$ if (mirrorPort > 0){ log.info("Starting Mirror server (" + mirrorPort + ")"); try { Object instance = ClassTools.construct( "org.apache.jmeter.protocol.http.control.HttpMirrorControl",// $NON-NLS-1$ mirrorPort); ClassTools.invoke(instance,"startHttpMirror"); } catch (JMeterException e) { log.warn("Could not start Mirror server",e); } } } /** * Sets a proxy server for the JVM if the command line arguments are * specified. */ private void setProxy(CLArgsParser parser) throws IllegalUserActionException { if (parser.getArgumentById(PROXY_USERNAME) != null) { Properties jmeterProps = JMeterUtils.getJMeterProperties(); if (parser.getArgumentById(PROXY_PASSWORD) != null) { String u, p; Authenticator.setDefault(new ProxyAuthenticator(u = parser.getArgumentById(PROXY_USERNAME) .getArgument(), p = parser.getArgumentById(PROXY_PASSWORD).getArgument())); log.info("Set Proxy login: " + u + "/" + p); jmeterProps.setProperty(HTTP_PROXY_USER, u);//for Httpclient jmeterProps.setProperty(HTTP_PROXY_PASS, p);//for Httpclient } else { String u; Authenticator.setDefault(new ProxyAuthenticator(u = parser.getArgumentById(PROXY_USERNAME) .getArgument(), "")); log.info("Set Proxy login: " + u); jmeterProps.setProperty(HTTP_PROXY_USER, u); } } if (parser.getArgumentById(PROXY_HOST) != null && parser.getArgumentById(PROXY_PORT) != null) { String h = parser.getArgumentById(PROXY_HOST).getArgument(); String p = parser.getArgumentById(PROXY_PORT).getArgument(); System.setProperty("http.proxyHost", h );// $NON-NLS-1$ System.setProperty("https.proxyHost", h);// $NON-NLS-1$ System.setProperty("http.proxyPort", p);// $NON-NLS-1$ System.setProperty("https.proxyPort", p);// $NON-NLS-1$ log.info("Set http[s].proxyHost: " + h + " Port: " + p); } else if (parser.getArgumentById(PROXY_HOST) != null || parser.getArgumentById(PROXY_PORT) != null) { throw new IllegalUserActionException(JMeterUtils.getResString("proxy_cl_error"));// $NON-NLS-1$ } if (parser.getArgumentById(NONPROXY_HOSTS) != null) { String n = parser.getArgumentById(NONPROXY_HOSTS).getArgument(); System.setProperty("http.nonProxyHosts", n );// $NON-NLS-1$ System.setProperty("https.nonProxyHosts", n );// $NON-NLS-1$ log.info("Set http[s].nonProxyHosts: "+n); } } private void initializeProperties(CLArgsParser parser) { if (parser.getArgumentById(PROPFILE_OPT) != null) { JMeterUtils.loadJMeterProperties(parser.getArgumentById(PROPFILE_OPT).getArgument()); } else { JMeterUtils.loadJMeterProperties(NewDriver.getJMeterDir() + File.separator + "bin" + File.separator // $NON-NLS-1$ + "jmeter.properties");// $NON-NLS-1$ } if (parser.getArgumentById(JMLOGFILE_OPT) != null){ String jmlogfile=parser.getArgumentById(JMLOGFILE_OPT).getArgument(); JMeterUtils.setProperty(LoggingManager.LOG_FILE,jmlogfile); } JMeterUtils.initLogging(); JMeterUtils.initLocale(); // Bug 33845 - allow direct override of Home dir if (parser.getArgumentById(JMETER_HOME_OPT) == null) { JMeterUtils.setJMeterHome(NewDriver.getJMeterDir()); } else { JMeterUtils.setJMeterHome(parser.getArgumentById(JMETER_HOME_OPT).getArgument()); } Properties jmeterProps = JMeterUtils.getJMeterProperties(); // Add local JMeter properties, if the file is found String userProp = JMeterUtils.getPropDefault("user.properties",""); //$NON-NLS-1$ if (userProp.length() > 0){ //$NON-NLS-1$ FileInputStream fis=null; try { File file = JMeterUtils.findFile(userProp); if (file.canRead()){ log.info("Loading user properties from: "+file.getCanonicalPath()); fis = new FileInputStream(file); Properties tmp = new Properties(); tmp.load(fis); jmeterProps.putAll(tmp); LoggingManager.setLoggingLevels(tmp);//Do what would be done earlier } } catch (IOException e) { log.warn("Error loading user property file: " + userProp, e); } finally { JOrphanUtils.closeQuietly(fis); } } // Add local system properties, if the file is found String sysProp = JMeterUtils.getPropDefault("system.properties",""); //$NON-NLS-1$ if (sysProp.length() > 0){ FileInputStream fis=null; try { File file = JMeterUtils.findFile(sysProp); if (file.canRead()){ log.info("Loading system properties from: "+file.getCanonicalPath()); fis = new FileInputStream(file); System.getProperties().load(fis); } } catch (IOException e) { log.warn("Error loading system property file: " + sysProp, e); } finally { JOrphanUtils.closeQuietly(fis); } } // Process command line property definitions // These can potentially occur multiple times List clOptions = parser.getArguments(); int size = clOptions.size(); for (int i = 0; i < size; i++) { CLOption option = (CLOption) clOptions.get(i); String name = option.getArgument(0); String value = option.getArgument(1); FileInputStream fis = null; switch (option.getDescriptor().getId()) { // Should not have any text arguments case CLOption.TEXT_ARGUMENT: throw new IllegalArgumentException("Unknown arg: "+option.getArgument()); case PROPFILE2_OPT: // Bug 33920 - allow multiple props try { fis = new FileInputStream(new File(name)); Properties tmp = new Properties(); tmp.load(fis); jmeterProps.putAll(tmp); LoggingManager.setLoggingLevels(tmp);//Do what would be done earlier } catch (FileNotFoundException e) { log.warn("Can't find additional property file: " + name, e); } catch (IOException e) { log.warn("Error loading additional property file: " + name, e); } finally { JOrphanUtils.closeQuietly(fis); } break; case SYSTEM_PROPFILE: log.info("Setting System properties from file: " + name); try { fis = new FileInputStream(new File(name)); System.getProperties().load(fis); } catch (IOException e) { log.warn("Cannot find system property file "+e.getLocalizedMessage()); } finally { JOrphanUtils.closeQuietly(fis); } break; case SYSTEM_PROPERTY: if (value.length() > 0) { // Set it log.info("Setting System property: " + name + "=" + value); System.getProperties().setProperty(name, value); } else { // Reset it log.warn("Removing System property: " + name); System.getProperties().remove(name); } break; case JMETER_PROPERTY: if (value.length() > 0) { // Set it log.info("Setting JMeter property: " + name + "=" + value); jmeterProps.setProperty(name, value); } else { // Reset it log.warn("Removing JMeter property: " + name); jmeterProps.remove(name); } break; case LOGLEVEL: if (value.length() > 0) { // Set category log.info("LogLevel: " + name + "=" + value); LoggingManager.setPriority(value, name); } else { // Set root level log.warn("LogLevel: " + name); LoggingManager.setPriority(name); } break; } } } private void startServer(int port) { try { new RemoteJMeterEngineImpl(port); } catch (Exception ex) { log.error("Giving up, as server failed with:", ex); System.err.println("Server failed to start: "+ex); System.exit(1);// Give up } } private void startNonGui(CLOption testFile, CLOption logFile, CLOption remoteStart) throws IllegalUserActionException { // add a system property so samplers can check to see if JMeter // is running in NonGui mode System.setProperty("JMeter.NonGui", "true");// $NON-NLS-1$ // Force the X11 display to be checked try { new JLabel(); } catch (InternalError e){ // ignored } JMeter driver = new JMeter(); driver.parent = this; PluginManager.install(this, false); String remote_hosts_string = null; if (remoteStart != null) { remote_hosts_string = remoteStart.getArgument(); if (remote_hosts_string == null) { remote_hosts_string = JMeterUtils.getPropDefault( "remote_hosts", //$NON-NLS-1$ "127.0.0.1");//$NON-NLS-1$ } } if (testFile == null) { throw new IllegalUserActionException(); } String argument = testFile.getArgument(); if (argument == null) { throw new IllegalUserActionException(); } if (logFile == null) { driver.run(argument, null, remoteStart != null,remote_hosts_string); } else { driver.run(argument, logFile.getArgument(), remoteStart != null,remote_hosts_string); } } // run test in batch mode private void run(String testFile, String logFile, boolean remoteStart, String remote_hosts_string) { FileInputStream reader = null; try { File f = new File(testFile); if (!f.exists() || !f.isFile()) { println("Could not open " + testFile); return; } FileServer.getFileServer().setBasedir(f.getAbsolutePath()); reader = new FileInputStream(f); log.info("Loading file: " + f); HashTree tree = SaveService.loadTree(reader); JMeterTreeModel treeModel = new JMeterTreeModel(new Object());// Create non-GUI version to avoid headless problems JMeterTreeNode root = (JMeterTreeNode) treeModel.getRoot(); treeModel.addSubTree(tree, root); // Hack to resolve ModuleControllers in non GUI mode SearchByClass replaceableControllers = new SearchByClass(ReplaceableController.class); tree.traverse(replaceableControllers); Collection replaceableControllersRes = replaceableControllers.getSearchResults(); for (Iterator iter = replaceableControllersRes.iterator(); iter.hasNext();) { ReplaceableController replaceableController = (ReplaceableController) iter.next(); replaceableController.resolveReplacementSubTree(root); } // Remove the disabled items // For GUI runs this is done in Start.java convertSubTree(tree); if (logFile != null) { ResultCollector logger = new ResultCollector(); logger.setFilename(logFile); tree.add(tree.getArray()[0], logger); } String summariserName = JMeterUtils.getPropDefault("summariser.name", "");//$NON-NLS-1$ if (summariserName.length() > 0) { log.info("Creating summariser <" + summariserName + ">"); println("Creating summariser <" + summariserName + ">"); Summariser summer = new Summariser(summariserName); tree.add(tree.getArray()[0], summer); } tree.add(tree.getArray()[0], new ListenToTest(parent)); println("Created the tree successfully"); JMeterEngine engine = null; if (!remoteStart) { engine = new StandardJMeterEngine(); engine.configure(tree); long now=System.currentTimeMillis(); println("Starting the test @ "+new Date(now)+" ("+now+")"); engine.runTest(); } else { java.util.StringTokenizer st = new java.util.StringTokenizer(remote_hosts_string, ",");//$NON-NLS-1$ List engines = new LinkedList(); while (st.hasMoreElements()) { String el = (String) st.nextElement(); println("Configuring remote engine for " + el); engines.add(doRemoteInit(el.trim(), tree)); } println("Starting remote engines"); long now=System.currentTimeMillis(); println("Starting the test @ "+new Date(now)+" ("+now+")"); Iterator iter = engines.iterator(); while (iter.hasNext()) { engine = (JMeterEngine) iter.next(); engine.runTest(); } println("Remote engines have been started"); } } catch (Exception e) { System.out.println("Error in NonGUIDriver " + e.toString()); log.error("", e); } finally { JOrphanUtils.closeQuietly(reader); } } /** * Refactored from AbstractAction.java * * @param tree */ public static void convertSubTree(HashTree tree) { Iterator iter = new LinkedList(tree.list()).iterator(); while (iter.hasNext()) { Object o = iter.next(); if (o instanceof TestElement) { TestElement item = (TestElement) o; if (item.isEnabled()) { if (item instanceof ReplaceableController) { // HACK: force the controller to load its tree ReplaceableController rc = (ReplaceableController) item .clone(); HashTree subTree = tree.getTree(item); if (subTree != null) { HashTree replacementTree = rc .getReplacementSubTree(); if (replacementTree != null) { convertSubTree(replacementTree); tree.replace(item, rc); tree.set(rc, replacementTree); } } else { convertSubTree(tree.getTree(item)); } } else { convertSubTree(tree.getTree(item)); } } else tree.remove(item); } else { JMeterTreeNode item = (JMeterTreeNode) o; if (item.isEnabled()) { // Replacement only needs to occur when starting the engine // @see StandardJMeterEngine.run() if (item.getUserObject() instanceof ReplaceableController) { ReplaceableController rc = (ReplaceableController) item .getTestElement(); HashTree subTree = tree.getTree(item); if (subTree != null) { HashTree replacementTree = rc .getReplacementSubTree(); if (replacementTree != null) { convertSubTree(replacementTree); tree.replace(item, rc); tree.set(rc, replacementTree); } } } else { convertSubTree(tree.getTree(item)); TestElement testElement = item.getTestElement(); tree.replace(item, testElement); } } else { tree.remove(item); } } } } private JMeterEngine doRemoteInit(String hostName, HashTree testTree) { JMeterEngine engine = null; try { engine = new ClientJMeterEngine(hostName); } catch (Exception e) { log.fatalError("Failure connecting to remote host", e); System.err.println("Failure connecting to remote host"+e); System.exit(1); } engine.configure(testTree); return engine; } /* * Listen to test and handle tidyup after non-GUI test completes. * If running a remote test, then after waiting a few seconds for listeners to finish files, * it calls System.exit to deal with the Naming Timer Thread. */ private static class ListenToTest implements TestListener, Runnable, Remoteable { private int started = 0; // keep track of remote tests private boolean remote = false; // Are we running a remote test? //NOT YET USED private JMeter _parent; private ListenToTest(JMeter parent) { //_parent = parent; } public synchronized void testEnded(String host) { started--; long now=System.currentTimeMillis(); log.info("Finished remote host: " + host + " ("+now+")"); if (started <= 0) { remote=true; Thread stopSoon = new Thread(this); stopSoon.start(); } } public void testEnded() { remote = false; Thread stopSoon = new Thread(this); stopSoon.start(); } public synchronized void testStarted(String host) { started++; long now=System.currentTimeMillis(); log.info("Started remote host: " + host + " ("+now+")"); } public void testStarted() { long now=System.currentTimeMillis(); log.info(JMeterUtils.getResString("running_test")+" ("+now+")");//$NON-NLS-1$ } /** * This is a hack to allow listeners a chance to close their files. Must * implement a queue for sample responses tied to the engine, and the * engine won't deliver testEnded signal till all sample responses have * been delivered. Should also improve performance of remote JMeter * testing. */ public void run() { long now = System.currentTimeMillis(); println("Tidying up ... @ "+new Date(now)+" ("+now+")"); /* * Note: although it should not be necessary to call System.exit here, in the case * of a remote test, a Timer thread seems to be generated by the Naming.lookup() * method, and it does not die. */ if (remote){ try { Thread.sleep(5000); // Allow listeners to close files } catch (InterruptedException ignored) { } } println("... end of run"); if (remote){ System.exit(0); } } /** * @see TestListener#testIterationStart(LoopIterationEvent) */ public void testIterationStart(LoopIterationEvent event) { // ignored } } private static void println(String str) { System.out.println(str); } private static final String[][] DEFAULT_ICONS = { { "org.apache.jmeter.control.gui.TestPlanGui", "org/apache/jmeter/images/beaker.gif" }, //$NON-NLS-1$ $NON-NLS-2$ { "org.apache.jmeter.timers.gui.AbstractTimerGui", "org/apache/jmeter/images/timer.gif" }, //$NON-NLS-1$ $NON-NLS-2$ { "org.apache.jmeter.threads.gui.ThreadGroupGui", "org/apache/jmeter/images/thread.gif" }, //$NON-NLS-1$ $NON-NLS-2$ { "org.apache.jmeter.visualizers.gui.AbstractVisualizer", "org/apache/jmeter/images/meter.png" }, //$NON-NLS-1$ $NON-NLS-2$ { "org.apache.jmeter.config.gui.AbstractConfigGui", "org/apache/jmeter/images/testtubes.png" }, //$NON-NLS-1$ $NON-NLS-2$ { "org.apache.jmeter.processor.gui.AbstractPreProcessorGui", "org/apache/jmeter/images/leafnode.gif"}, //$NON-NLS-1$ $NON-NLS-2$ { "org.apache.jmeter.processor.gui.AbstractPostProcessorGui","org/apache/jmeter/images/leafnodeflip.gif"},//$NON-NLS-1$ $NON-NLS-2$ { "org.apache.jmeter.control.gui.AbstractControllerGui", "org/apache/jmeter/images/knob.gif" }, //$NON-NLS-1$ $NON-NLS-2$ { "org.apache.jmeter.control.gui.WorkBenchGui", "org/apache/jmeter/images/clipboard.gif" }, //$NON-NLS-1$ $NON-NLS-2$ { "org.apache.jmeter.samplers.gui.AbstractSamplerGui", "org/apache/jmeter/images/pipet.png" }, //$NON-NLS-1$ $NON-NLS-2$ { "org.apache.jmeter.assertions.gui.AbstractAssertionGui", "org/apache/jmeter/images/question.gif"} //$NON-NLS-1$ $NON-NLS-2$ }; public String[][] getIconMappings() { final String defaultIconProp = "org/apache/jmeter/images/icon.properties"; //$NON-NLS-1$ String iconProp = JMeterUtils.getPropDefault("jmeter.icons", defaultIconProp);//$NON-NLS-1$ Properties p = JMeterUtils.loadProperties(iconProp); if (p == null && !iconProp.equals(defaultIconProp)) { log.info(iconProp + " not found - using " + defaultIconProp); iconProp = defaultIconProp; p = JMeterUtils.loadProperties(iconProp); } if (p == null) { log.info(iconProp + " not found - using inbuilt icon set"); return DEFAULT_ICONS; } log.info("Loaded icon properties from " + iconProp); String[][] iconlist = new String[p.size()][3]; Enumeration pe = p.keys(); int i = 0; while (pe.hasMoreElements()) { String key = (String) pe.nextElement(); String icons[] = JOrphanUtils.split(p.getProperty(key), " ");//$NON-NLS-1$ iconlist[i][0] = key; iconlist[i][1] = icons[0]; if (icons.length > 1) iconlist[i][2] = icons[1]; i++; } return iconlist; } public String[][] getResourceBundles() { return new String[0][]; } private void logProperty(String prop){ log.info(prop+"="+System.getProperty(prop));//$NON-NLS-1$ } private void logProperty(String prop,String separator){ log.info(prop+separator+System.getProperty(prop));//$NON-NLS-1$ } }
src/core/org/apache/jmeter/JMeter.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.jmeter; import java.awt.event.ActionEvent; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.net.Authenticator; import java.net.MalformedURLException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Enumeration; import java.util.Collection; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.Properties; import java.util.StringTokenizer; import javax.swing.JLabel; import org.apache.commons.cli.avalon.CLArgsParser; import org.apache.commons.cli.avalon.CLOption; import org.apache.commons.cli.avalon.CLOptionDescriptor; import org.apache.commons.cli.avalon.CLUtil; import org.apache.jmeter.control.ReplaceableController; import org.apache.jmeter.engine.ClientJMeterEngine; import org.apache.jmeter.engine.JMeterEngine; import org.apache.jmeter.engine.RemoteJMeterEngineImpl; import org.apache.jmeter.engine.StandardJMeterEngine; import org.apache.jmeter.engine.event.LoopIterationEvent; import org.apache.jmeter.exceptions.IllegalUserActionException; import org.apache.jmeter.gui.GuiPackage; import org.apache.jmeter.gui.action.ActionNames; import org.apache.jmeter.gui.action.ActionRouter; import org.apache.jmeter.gui.action.Load; import org.apache.jmeter.gui.tree.JMeterTreeListener; import org.apache.jmeter.gui.tree.JMeterTreeNode; import org.apache.jmeter.gui.tree.JMeterTreeModel; import org.apache.jmeter.plugin.JMeterPlugin; import org.apache.jmeter.plugin.PluginManager; import org.apache.jmeter.reporters.ResultCollector; import org.apache.jmeter.reporters.Summariser; import org.apache.jmeter.samplers.Remoteable; import org.apache.jmeter.save.SaveService; import org.apache.jmeter.services.FileServer; import org.apache.jmeter.testelement.TestElement; import org.apache.jmeter.testelement.TestListener; import org.apache.jmeter.util.BeanShellInterpreter; import org.apache.jmeter.util.BeanShellServer; import org.apache.jmeter.util.JMeterUtils; import org.apache.jorphan.collections.HashTree; import org.apache.jorphan.gui.ComponentUtil; import org.apache.jorphan.logging.LoggingManager; import org.apache.jorphan.collections.SearchByClass; import org.apache.jorphan.reflect.ClassTools; import org.apache.jorphan.util.JMeterException; import org.apache.jorphan.util.JOrphanUtils; import org.apache.log.Logger; import com.thoughtworks.xstream.converters.ConversionException; /** * @author mstover */ public class JMeter implements JMeterPlugin { private static final Logger log = LoggingManager.getLoggerForClass(); public static final String HTTP_PROXY_PASS = "http.proxyPass"; // $NON-NLS-1$ public static final String HTTP_PROXY_USER = "http.proxyUser"; // $NON-NLS-1$ private static final int PROXY_PASSWORD = 'a';// $NON-NLS-1$ private static final int JMETER_HOME_OPT = 'd';// $NON-NLS-1$ private static final int HELP_OPT = 'h';// $NON-NLS-1$ // jmeter.log private static final int JMLOGFILE_OPT = 'j';// $NON-NLS-1$ // sample result log file private static final int LOGFILE_OPT = 'l';// $NON-NLS-1$ private static final int NONGUI_OPT = 'n';// $NON-NLS-1$ private static final int PROPFILE_OPT = 'p';// $NON-NLS-1$ private static final int PROPFILE2_OPT = 'q';// $NON-NLS-1$ private static final int REMOTE_OPT = 'r';// $NON-NLS-1$ private static final int SERVER_OPT = 's';// $NON-NLS-1$ private static final int TESTFILE_OPT = 't';// $NON-NLS-1$ private static final int PROXY_USERNAME = 'u';// $NON-NLS-1$ private static final int VERSION_OPT = 'v';// $NON-NLS-1$ private static final int SYSTEM_PROPERTY = 'D';// $NON-NLS-1$ private static final int PROXY_HOST = 'H';// $NON-NLS-1$ private static final int JMETER_PROPERTY = 'J';// $NON-NLS-1$ private static final int LOGLEVEL = 'L';// $NON-NLS-1$ private static final int NONPROXY_HOSTS = 'N';// $NON-NLS-1$ private static final int PROXY_PORT = 'P';// $NON-NLS-1$ private static final int REMOTE_OPT_PARAM = 'R';// $NON-NLS-1$ private static final int SYSTEM_PROPFILE = 'S';// $NON-NLS-1$ /** * Define the understood options. Each CLOptionDescriptor contains: * <ul> * <li>The "long" version of the option. Eg, "help" means that "--help" * will be recognised.</li> * <li>The option flags, governing the option's argument(s).</li> * <li>The "short" version of the option. Eg, 'h' means that "-h" will be * recognised.</li> * <li>A description of the option.</li> * </ul> */ private static final CLOptionDescriptor[] options = new CLOptionDescriptor[] { new CLOptionDescriptor("help", CLOptionDescriptor.ARGUMENT_DISALLOWED, HELP_OPT, "print usage information and exit"), new CLOptionDescriptor("version", CLOptionDescriptor.ARGUMENT_DISALLOWED, VERSION_OPT, "print the version information and exit"), new CLOptionDescriptor("propfile", CLOptionDescriptor.ARGUMENT_REQUIRED, PROPFILE_OPT, "the jmeter property file to use"), new CLOptionDescriptor("addprop", CLOptionDescriptor.ARGUMENT_REQUIRED | CLOptionDescriptor.DUPLICATES_ALLOWED, PROPFILE2_OPT, "additional JMeter property file(s)"), new CLOptionDescriptor("testfile", CLOptionDescriptor.ARGUMENT_REQUIRED, TESTFILE_OPT, "the jmeter test(.jmx) file to run"), new CLOptionDescriptor("logfile", CLOptionDescriptor.ARGUMENT_REQUIRED, LOGFILE_OPT, "the file to log samples to"), new CLOptionDescriptor("jmeterlogfile", CLOptionDescriptor.ARGUMENT_REQUIRED, JMLOGFILE_OPT, "jmeter run log file (jmeter.log)"), new CLOptionDescriptor("nongui", CLOptionDescriptor.ARGUMENT_DISALLOWED, NONGUI_OPT, "run JMeter in nongui mode"), new CLOptionDescriptor("server", CLOptionDescriptor.ARGUMENT_DISALLOWED, SERVER_OPT, "run the JMeter server"), new CLOptionDescriptor("proxyHost", CLOptionDescriptor.ARGUMENT_REQUIRED, PROXY_HOST, "Set a proxy server for JMeter to use"), new CLOptionDescriptor("proxyPort", CLOptionDescriptor.ARGUMENT_REQUIRED, PROXY_PORT, "Set proxy server port for JMeter to use"), new CLOptionDescriptor("nonProxyHosts", CLOptionDescriptor.ARGUMENT_REQUIRED, NONPROXY_HOSTS, "Set nonproxy host list (e.g. *.apache.org|localhost)"), new CLOptionDescriptor("username", CLOptionDescriptor.ARGUMENT_REQUIRED, PROXY_USERNAME, "Set username for proxy server that JMeter is to use"), new CLOptionDescriptor("password", CLOptionDescriptor.ARGUMENT_REQUIRED, PROXY_PASSWORD, "Set password for proxy server that JMeter is to use"), new CLOptionDescriptor("jmeterproperty", CLOptionDescriptor.DUPLICATES_ALLOWED | CLOptionDescriptor.ARGUMENTS_REQUIRED_2, JMETER_PROPERTY, "Define additional JMeter properties"), new CLOptionDescriptor("systemproperty", CLOptionDescriptor.DUPLICATES_ALLOWED | CLOptionDescriptor.ARGUMENTS_REQUIRED_2, SYSTEM_PROPERTY, "Define additional system properties"), new CLOptionDescriptor("systemPropertyFile", CLOptionDescriptor.DUPLICATES_ALLOWED | CLOptionDescriptor.ARGUMENT_REQUIRED, SYSTEM_PROPFILE, "additional system property file(s)"), new CLOptionDescriptor("loglevel", CLOptionDescriptor.DUPLICATES_ALLOWED | CLOptionDescriptor.ARGUMENTS_REQUIRED_2, LOGLEVEL, "[category=]level e.g. jorphan=INFO or jmeter.util=DEBUG"), new CLOptionDescriptor("runremote", CLOptionDescriptor.ARGUMENT_DISALLOWED, REMOTE_OPT, "Start remote servers (as defined in remote_hosts)"), new CLOptionDescriptor("remotestart", CLOptionDescriptor.ARGUMENT_REQUIRED, REMOTE_OPT_PARAM, "Start these remote servers (overrides remote_hosts)"), new CLOptionDescriptor("homedir", CLOptionDescriptor.ARGUMENT_REQUIRED, JMETER_HOME_OPT, "the jmeter home directory to use"), }; public JMeter() { } // Hack to allow automated tests to find when test has ended //transient boolean testEnded = false; private JMeter parent; /** * Starts up JMeter in GUI mode */ private void startGui(CLOption testFile) { PluginManager.install(this, true); JMeterTreeModel treeModel = new JMeterTreeModel(); JMeterTreeListener treeLis = new JMeterTreeListener(treeModel); treeLis.setActionHandler(ActionRouter.getInstance()); // NOTUSED: GuiPackage guiPack = GuiPackage.getInstance(treeLis, treeModel); org.apache.jmeter.gui.MainFrame main = new org.apache.jmeter.gui.MainFrame(ActionRouter.getInstance(), treeModel, treeLis); // TODO - set up these items in MainFrame? main.setTitle("Apache JMeter ("+JMeterUtils.getJMeterVersion()+")");// $NON-NLS-1$ main.setIconImage(JMeterUtils.getImage("jmeter.jpg").getImage());// $NON-NLS-1$ ComponentUtil.centerComponentInWindow(main, 80); main.show(); ActionRouter.getInstance().actionPerformed(new ActionEvent(main, 1, ActionNames.ADD_ALL)); String arg; if (testFile != null && (arg = testFile.getArgument()) != null) { FileInputStream reader = null; try { File f = new File(arg); log.info("Loading file: " + f); reader = new FileInputStream(f); HashTree tree = SaveService.loadTree(reader); GuiPackage.getInstance().setTestPlanFile(f.getAbsolutePath()); Load.insertLoadedTree(1, tree); } catch (ConversionException e) { log.error("Failure loading test file", e); JMeterUtils.reportErrorToUser(SaveService.CEtoString(e)); } catch (Exception e) { log.error("Failure loading test file", e); JMeterUtils.reportErrorToUser(e.toString()); } finally { JOrphanUtils.closeQuietly(reader); } } } /** * Takes the command line arguments and uses them to determine how to * startup JMeter. */ public void start(String[] args) { CLArgsParser parser = new CLArgsParser(args, options); if (null != parser.getErrorString()) { System.err.println("Error: " + parser.getErrorString()); System.out.println("Usage"); System.out.println(CLUtil.describeOptions(options).toString()); return; } try { initializeProperties(parser); // Also initialises JMeter logging /* * The following is needed for HTTPClient. * (originally tried doing this in HTTPSampler2, * but it appears that it was done too late when running in GUI mode) * Set the commons logging default to Avalon Logkit, if not already defined */ if (System.getProperty("org.apache.commons.logging.Log") == null) { // $NON-NLS-1$ System.setProperty("org.apache.commons.logging.Log" // $NON-NLS-1$ , "org.apache.commons.logging.impl.LogKitLogger"); // $NON-NLS-1$ } log.info(JMeterUtils.getJMeterCopyright()); log.info("Version " + JMeterUtils.getJMeterVersion()); logProperty("java.version"); //$NON-NLS-1$ logProperty("os.name"); //$NON-NLS-1$ logProperty("os.arch"); //$NON-NLS-1$ logProperty("os.version"); //$NON-NLS-1$ logProperty("file.encoding"); // $NON-NLS-1$ log.info("Default Locale=" + Locale.getDefault().getDisplayName());// $NON-NLS-1$ log.info("JMeter Locale=" + JMeterUtils.getLocale().getDisplayName());// $NON-NLS-1$ log.info("JMeterHome=" + JMeterUtils.getJMeterHome());// $NON-NLS-1$ logProperty("user.dir"," ="); //$NON-NLS-1$ log.info("PWD ="+new File(".").getCanonicalPath());//$NON-NLS-1$ setProxy(parser); updateClassLoader(); if (log.isDebugEnabled()) { String jcp=System.getProperty("java.class.path");// $NON-NLS-1$ String bits[] =jcp.split(File.pathSeparator); log.debug("ClassPath"); for(int i = 0; i<bits.length ;i++){ log.debug(bits[i]); } log.debug(jcp); } // Set some (hopefully!) useful properties long now=System.currentTimeMillis(); JMeterUtils.setProperty("START.MS",Long.toString(now)); Date today=new Date(now); // so it agrees with above // TODO perhaps should share code with __time() function for this... JMeterUtils.setProperty("START.YMD",new SimpleDateFormat("yyyyMMdd").format(today)); JMeterUtils.setProperty("START.HMS",new SimpleDateFormat("HHmmss").format(today)); if (parser.getArgumentById(VERSION_OPT) != null) { System.out.println(JMeterUtils.getJMeterCopyright()); System.out.println("Version " + JMeterUtils.getJMeterVersion()); } else if (parser.getArgumentById(HELP_OPT) != null) { System.out.println(JMeterUtils.getResourceFileAsText("org/apache/jmeter/help.txt"));// $NON-NLS-1$ } else if (parser.getArgumentById(SERVER_OPT) != null) { // We need to check if the JMeter home contains spaces in the path, // because then we will not be able to bind to RMI registry, see // Java bug id 4496398 final String jmHome = JMeterUtils.getJMeterHome(); if(jmHome.indexOf(" ") > -1) {// $NON-NLS-1$ // Just warn user, and exit, no reason to continue, since we will // not be able to bind to RMI registry, until Java bug 4496398 is fixed log.error("JMeter path cannot contain spaces when run in server mode : " + jmHome); throw new RuntimeException("JMeter path cannot contain spaces when run in server mode: "+jmHome); } // Start the server startServer(JMeterUtils.getPropDefault("server_port", 0));// $NON-NLS-1$ startOptionalServers(); } else if (parser.getArgumentById(NONGUI_OPT) == null) { startGui(parser.getArgumentById(TESTFILE_OPT)); startOptionalServers(); } else { CLOption rem=parser.getArgumentById(REMOTE_OPT_PARAM); if (rem==null) rem=parser.getArgumentById(REMOTE_OPT); startNonGui(parser.getArgumentById(TESTFILE_OPT), parser.getArgumentById(LOGFILE_OPT), rem); startOptionalServers(); } } catch (IllegalUserActionException e) { System.out.println(e.getMessage()); System.out.println("Incorrect Usage"); System.out.println(CLUtil.describeOptions(options).toString()); } catch (Throwable e) { if (log != null){ log.fatalError("An error occurred: ",e); } else { e.printStackTrace(); } System.out.println("An error occurred: " + e.getMessage()); System.exit(1); } } // Update classloader if necessary private void updateClassLoader() { updatePath("search_paths",";"); //$NON-NLS-1$//$NON-NLS-2$ updatePath("user.classpath",File.pathSeparator);//$NON-NLS-1$ } private void updatePath(String property, String sep) { String userpath= JMeterUtils.getPropDefault(property,"");// $NON-NLS-1$ if (userpath.length() <= 0) return; log.info(property+"="+userpath); //$NON-NLS-1$ StringTokenizer tok = new StringTokenizer(userpath, sep); while(tok.hasMoreTokens()) { String path=tok.nextToken(); File f=new File(path); if (!f.canRead() && !f.isDirectory()) { log.warn("Can't read "+path); } else { log.info("Adding to classpath: "+path); try { NewDriver.addPath(path); } catch (MalformedURLException e) { log.warn("Error adding: "+path+" "+e.getLocalizedMessage()); } } } } /** * */ private void startOptionalServers() { int bshport = JMeterUtils.getPropDefault("beanshell.server.port", 0);// $NON-NLS-1$ String bshfile = JMeterUtils.getPropDefault("beanshell.server.file", "");// $NON-NLS-1$ $NON-NLS-2$ if (bshport > 0) { log.info("Starting Beanshell server (" + bshport + "," + bshfile + ")"); Runnable t = new BeanShellServer(bshport, bshfile); t.run(); } // Should we run a beanshell script on startup? String bshinit = JMeterUtils.getProperty("beanshell.init.file");// $NON-NLS-1$ if (bshinit != null){ log.info("Run Beanshell on file: "+bshinit); try { BeanShellInterpreter bsi = new BeanShellInterpreter();//bshinit,log); bsi.source(bshinit); } catch (ClassNotFoundException e) { log.warn("Could not start Beanshell: "+e.getLocalizedMessage()); } catch (JMeterException e) { log.warn("Could not process Beanshell file: "+e.getLocalizedMessage()); } } int mirrorPort=JMeterUtils.getPropDefault("mirror.server.port", 0);// $NON-NLS-1$ if (mirrorPort > 0){ log.info("Starting Mirror server (" + mirrorPort + ")"); try { Object instance = ClassTools.construct( "org.apache.jmeter.protocol.http.control.HttpMirrorControl",// $NON-NLS-1$ mirrorPort); ClassTools.invoke(instance,"startHttpMirror"); } catch (JMeterException e) { log.warn("Could not start Mirror server",e); } } } /** * Sets a proxy server for the JVM if the command line arguments are * specified. */ private void setProxy(CLArgsParser parser) throws IllegalUserActionException { if (parser.getArgumentById(PROXY_USERNAME) != null) { Properties jmeterProps = JMeterUtils.getJMeterProperties(); if (parser.getArgumentById(PROXY_PASSWORD) != null) { String u, p; Authenticator.setDefault(new ProxyAuthenticator(u = parser.getArgumentById(PROXY_USERNAME) .getArgument(), p = parser.getArgumentById(PROXY_PASSWORD).getArgument())); log.info("Set Proxy login: " + u + "/" + p); jmeterProps.setProperty(HTTP_PROXY_USER, u);//for Httpclient jmeterProps.setProperty(HTTP_PROXY_PASS, p);//for Httpclient } else { String u; Authenticator.setDefault(new ProxyAuthenticator(u = parser.getArgumentById(PROXY_USERNAME) .getArgument(), "")); log.info("Set Proxy login: " + u); jmeterProps.setProperty(HTTP_PROXY_USER, u); } } if (parser.getArgumentById(PROXY_HOST) != null && parser.getArgumentById(PROXY_PORT) != null) { String h = parser.getArgumentById(PROXY_HOST).getArgument(); String p = parser.getArgumentById(PROXY_PORT).getArgument(); System.setProperty("http.proxyHost", h );// $NON-NLS-1$ System.setProperty("https.proxyHost", h);// $NON-NLS-1$ System.setProperty("http.proxyPort", p);// $NON-NLS-1$ System.setProperty("https.proxyPort", p);// $NON-NLS-1$ log.info("Set http[s].proxyHost: " + h + " Port: " + p); } else if (parser.getArgumentById(PROXY_HOST) != null || parser.getArgumentById(PROXY_PORT) != null) { throw new IllegalUserActionException(JMeterUtils.getResString("proxy_cl_error"));// $NON-NLS-1$ } if (parser.getArgumentById(NONPROXY_HOSTS) != null) { String n = parser.getArgumentById(NONPROXY_HOSTS).getArgument(); System.setProperty("http.nonProxyHosts", n );// $NON-NLS-1$ System.setProperty("https.nonProxyHosts", n );// $NON-NLS-1$ log.info("Set http[s].nonProxyHosts: "+n); } } private void initializeProperties(CLArgsParser parser) { if (parser.getArgumentById(PROPFILE_OPT) != null) { JMeterUtils.loadJMeterProperties(parser.getArgumentById(PROPFILE_OPT).getArgument()); } else { JMeterUtils.loadJMeterProperties(NewDriver.getJMeterDir() + File.separator + "bin" + File.separator // $NON-NLS-1$ + "jmeter.properties");// $NON-NLS-1$ } if (parser.getArgumentById(JMLOGFILE_OPT) != null){ String jmlogfile=parser.getArgumentById(JMLOGFILE_OPT).getArgument(); JMeterUtils.setProperty(LoggingManager.LOG_FILE,jmlogfile); } JMeterUtils.initLogging(); JMeterUtils.initLocale(); // Bug 33845 - allow direct override of Home dir if (parser.getArgumentById(JMETER_HOME_OPT) == null) { JMeterUtils.setJMeterHome(NewDriver.getJMeterDir()); } else { JMeterUtils.setJMeterHome(parser.getArgumentById(JMETER_HOME_OPT).getArgument()); } Properties jmeterProps = JMeterUtils.getJMeterProperties(); // Add local JMeter properties, if the file is found String userProp = JMeterUtils.getPropDefault("user.properties",""); //$NON-NLS-1$ if (userProp.length() > 0){ //$NON-NLS-1$ FileInputStream fis=null; try { File file = JMeterUtils.findFile(userProp); if (file.canRead()){ log.info("Loading user properties from: "+file.getCanonicalPath()); fis = new FileInputStream(file); Properties tmp = new Properties(); tmp.load(fis); jmeterProps.putAll(tmp); LoggingManager.setLoggingLevels(tmp);//Do what would be done earlier } } catch (IOException e) { log.warn("Error loading user property file: " + userProp, e); } finally { JOrphanUtils.closeQuietly(fis); } } // Add local system properties, if the file is found String sysProp = JMeterUtils.getPropDefault("system.properties",""); //$NON-NLS-1$ if (sysProp.length() > 0){ FileInputStream fis=null; try { File file = JMeterUtils.findFile(sysProp); if (file.canRead()){ log.info("Loading system properties from: "+file.getCanonicalPath()); fis = new FileInputStream(file); System.getProperties().load(fis); } } catch (IOException e) { log.warn("Error loading system property file: " + sysProp, e); } finally { JOrphanUtils.closeQuietly(fis); } } // Process command line property definitions // These can potentially occur multiple times List clOptions = parser.getArguments(); int size = clOptions.size(); for (int i = 0; i < size; i++) { CLOption option = (CLOption) clOptions.get(i); String name = option.getArgument(0); String value = option.getArgument(1); FileInputStream fis = null; switch (option.getDescriptor().getId()) { // Should not have any text arguments case CLOption.TEXT_ARGUMENT: throw new IllegalArgumentException("Unknown arg: "+option.getArgument()); case PROPFILE2_OPT: // Bug 33920 - allow multiple props try { fis = new FileInputStream(new File(name)); Properties tmp = new Properties(); tmp.load(fis); jmeterProps.putAll(tmp); LoggingManager.setLoggingLevels(tmp);//Do what would be done earlier } catch (FileNotFoundException e) { log.warn("Can't find additional property file: " + name, e); } catch (IOException e) { log.warn("Error loading additional property file: " + name, e); } finally { JOrphanUtils.closeQuietly(fis); } break; case SYSTEM_PROPFILE: log.info("Setting System properties from file: " + name); try { fis = new FileInputStream(new File(name)); System.getProperties().load(fis); } catch (IOException e) { log.warn("Cannot find system property file "+e.getLocalizedMessage()); } finally { JOrphanUtils.closeQuietly(fis); } break; case SYSTEM_PROPERTY: if (value.length() > 0) { // Set it log.info("Setting System property: " + name + "=" + value); System.getProperties().setProperty(name, value); } else { // Reset it log.warn("Removing System property: " + name); System.getProperties().remove(name); } break; case JMETER_PROPERTY: if (value.length() > 0) { // Set it log.info("Setting JMeter property: " + name + "=" + value); jmeterProps.setProperty(name, value); } else { // Reset it log.warn("Removing JMeter property: " + name); jmeterProps.remove(name); } break; case LOGLEVEL: if (value.length() > 0) { // Set category log.info("LogLevel: " + name + "=" + value); LoggingManager.setPriority(value, name); } else { // Set root level log.warn("LogLevel: " + name); LoggingManager.setPriority(name); } break; } } } private void startServer(int port) { try { new RemoteJMeterEngineImpl(port); } catch (Exception ex) { log.error("Giving up, as server failed with:", ex); System.err.println("Server failed to start: "+ex); System.exit(1);// Give up } } private void startNonGui(CLOption testFile, CLOption logFile, CLOption remoteStart) throws IllegalUserActionException { // add a system property so samplers can check to see if JMeter // is running in NonGui mode System.setProperty("JMeter.NonGui", "true");// $NON-NLS-1$ // Force the X11 display to be checked try { new JLabel(); } catch (InternalError e){ // ignored } JMeter driver = new JMeter(); driver.parent = this; PluginManager.install(this, false); String remote_hosts_string = null; if (remoteStart != null) { remote_hosts_string = remoteStart.getArgument(); if (remote_hosts_string == null) { remote_hosts_string = JMeterUtils.getPropDefault( "remote_hosts", //$NON-NLS-1$ "127.0.0.1");//$NON-NLS-1$ } } if (testFile == null) { throw new IllegalUserActionException(); } String argument = testFile.getArgument(); if (argument == null) { throw new IllegalUserActionException(); } if (logFile == null) { driver.run(argument, null, remoteStart != null,remote_hosts_string); } else { driver.run(argument, logFile.getArgument(), remoteStart != null,remote_hosts_string); } } // run test in batch mode private void run(String testFile, String logFile, boolean remoteStart, String remote_hosts_string) { FileInputStream reader = null; try { File f = new File(testFile); if (!f.exists() || !f.isFile()) { println("Could not open " + testFile); return; } FileServer.getFileServer().setBasedir(f.getAbsolutePath()); reader = new FileInputStream(f); log.info("Loading file: " + f); HashTree tree = SaveService.loadTree(reader); JMeterTreeModel treeModel = new JMeterTreeModel(new Object());// Create non-GUI version to avoid headless problems JMeterTreeNode root = (JMeterTreeNode) treeModel.getRoot(); treeModel.addSubTree(tree, root); // Hack to resolve ModuleControllers in non GUI mode SearchByClass replaceableControllers = new SearchByClass(ReplaceableController.class); tree.traverse(replaceableControllers); Collection replaceableControllersRes = replaceableControllers.getSearchResults(); for (Iterator iter = replaceableControllersRes.iterator(); iter.hasNext();) { ReplaceableController replaceableController = (ReplaceableController) iter.next(); replaceableController.resolveReplacementSubTree(root); } // Remove the disabled items // For GUI runs this is done in Start.java convertSubTree(tree); if (logFile != null) { ResultCollector logger = new ResultCollector(); logger.setFilename(logFile); tree.add(tree.getArray()[0], logger); } String summariserName = JMeterUtils.getPropDefault("summariser.name", "");//$NON-NLS-1$ if (summariserName.length() > 0) { log.info("Creating summariser <" + summariserName + ">"); println("Creating summariser <" + summariserName + ">"); Summariser summer = new Summariser(summariserName); tree.add(tree.getArray()[0], summer); } tree.add(tree.getArray()[0], new ListenToTest(parent)); println("Created the tree successfully"); JMeterEngine engine = null; if (!remoteStart) { engine = new StandardJMeterEngine(); engine.configure(tree); long now=System.currentTimeMillis(); println("Starting the test @ "+new Date(now)+" ("+now+")"); engine.runTest(); } else { java.util.StringTokenizer st = new java.util.StringTokenizer(remote_hosts_string, ",");//$NON-NLS-1$ List engines = new LinkedList(); while (st.hasMoreElements()) { String el = (String) st.nextElement(); println("Configuring remote engine for " + el); engines.add(doRemoteInit(el.trim(), tree)); } println("Starting remote engines"); long now=System.currentTimeMillis(); println("Starting the test @ "+new Date(now)+" ("+now+")"); Iterator iter = engines.iterator(); while (iter.hasNext()) { engine = (JMeterEngine) iter.next(); engine.runTest(); } println("Remote engines have been started"); } } catch (Exception e) { System.out.println("Error in NonGUIDriver " + e.toString()); log.error("", e); } finally { JOrphanUtils.closeQuietly(reader); } } /** * Refactored from AbstractAction.java * * @param tree */ public static void convertSubTree(HashTree tree) { Iterator iter = new LinkedList(tree.list()).iterator(); while (iter.hasNext()) { Object o = iter.next(); if (o instanceof TestElement) { TestElement item = (TestElement) o; if (item.isEnabled()) { if (item instanceof ReplaceableController) { // HACK: force the controller to load its tree ReplaceableController rc = (ReplaceableController) item .clone(); HashTree subTree = tree.getTree(item); if (subTree != null) { HashTree replacementTree = rc .getReplacementSubTree(); if (replacementTree != null) { convertSubTree(replacementTree); tree.replace(item, rc); tree.set(rc, replacementTree); } } else { convertSubTree(tree.getTree(item)); } } else { convertSubTree(tree.getTree(item)); } } else tree.remove(item); } else { JMeterTreeNode item = (JMeterTreeNode) o; if (item.isEnabled()) { // Replacement only needs to occur when starting the engine // @see StandardJMeterEngine.run() if (item.getUserObject() instanceof ReplaceableController) { ReplaceableController rc = (ReplaceableController) item .getTestElement(); HashTree subTree = tree.getTree(item); if (subTree != null) { HashTree replacementTree = rc .getReplacementSubTree(); if (replacementTree != null) { convertSubTree(replacementTree); tree.replace(item, rc); tree.set(rc, replacementTree); } } } else { convertSubTree(tree.getTree(item)); TestElement testElement = item.getTestElement(); tree.replace(item, testElement); } } else { tree.remove(item); } } } } private JMeterEngine doRemoteInit(String hostName, HashTree testTree) { JMeterEngine engine = null; try { engine = new ClientJMeterEngine(hostName); } catch (Exception e) { log.fatalError("Failure connecting to remote host", e); System.exit(1); } engine.configure(testTree); return engine; } /* * Listen to test and handle tidyup after non-GUI test completes. * If running a remote test, then after waiting a few seconds for listeners to finish files, * it calls System.exit to deal with the Naming Timer Thread. */ private static class ListenToTest implements TestListener, Runnable, Remoteable { private int started = 0; // keep track of remote tests private boolean remote = false; // Are we running a remote test? //NOT YET USED private JMeter _parent; private ListenToTest(JMeter parent) { //_parent = parent; } public synchronized void testEnded(String host) { started--; long now=System.currentTimeMillis(); log.info("Finished remote host: " + host + " ("+now+")"); if (started <= 0) { remote=true; Thread stopSoon = new Thread(this); stopSoon.start(); } } public void testEnded() { remote = false; Thread stopSoon = new Thread(this); stopSoon.start(); } public synchronized void testStarted(String host) { started++; long now=System.currentTimeMillis(); log.info("Started remote host: " + host + " ("+now+")"); } public void testStarted() { long now=System.currentTimeMillis(); log.info(JMeterUtils.getResString("running_test")+" ("+now+")");//$NON-NLS-1$ } /** * This is a hack to allow listeners a chance to close their files. Must * implement a queue for sample responses tied to the engine, and the * engine won't deliver testEnded signal till all sample responses have * been delivered. Should also improve performance of remote JMeter * testing. */ public void run() { long now = System.currentTimeMillis(); println("Tidying up ... @ "+new Date(now)+" ("+now+")"); /* * Note: although it should not be necessary to call System.exit here, in the case * of a remote test, a Timer thread seems to be generated by the Naming.lookup() * method, and it does not die. */ if (remote){ try { Thread.sleep(5000); // Allow listeners to close files } catch (InterruptedException ignored) { } } println("... end of run"); if (remote){ System.exit(0); } } /** * @see TestListener#testIterationStart(LoopIterationEvent) */ public void testIterationStart(LoopIterationEvent event) { // ignored } } private static void println(String str) { System.out.println(str); } private static final String[][] DEFAULT_ICONS = { { "org.apache.jmeter.control.gui.TestPlanGui", "org/apache/jmeter/images/beaker.gif" }, //$NON-NLS-1$ $NON-NLS-2$ { "org.apache.jmeter.timers.gui.AbstractTimerGui", "org/apache/jmeter/images/timer.gif" }, //$NON-NLS-1$ $NON-NLS-2$ { "org.apache.jmeter.threads.gui.ThreadGroupGui", "org/apache/jmeter/images/thread.gif" }, //$NON-NLS-1$ $NON-NLS-2$ { "org.apache.jmeter.visualizers.gui.AbstractVisualizer", "org/apache/jmeter/images/meter.png" }, //$NON-NLS-1$ $NON-NLS-2$ { "org.apache.jmeter.config.gui.AbstractConfigGui", "org/apache/jmeter/images/testtubes.png" }, //$NON-NLS-1$ $NON-NLS-2$ { "org.apache.jmeter.processor.gui.AbstractPreProcessorGui", "org/apache/jmeter/images/leafnode.gif"}, //$NON-NLS-1$ $NON-NLS-2$ { "org.apache.jmeter.processor.gui.AbstractPostProcessorGui","org/apache/jmeter/images/leafnodeflip.gif"},//$NON-NLS-1$ $NON-NLS-2$ { "org.apache.jmeter.control.gui.AbstractControllerGui", "org/apache/jmeter/images/knob.gif" }, //$NON-NLS-1$ $NON-NLS-2$ { "org.apache.jmeter.control.gui.WorkBenchGui", "org/apache/jmeter/images/clipboard.gif" }, //$NON-NLS-1$ $NON-NLS-2$ { "org.apache.jmeter.samplers.gui.AbstractSamplerGui", "org/apache/jmeter/images/pipet.png" }, //$NON-NLS-1$ $NON-NLS-2$ { "org.apache.jmeter.assertions.gui.AbstractAssertionGui", "org/apache/jmeter/images/question.gif"} //$NON-NLS-1$ $NON-NLS-2$ }; public String[][] getIconMappings() { final String defaultIconProp = "org/apache/jmeter/images/icon.properties"; //$NON-NLS-1$ String iconProp = JMeterUtils.getPropDefault("jmeter.icons", defaultIconProp);//$NON-NLS-1$ Properties p = JMeterUtils.loadProperties(iconProp); if (p == null && !iconProp.equals(defaultIconProp)) { log.info(iconProp + " not found - using " + defaultIconProp); iconProp = defaultIconProp; p = JMeterUtils.loadProperties(iconProp); } if (p == null) { log.info(iconProp + " not found - using inbuilt icon set"); return DEFAULT_ICONS; } log.info("Loaded icon properties from " + iconProp); String[][] iconlist = new String[p.size()][3]; Enumeration pe = p.keys(); int i = 0; while (pe.hasMoreElements()) { String key = (String) pe.nextElement(); String icons[] = JOrphanUtils.split(p.getProperty(key), " ");//$NON-NLS-1$ iconlist[i][0] = key; iconlist[i][1] = icons[0]; if (icons.length > 1) iconlist[i][2] = icons[1]; i++; } return iconlist; } public String[][] getResourceBundles() { return new String[0][]; } private void logProperty(String prop){ log.info(prop+"="+System.getProperty(prop));//$NON-NLS-1$ } private void logProperty(String prop,String separator){ log.info(prop+separator+System.getProperty(prop));//$NON-NLS-1$ } }
Report if cannot connect to remote server git-svn-id: 7c053b8fbd1fb5868f764c6f9536fc6a9bbe7da9@585635 13f79535-47bb-0310-9956-ffa450edef68
src/core/org/apache/jmeter/JMeter.java
Report if cannot connect to remote server
Java
bsd-3-clause
a83b0dd1f00e4de58b100577650cb77f65fcc0f1
0
TeamCohen/MinorThird,TeamCohen/MinorThird,TeamCohen/MinorThird,TeamCohen/MinorThird,TeamCohen/MinorThird
package edu.cmu.minorthird.util; /** Stores the version number as: <br> * <br> * Version # Format: Version#.Year.Month.Day <br> * <br> * Version History: * <hr> * <table border="0"> * <tr valign=top><td align="right">1.5.7.15</td> * <td align="left"> * - First Version to be checked in. <br> * - Recently added Mixup tokenization extras * </td></tr> * <tr valign=top><td align="right">2.5.8.9</td> * <td align="left">- Added multi label classification to text package * </td></tr> * <tr valign=top><td align="right">3.5.8.18</td> * <td align="left">- New Explanation Facilities * </td></tr> * <tr valign=top><td align="right">3.2.5.9.15</td> * <td align="left">Fixed Bugs:<br> * - createSpanProp <br> * - MaxEntLearner(CRFLearner)log space option: trainer ll (for large german dataset) <br> * - CascadingBinaryLearner macKappa changed from 0.0 t0 -1.0 <br> * - MultiClassifierAnnotator outputs _predicted_spanProp <br> * </td></tr> * <tr valign=top><td align="right">4.5.10.3</td> * <td align="left">- NEW GUI<br> * - other option for classifyCommandLineUtil<br> * - Fixed saving bug in classify package<br> * </td></tr> * <tr valign=top><td align="right">5.5.10.17</td> * <td align="left">- Fixed bug in GUI (PE doesn't pop up when TextField is entered) <br> * - Added TransformingMultiLearner and PredictedClassTransform for adding predicted class * names as features for multi label classification * </td></tr> * <tr valign=top><td align="right">5.2.5.10.27</td> * <td align="left">- a few gui fixes: help button fixes, showTestDetails automatic, DebugMixup, * and EditParams added to Selectable Types<br> * - Saving Extractor bug fixed<br> * - classify command line to gui -learner option consistency fixed<br> * </td></tr> * <tr valign=top><td align="right">6.5.11.30</td> * <td align="left">- More gui updates: shorted class names, links to tutorials, links to javadocs, more help buttons<br> * - more parameter bunches added to selectable types<br> * - Documentation added: Index and tutorial<br> * - Fixed cross option for TrainTestMultiClassifier - Tester.multiEvaluate, MultiCrossValidatedDataset<br> * </td></tr> * <tr valign=top><td align="right">6.2.5.12.8</td> * <td align="left">- Fixed MultiClassifier cross testing implementation<br> * - Fixed MultiClassifier explanation facilities<br> * - Added and updated documentation<br> * - Fixed SpanTypeTextBase to extract more than one span Type per document</br> * </td></tr> * <tr valign=top><td align="right">7.6.1.11</td> * <td align="left">- added demos/MyFE.java as an example<br> * - modified CommandLineUtil.newObjectFromBSH to allow bsh.source(file)<br> * - added PreprocessTextForClassifier, PreprocessTextForExtractor<br> * - added text.learn.BeginContinueOutsideReduction<br> * - updated selectableTypes as appropriate<br> * - fixed buggy implementation of span.getLoChar(), span.getHiChar()<br> * </td></tr> * <tr valign=top><td align="right">7.6.1.31</td> * <td align="left">- added main to SpanDifference<br> * - added mixup command 'annotateWith FILE'<br> * </td></tr> * <tr valign=top><td align="right">8.6.2.13</td> * <td align="left">- Changed createSpanProp to implement Mixup<br> * - fixed semiCRF saving bug<br> * - fixed DecisionTree Print<br> * - Updated MinorTagger and MinorTaggerClient to output labels format and run on velmak<br> * - Cleaned up commandLineUtil<br> * - Fixed bug in RefUtils<br> * </td></tr> * <tr valign=top><td align="right">8.6.3.15</td> * <td align="left">- cleaned up output in ProgressCounter<br> * - fixed some bugs in TextBaseLoader, for reading in text with XML labels<br> * - added ProgressCounter to TextBaseLoader for loading directories<br> * - made OneVsAllLearner work for Online learners<br> * </td></tr> * <tr valign=top><td align="right">9.6.4.19</td> * <td align="left">- NEW classify GUI<br> * - fixed bug in CRFLearner<br> * - New LevelManager and TexBaseMapper for handling multiple levels<br> * - importLabels taken out of TextBase<br> * - Encapsulated Annotator Loader fixed<br> * - Updated Documentation<br> * - Cammie's Last Day!<br> * </td></tr> * <tr valign=top><td align="right">10.6.10.12</td> * <td align="left">- Added confidence calculation capability to the SVM learner<br> * - Fixed encapsulated annotators so that they can require other encapsulated annotators.<br> * </td></tr> * <tr valign=top><td align="right">10.6.10.23</td> * <td align="left">- Fixed errors in MixupPrograms handling of regular expressions. * </td></tr> * <tr valign=top><td align="right">11.6.11.21</td> * <td align="left">- Initial version of extractor-confidence computation * </td></tr> * <tr valign=top><td align="right">11.6.11.22</td> * <td align="left"> - Better version of extractor-confidence computation, with BeamSearch modified appropriately * </td></tr> * <tr valign=top><td align="right">12.7.3.30</td> * <td align="left"> - Added support for a hierarchy of text bases and text labels that can be used in code or mixup<br> * <td align="left"> - Refactored the Tokenizer class to support multiple tokenization schemes<br> * <td align="left"> - Refactored the TextBase hierarchy to make the TextBase interface immutable with a mutable abstract * implementation defining the mutable functionality. <br> * <td align="left"> - Created a TextBaseManager class to manage text bases that are derived from each other.<br> * <td align="left"> - Added keywords to the mixup language to provide access to the TextBaseManager functionality.<br> * </td></tr> * <tr valign=top><td align="right">12.7.5.31</td> * <td align="left"> - Fixed bug where history size variable for certain learners was being ignored<br> * <td align="left"> - Added new Random Forests learners<br> * <td align="left"> - Fixed bugs that prevented compilation under java 1.6<br> * <td align="left"> - Switched the build mode from java 1.4 to java 1.5 in the ant build scripts<br> * <td align="left"> - Created new layout for documentation<br> * </td></tr> * <tr valign=top><td algin="right">13.7.10.8</td> * <td algin="left"> - Added visiolization of MINORTHIRD on LIBSVM.<br> * </td> * </tr> * </table> */ public class Version { private static String version = "Version 13.7.10.8"; public static String getVersion() { return version; } }
src/edu/cmu/minorthird/util/Version.java
package edu.cmu.minorthird.util; /** Stores the version number as: <br> * <br> * Version # Format: Version#.Year.Month.Day <br> * <br> * Version History: * <hr> * <table border="0"> * <tr valign=top><td align="right">1.5.7.15</td> * <td align="left"> * - First Version to be checked in. <br> * - Recently added Mixup tokenization extras * </td></tr> * <tr valign=top><td align="right">2.5.8.9</td> * <td align="left">- Added multi label classification to text package * </td></tr> * <tr valign=top><td align="right">3.5.8.18</td> * <td align="left">- New Explanation Facilities * </td></tr> * <tr valign=top><td align="right">3.2.5.9.15</td> * <td align="left">Fixed Bugs:<br> * - createSpanProp <br> * - MaxEntLearner(CRFLearner)log space option: trainer ll (for large german dataset) <br> * - CascadingBinaryLearner macKappa changed from 0.0 t0 -1.0 <br> * - MultiClassifierAnnotator outputs _predicted_spanProp <br> * </td></tr> * <tr valign=top><td align="right">4.5.10.3</td> * <td align="left">- NEW GUI<br> * - other option for classifyCommandLineUtil<br> * - Fixed saving bug in classify package<br> * </td></tr> * <tr valign=top><td align="right">5.5.10.17</td> * <td align="left">- Fixed bug in GUI (PE doesn't pop up when TextField is entered) <br> * - Added TransformingMultiLearner and PredictedClassTransform for adding predicted class * names as features for multi label classification * </td></tr> * <tr valign=top><td align="right">5.2.5.10.27</td> * <td align="left">- a few gui fixes: help button fixes, showTestDetails automatic, DebugMixup, * and EditParams added to Selectable Types<br> * - Saving Extractor bug fixed<br> * - classify command line to gui -learner option consistency fixed<br> * </td></tr> * <tr valign=top><td align="right">6.5.11.30</td> * <td align="left">- More gui updates: shorted class names, links to tutorials, links to javadocs, more help buttons<br> * - more parameter bunches added to selectable types<br> * - Documentation added: Index and tutorial<br> * - Fixed cross option for TrainTestMultiClassifier - Tester.multiEvaluate, MultiCrossValidatedDataset<br> * </td></tr> * <tr valign=top><td align="right">6.2.5.12.8</td> * <td align="left">- Fixed MultiClassifier cross testing implementation<br> * - Fixed MultiClassifier explanation facilities<br> * - Added and updated documentation<br> * - Fixed SpanTypeTextBase to extract more than one span Type per document</br> * </td></tr> * <tr valign=top><td align="right">7.6.1.11</td> * <td align="left">- added demos/MyFE.java as an example<br> * - modified CommandLineUtil.newObjectFromBSH to allow bsh.source(file)<br> * - added PreprocessTextForClassifier, PreprocessTextForExtractor<br> * - added text.learn.BeginContinueOutsideReduction<br> * - updated selectableTypes as appropriate<br> * - fixed buggy implementation of span.getLoChar(), span.getHiChar()<br> * </td></tr> * <tr valign=top><td align="right">7.6.1.31</td> * <td align="left">- added main to SpanDifference<br> * - added mixup command 'annotateWith FILE'<br> * </td></tr> * <tr valign=top><td align="right">8.6.2.13</td> * <td align="left">- Changed createSpanProp to implement Mixup<br> * - fixed semiCRF saving bug<br> * - fixed DecisionTree Print<br> * - Updated MinorTagger and MinorTaggerClient to output labels format and run on velmak<br> * - Cleaned up commandLineUtil<br> * - Fixed bug in RefUtils<br> * </td></tr> * <tr valign=top><td align="right">8.6.3.15</td> * <td align="left">- cleaned up output in ProgressCounter<br> * - fixed some bugs in TextBaseLoader, for reading in text with XML labels<br> * - added ProgressCounter to TextBaseLoader for loading directories<br> * - made OneVsAllLearner work for Online learners<br> * </td></tr> * <tr valign=top><td align="right">9.6.4.19</td> * <td align="left">- NEW classify GUI<br> * - fixed bug in CRFLearner<br> * - New LevelManager and TexBaseMapper for handling multiple levels<br> * - importLabels taken out of TextBase<br> * - Encapsulated Annotator Loader fixed<br> * - Updated Documentation<br> * - Cammie's Last Day!<br> * </td></tr> * <tr valign=top><td align="right">10.6.10.12</td> * <td align="left">- Added confidence calculation capability to the SVM learner<br> * - Fixed encapsulated annotators so that they can require other encapsulated annotators.<br> * </td></tr> * <tr valign=top><td align="right">10.6.10.23</td> * <td align="left">- Fixed errors in MixupPrograms handling of regular expressions. * </td></tr> * <tr valign=top><td align="right">11.6.11.21</td> * <td align="left">- Initial version of extractor-confidence computation * </td></tr> * <tr valign=top><td align="right">11.6.11.22</td> * <td align="left"> - Better version of extractor-confidence computation, with BeamSearch modified appropriately * </td></tr> * <tr valign=top><td align="right">12.7.3.30</td> * <td align="left"> - Added support for a hierarchy of text bases and text labels that can be used in code or mixup<br> * <td align="left"> - Refactored the Tokenizer class to support multiple tokenization schemes<br> * <td align="left"> - Refactored the TextBase hierarchy to make the TextBase interface immutable with a mutable abstract * implementation defining the mutable functionality. <br> * <td align="left"> - Created a TextBaseManager class to manage text bases that are derived from each other.<br> * <td align="left"> - Added keywords to the mixup language to provide access to the TextBaseManager functionality.<br> * </td></tr> * <tr valign=top><td align="right">12.7.5.31</td> * <td align="left"> - Fixed bug where history size variable for certain learners was being ignored<br> * <td align="left"> - Added new Random Forests learners<br> * <td align="left"> - Fixed bugs that prevented compilation under java 1.6<br> * <td align="left"> - Switched the build mode from java 1.4 to java 1.5 in the ant build scripts<br> * <td align="left"> - Created new layout for documentation<br> * </td></tr> * <tr valign=top><td align="right">12.7.8.10</td> * <td align="left"> - Fixed bug in KnnClassifier: now when no neighbors are found, class priors are used * </td></tr> * </table> */ public class Version { private static String version = "Version 12.7.8.10"; public static String getVersion() { return version; } }
Added version 13.7.10.8.
src/edu/cmu/minorthird/util/Version.java
Added version 13.7.10.8.
Java
bsd-3-clause
9cad5e84cebf6fa4f41277342b9ac91d7b3167eb
0
joansmith/tripleplay,tomfisher/tripleplay,tomfisher/tripleplay,tomfisher/tripleplay,joansmith/tripleplay,joansmith/tripleplay,joansmith/tripleplay,tomfisher/tripleplay,tomfisher/tripleplay,joansmith/tripleplay
// // Triple Play - utilities for use in PlayN-based games // Copyright (c) 2011, Three Rings Design, Inc. - All rights reserved. // http://github.com/threerings/tripleplay/blob/master/LICENSE package tripleplay.ui; import pythagoras.f.Dimension; import pythagoras.f.IDimension; /** * An invisible widget that simply requests a fixed amount of space. */ public class Shim extends Element<Shim> { public Shim (float width, float height) { _size = new Dimension(width, height); } public Shim (IDimension size) { _size = new Dimension(size); } @Override protected LayoutData createLayoutData (float hintX, float hintY) { return new LayoutData() { @Override public Dimension computeSize (float hintX, float hintY) { return new Dimension(_size); } }; } protected final Dimension _size; }
core/src/main/java/tripleplay/ui/Shim.java
// // Triple Play - utilities for use in PlayN-based games // Copyright (c) 2011, Three Rings Design, Inc. - All rights reserved. // http://github.com/threerings/tripleplay/blob/master/LICENSE package tripleplay.ui; import pythagoras.f.Dimension; /** * An invisible widget that simply requests a fixed amount of space. */ public class Shim extends Element<Shim> { public Shim (float width, float height) { _shimWidth = width; _shimHeight = height; } @Override protected LayoutData createLayoutData (float hintX, float hintY) { return new LayoutData() { @Override public Dimension computeSize (float hintX, float hintY) { return new Dimension(_shimWidth, _shimHeight); } }; } protected final float _shimWidth, _shimHeight; }
Accept a Dimension for our size.
core/src/main/java/tripleplay/ui/Shim.java
Accept a Dimension for our size.
Java
mit
d108e65051e2492d88a8c6f277cb755dbd7c5650
0
luckydonald/JavaPipBoyServer
/** * Created by luckydonald on 11.02.16. */ import de.luckydonald.pipboyserver.PipBoyServer.*; import de.luckydonald.pipboyserver.PipBoyServer.exceptions.AlreadyInsertedException; import de.luckydonald.pipboyserver.PipBoyServer.exceptions.AlreadyTakenException; import de.luckydonald.pipboyserver.PipBoyServer.exceptions.ParserException; import de.luckydonald.pipboyserver.PipBoyServer.types.*; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; import java.io.*; import java.util.logging.*; public class DatabaseTest { private static Logger jlog = Logger.getLogger("tests"); static { Logger.getGlobal().setLevel(Level.ALL); jlog.log(Level.INFO, "Loaded."); } Database db; DBDict root; @Before public void setUp() { db = null; root = null; db = new Database(); root = new DBDict(null); db.add(root); assertEquals("db[0] == root", root, db.get(0)); // {} } /** * Checks that Ids are set automatically and correctly when adding to {@link DBList}s and {@link DBDict}s. * Also checks inserting all the different types of {@link DBEntry}s. * * @throws AlreadyTakenException * @throws AlreadyInsertedException */ public void testCreation(boolean printDebug) throws AlreadyTakenException, AlreadyInsertedException { /* BOOLEAN (1), // java: bool INT8 (2), // java: byte INT32 (3), // java: int FLOAT (5), // java: float STRING (6), // java: String LIST (7), DICT (8); */ if (printDebug) System.out.println(""); if (printDebug) System.out.println("a1"); DBBoolean a1 = new DBBoolean(db, true); root.add("a1", a1); // {"a1": True} if (printDebug) db.print(); assertEquals("db[1] == a1", a1, db.get(1)); if (printDebug) System.out.println(""); if (printDebug) System.out.println("a2"); DBInteger8 a2 = new DBInteger8(db, 8); root.add("a2", a2); // {"a1": True, "a2": 0x08} if (printDebug) db.print(); assertEquals("db[2] == a2", a2, db.get(2)); if (printDebug) System.out.println(""); if (printDebug) System.out.println("a3"); DBInteger32 a3 = new DBInteger32(db, 32); root.add("a3", a3); // {"a1": True, "a2": 0x08, "a3": 32} if (printDebug) db.print(); assertEquals("db[3] = a3", a3, db.get(3)); if (printDebug) System.out.println(""); if (printDebug) System.out.println("a4"); DBFloat a4 = new DBFloat(db, 3.4); root.add("a4", a4); // {"a1": True, "a2": 0x08, "a3": 32, "a4": 3.4} if (printDebug) db.print(); assertEquals("db[4] = a4", a4, db.get(4)); if (printDebug) System.out.println(""); if (printDebug) System.out.println("a5"); DBString a5 = new DBString(db, "foo"); root.add("a5", a5); // { "a1": True, "a2": 0x08, "a3": 32, "a4": 3.4, // "a5: "foo" } if (printDebug) db.print(); assertEquals("db[5] = a5", a5, db.get(5)); if (printDebug) System.out.println(""); if (printDebug) System.out.println("a6 + b1"); DBString b1 = new DBString(db, "bar"); DBList a6 = new DBList(db, b1); // ["bar"] root.add("a6", a6); // { "a1": True, "a2": 0x08, "a3": 32, "a4": 3.4, // "a5: "foo", "a6": ["bar"] } if (printDebug) db.print(); assertEquals("db[6] = b1", b1, db.get(6)); assertEquals("db[7] = a6", a6, db.get(7)); if (printDebug) System.out.println(""); if (printDebug) System.out.println("a6 -> b2"); DBInteger32 b2 = new DBInteger32(db, 34); a6.append(b2); // { "a1": True, "a2": 0x08, "a3": 32, "a4": 3.4, // "a5: "foo", "a6": ["bar", 34] } if (printDebug) db.print(); assertEquals("db[8] = b2", b2, db.get(8)); assertEquals("db[7] = a6", a6, db.get(7)); if (printDebug) System.out.println(""); if (printDebug) System.out.println("a6 -> b3"); DBDict b3 = new DBDict(db); // {} a6.append(b3); // { "a1": True, "a2": 0x08, "a3": 32, "a4": 3.4, // "a5: "foo", "a6": ["bar", 34, {}] } if (printDebug) db.print(); assertEquals("db[9] = b3", b3, db.get(9)); if (printDebug) System.out.println(""); if (printDebug) System.out.println("a6 -> b3 -> c1"); DBString c1 = new DBString(db, "baz"); DBInteger32 c2 = new DBInteger32(db, 35); b3.add("c1", c1).add("c2", c2); // { // "a1": True, // "a2": 0x08, // "a3": 32, // "a4": 3.4, // "a5: "foo", // "a6": [ // "bar", // 34, // {"c1": "baz", "c2": 35} // ] // } if (printDebug) db.print(); assertEquals("db[10] = c1", c1, db.get(10)); assertEquals("db[11] = c2", c2, db.get(11)); if (printDebug) System.out.println(""); } @Test public void testCreation() throws AlreadyTakenException, AlreadyInsertedException { this.testCreation(false); } @Test public void testInsertBoolean() throws AlreadyTakenException, AlreadyInsertedException { DBBoolean b1 = new DBBoolean(db, true); root.add("boolean1", b1); assertEquals("boolean without DB added", b1, db.get(1)); DBBoolean b2 = new DBBoolean(true); root.add("boolean2", b2); assertEquals("boolean with DB added", b2, db.get(2)); } @Test public void testInsertInt8() throws AlreadyTakenException, AlreadyInsertedException { DBInteger8 i1 = new DBInteger8(db, 16); root.add("Integer8_1a", i1); assertEquals("boolean without DB added", i1, db.get(1)); DBInteger8 i2 = new DBInteger8(16); root.add("Integer8_1b", i2); assertEquals("boolean with DB added", i2, db.get(2)); DBInteger8 i3 = new DBInteger8(db, (byte)17); root.add("Integer8_2a", i3); assertEquals("boolean without DB added", i3, db.get(3)); DBInteger8 i4 = new DBInteger8((byte)17); root.add("Integer8_2b", i4); assertEquals("boolean with DB added", i4, db.get(4)); } @Test public void testInsertInt32() throws AlreadyTakenException, AlreadyInsertedException { DBInteger32 i1 = new DBInteger32(db, 16); root.add("Integer32_1a", i1); assertEquals("integer with DB added", i1, db.get(1)); Integer integer_test_value = 300; DBInteger32 i2 = new DBInteger32(integer_test_value); root.add("Integer32_1b", i2); assertEquals("integer with DB added", i2, db.get(2)); assertEquals("integer with DB has correct number", integer_test_value, ((DBInteger32)db.get(2)).getValue()); //{ "Integer32_1a": 16, "Integer32_1b": 300} } @Test public void testGetInt32() throws AlreadyTakenException, AlreadyInsertedException { testInsertInt32(); //{ "Integer32_1a": 16, "Integer32_1b": 300} assertEquals("db.get -> Int32 -> intValue() == 300", 300, db.get("Integer32_1b").intValue()); } @Test public void testUpdateFromString() throws AlreadyTakenException, AlreadyInsertedException, ParserException { testCreation(); // { // "a1": True, // "a2": 0x08, // "a3": 32, // "a4": 3.4, // "a5: "foo", // "a6": [ // "bar", // 34, // {"c1": "baz", "c2": 35} // ] // } DBSimple a1 = (DBSimple) db.get("a1"); a1.setValueFromString("false"); assertEquals("(DBSimple) updated to false=false", a1.getValue(), false); a1.setValueFromString("1"); assertEquals("(DBSimple) updated to 1=true", a1.getValue(), true); DBBoolean a1b = (DBBoolean) db.get("a1"); a1b.setValue(false); assertEquals("(DBBoolean) directly updated to false", a1.getValue(), false); a1b.setValueFromString("yes"); assertEquals("(DBBoolean) updated to yes=true", a1.getValue(), true); a1b.setValueFromString("no"); assertEquals("(DBBoolean) updated to no=false", a1.getValue(), false); } @Test public void testUnicodeStrings() throws AlreadyTakenException, AlreadyInsertedException { DBString str = new DBString("Günter was here."); root.add("äöüß", str); db.get("äöüß").textValue(); } @Test public void testTraversal() throws AlreadyTakenException, AlreadyInsertedException { testCreation(); // { // "a1": True, // "a2": 0x08, // "a3": 32, // "a4": 3.4, // "a5: "foo", // "a6": [ // "bar", // 34, // {"c1": "baz", "c2": 35} // ] // } assertEquals( "root[\"a6\"][2][\"c1\"] traversal", "baz", db.getRoot().getDBDict().get("a6").getDBList().get(2).getDBDict().get("c1").textValue() ); } @Test public void testStringTraversal() throws AlreadyTakenException, AlreadyInsertedException { testCreation(); // { // "a1": True, // "a2": 0x08, // "a3": 32, // "a4": 3.4, // "a5: "foo", // "a6": [ // "bar", // 34, // {"c1": "baz", "c2": 35} // ] // } assertEquals( "root[\"a6.2.c1\"] string traversal", "baz", db.get("a6.2.c1").textValue() ); } @Test public void testCommands() throws AlreadyTakenException, AlreadyInsertedException { testCreation(); String inContent = "get a1\n\nset a6.2.c1\n\nGünter was here\n"; String expected = "Enter command, end with ^D\n" + "(0):\tDBDict(id=0, data={\"a1\":1, \"a2\":2, \"a3\":3, \"a4\":4, \"a5\":5, \"a6\":7}," + " inserts={\"a1\":1, \"a2\":2, \"a3\":3, \"a4\":4, \"a5\":5, \"a6\":7}," + " removes=[]\na1 (1):\tDBBoolean(true)\n" + " _\n" + "| Give a key/index where to go next or \"..\" to move up agan.\n" + "| Blank line exits.\n" + "'>Enter command, end with ^D\n" + "(0):\tDBDict(id=0, data={\"a1\":1, \"a2\":2, \"a3\":3, \"a4\":4, \"a5\":5, \"a6\":7}, inserts={\"a1\":1, \"a2\":2, \"a3\":3, \"a4\":4, \"a5\":5, \"a6\":7}, removes=[]\n" + "a6.2.c1 (10):\tDBString(\"baz\")\n" + " _\n" + "| Give a key/index where to go next or \"..\" to move up agan.\n" + "| Blank line exits.\n" + "'>a6.2.c1 (10):\tDBString(\"baz\")\n" + " _\n" + "| Enter your new value.\n" + "'>a6.2.c1 (10):\tDBString(\"Günter was here\")\n" + "Enter command, end with ^D\n"; ByteArrayInputStream in = new ByteArrayInputStream(inContent.getBytes()); ByteArrayOutputStream outContent = new ByteArrayOutputStream(); PrintStream out = new PrintStream(outContent); System.setOut(out); System.setIn(in); this.db.startCLI(); //while(true){ try { Thread.sleep(5000); } catch (InterruptedException ignored) {} //} //reset System.in/out to its original. Just to be sure. System.setIn(System.in); System.setOut(System.out); assertEquals("CLI: execute several commands", expected, outContent.toString()); assertEquals( "root[\"a6.2.c1\"] is now Günter was here", "Günter was here", db.get("a6.2.c1").textValue() ); } }
src/test/java/DatabaseTest.java
/** * Created by luckydonald on 11.02.16. */ import de.luckydonald.pipboyserver.PipBoyServer.*; import de.luckydonald.pipboyserver.PipBoyServer.exceptions.AlreadyInsertedException; import de.luckydonald.pipboyserver.PipBoyServer.exceptions.AlreadyTakenException; import de.luckydonald.pipboyserver.PipBoyServer.exceptions.ParserException; import de.luckydonald.pipboyserver.PipBoyServer.types.*; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; import java.util.logging.*; public class DatabaseTest { private static Logger jlog = Logger.getLogger("tests"); static { Logger.getGlobal().setLevel(Level.ALL); jlog.log(Level.INFO, "Loaded."); } Database db; DBDict root; @Before public void setUp() { db = null; root = null; db = new Database(); root = new DBDict(null); db.add(root); assertEquals("db[0] == root", root, db.get(0)); // {} } /** * Checks that Ids are set automatically and correctly when adding to {@link DBList}s and {@link DBDict}s. * Also checks inserting all the different types of {@link DBEntry}s. * * @throws AlreadyTakenException * @throws AlreadyInsertedException */ public void testCreation(boolean printDebug) throws AlreadyTakenException, AlreadyInsertedException { /* BOOLEAN (1), // java: bool INT8 (2), // java: byte INT32 (3), // java: int FLOAT (5), // java: float STRING (6), // java: String LIST (7), DICT (8); */ if (printDebug) System.out.println(""); if (printDebug) System.out.println("a1"); DBBoolean a1 = new DBBoolean(db, true); root.add("a1", a1); // {"a1": True} if (printDebug) db.print(); assertEquals("db[1] == a1", a1, db.get(1)); if (printDebug) System.out.println(""); if (printDebug) System.out.println("a2"); DBInteger8 a2 = new DBInteger8(db, 8); root.add("a2", a2); // {"a1": True, "a2": 0x08} if (printDebug) db.print(); assertEquals("db[2] == a2", a2, db.get(2)); if (printDebug) System.out.println(""); if (printDebug) System.out.println("a3"); DBInteger32 a3 = new DBInteger32(db, 32); root.add("a3", a3); // {"a1": True, "a2": 0x08, "a3": 32} if (printDebug) db.print(); assertEquals("db[3] = a3", a3, db.get(3)); if (printDebug) System.out.println(""); if (printDebug) System.out.println("a4"); DBFloat a4 = new DBFloat(db, 3.4); root.add("a4", a4); // {"a1": True, "a2": 0x08, "a3": 32, "a4": 3.4} if (printDebug) db.print(); assertEquals("db[4] = a4", a4, db.get(4)); if (printDebug) System.out.println(""); if (printDebug) System.out.println("a5"); DBString a5 = new DBString(db, "foo"); root.add("a5", a5); // { "a1": True, "a2": 0x08, "a3": 32, "a4": 3.4, // "a5: "foo" } if (printDebug) db.print(); assertEquals("db[5] = a5", a5, db.get(5)); if (printDebug) System.out.println(""); if (printDebug) System.out.println("a6 + b1"); DBString b1 = new DBString(db, "bar"); DBList a6 = new DBList(db, b1); // ["bar"] root.add("a6", a6); // { "a1": True, "a2": 0x08, "a3": 32, "a4": 3.4, // "a5: "foo", "a6": ["bar"] } if (printDebug) db.print(); assertEquals("db[6] = b1", b1, db.get(6)); assertEquals("db[7] = a6", a6, db.get(7)); if (printDebug) System.out.println(""); if (printDebug) System.out.println("a6 -> b2"); DBInteger32 b2 = new DBInteger32(db, 34); a6.append(b2); // { "a1": True, "a2": 0x08, "a3": 32, "a4": 3.4, // "a5: "foo", "a6": ["bar", 34] } if (printDebug) db.print(); assertEquals("db[8] = b2", b2, db.get(8)); assertEquals("db[7] = a6", a6, db.get(7)); if (printDebug) System.out.println(""); if (printDebug) System.out.println("a6 -> b3"); DBDict b3 = new DBDict(db); // {} a6.append(b3); // { "a1": True, "a2": 0x08, "a3": 32, "a4": 3.4, // "a5: "foo", "a6": ["bar", 34, {}] } if (printDebug) db.print(); assertEquals("db[9] = b3", b3, db.get(9)); if (printDebug) System.out.println(""); if (printDebug) System.out.println("a6 -> b3 -> c1"); DBString c1 = new DBString(db, "baz"); DBInteger32 c2 = new DBInteger32(db, 35); b3.add("c1", c1).add("c2", c2); // { // "a1": True, // "a2": 0x08, // "a3": 32, // "a4": 3.4, // "a5: "foo", // "a6": [ // "bar", // 34, // {"c1": "baz", "c2": 35} // ] // } if (printDebug) db.print(); assertEquals("db[10] = c1", c1, db.get(10)); assertEquals("db[11] = c2", c2, db.get(11)); if (printDebug) System.out.println(""); } @Test public void testCreation() throws AlreadyTakenException, AlreadyInsertedException { this.testCreation(false); } @Test public void testInsertBoolean() throws AlreadyTakenException, AlreadyInsertedException { DBBoolean b1 = new DBBoolean(db, true); root.add("boolean1", b1); assertEquals("boolean without DB added", b1, db.get(1)); DBBoolean b2 = new DBBoolean(true); root.add("boolean2", b2); assertEquals("boolean with DB added", b2, db.get(2)); } @Test public void testInsertInt8() throws AlreadyTakenException, AlreadyInsertedException { DBInteger8 i1 = new DBInteger8(db, 16); root.add("Integer8_1a", i1); assertEquals("boolean without DB added", i1, db.get(1)); DBInteger8 i2 = new DBInteger8(16); root.add("Integer8_1b", i2); assertEquals("boolean with DB added", i2, db.get(2)); DBInteger8 i3 = new DBInteger8(db, (byte)17); root.add("Integer8_2a", i3); assertEquals("boolean without DB added", i3, db.get(3)); DBInteger8 i4 = new DBInteger8((byte)17); root.add("Integer8_2b", i4); assertEquals("boolean with DB added", i4, db.get(4)); } @Test public void testInsertInt32() throws AlreadyTakenException, AlreadyInsertedException { DBInteger32 i1 = new DBInteger32(db, 16); root.add("Integer32_1a", i1); assertEquals("integer with DB added", i1, db.get(1)); Integer integer_test_value = 300; DBInteger32 i2 = new DBInteger32(integer_test_value); root.add("Integer32_1b", i2); assertEquals("integer with DB added", i2, db.get(2)); assertEquals("integer with DB has correct number", integer_test_value, ((DBInteger32)db.get(2)).getValue()); //{ "Integer32_1a": 16, "Integer32_1b": 300} } @Test public void testGetInt32() throws AlreadyTakenException, AlreadyInsertedException { testInsertInt32(); //{ "Integer32_1a": 16, "Integer32_1b": 300} assertEquals("db.get -> Int32 -> intValue() == 300", 300, db.get("Integer32_1b").intValue()); } @Test public void testUpdateFromString() throws AlreadyTakenException, AlreadyInsertedException, ParserException { testCreation(); // { // "a1": True, // "a2": 0x08, // "a3": 32, // "a4": 3.4, // "a5: "foo", // "a6": [ // "bar", // 34, // {"c1": "baz", "c2": 35} // ] // } DBSimple a1 = (DBSimple) db.get("a1"); a1.setValueFromString("false"); assertEquals("(DBSimple) updated to false=false", a1.getValue(), false); a1.setValueFromString("1"); assertEquals("(DBSimple) updated to 1=true", a1.getValue(), true); DBBoolean a1b = (DBBoolean) db.get("a1"); a1b.setValue(false); assertEquals("(DBBoolean) directly updated to false", a1.getValue(), false); a1b.setValueFromString("yes"); assertEquals("(DBBoolean) updated to yes=true", a1.getValue(), true); a1b.setValueFromString("no"); assertEquals("(DBBoolean) updated to no=false", a1.getValue(), false); } @Test public void testUnicodeStrings() throws AlreadyTakenException, AlreadyInsertedException { DBString str = new DBString("Günter was here."); root.add("äöüß", str); db.get("äöüß").textValue(); } @Test public void testTraversal() throws AlreadyTakenException, AlreadyInsertedException { testCreation(); // { // "a1": True, // "a2": 0x08, // "a3": 32, // "a4": 3.4, // "a5: "foo", // "a6": [ // "bar", // 34, // {"c1": "baz", "c2": 35} // ] // } assertEquals( "root[\"a6\"][2][\"c1\"] traversal", "baz", db.getRoot().getDBDict().get("a6").getDBList().get(2).getDBDict().get("c1").textValue() ); } @Test public void testStringTraversal() throws AlreadyTakenException, AlreadyInsertedException { testCreation(); // { // "a1": True, // "a2": 0x08, // "a3": 32, // "a4": 3.4, // "a5: "foo", // "a6": [ // "bar", // 34, // {"c1": "baz", "c2": 35} // ] // } assertEquals( "root[\"a6.2.c1\"] string traversal", "baz", db.get("a6.2.c1").textValue() ); } }
Test for some commands.
src/test/java/DatabaseTest.java
Test for some commands.
Java
mit
8246562afc0444215f0764ef4bd0cd006525ef22
0
ramswaroop/botkit,ramswaroop/botkit
package me.ramswaroop.jbot.core.slack; import com.fasterxml.jackson.databind.ObjectMapper; import me.ramswaroop.jbot.core.common.BaseBot; import me.ramswaroop.jbot.core.common.BotWebSocketHandler; import me.ramswaroop.jbot.core.common.Controller; import me.ramswaroop.jbot.core.common.EventType; import me.ramswaroop.jbot.core.slack.models.Event; import me.ramswaroop.jbot.core.slack.models.Message; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.util.StringUtils; import org.springframework.web.socket.CloseStatus; import org.springframework.web.socket.TextMessage; import org.springframework.web.socket.WebSocketHandler; import org.springframework.web.socket.WebSocketSession; import org.springframework.web.socket.client.WebSocketConnectionManager; import org.springframework.web.socket.client.standard.StandardWebSocketClient; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import java.io.IOException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Queue; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.regex.Matcher; /** * Base class for making Slack Bots. Any class extending * this will get all powers of a Slack Bot. * * @author ramswaroop * @version 1.0.0, 05/06/2016 */ public abstract class Bot extends BaseBot { private static final Logger logger = LoggerFactory.getLogger(Bot.class); private final Object sendMessageLock = new Object(); /** * Service to access Slack APIs. */ @Autowired protected SlackService slackService; /** * Task to ping Slack at regular intervals to prevent * closing of web socket connection. */ private PingTask pingTask; /** * Executor service which houses the ping task. */ private ScheduledExecutorService pingScheduledExecutorService; /** * Web socket manager */ private WebSocketConnectionManager webSocketManager; /** * Class extending this must implement this as it's * required to make the initial RTM.start() call. * * @return the slack token of the bot */ public abstract String getSlackToken(); /** * An instance of the Bot is required by * the {@link BotWebSocketHandler} class. * * @return the Bot instance overriding this method */ public abstract Bot getSlackBot(); /** * Invoked after a successful web socket connection is * established. You can override this method in the child classes. * * @param session websocket session between bot and slack * @see WebSocketHandler#afterConnectionEstablished */ public void afterConnectionEstablished(WebSocketSession session) { logger.debug("WebSocket connected: {}", session); } /** * Invoked after the web socket connection is closed. * You can override this method in the child classes. * * @param session websocket session between bot and slack * @param status websocket close status * @see WebSocketHandler#afterConnectionClosed */ public void afterConnectionClosed(WebSocketSession session, CloseStatus status) { logger.debug("WebSocket closed: {}, Close Status: {}", session, status.toString()); } /** * Handle an error from the underlying WebSocket message transport. * * @param session websocket session between bot and slack * @param exception thrown because of transport error * @see WebSocketHandler#handleTransportError */ public void handleTransportError(WebSocketSession session, Throwable exception) { logger.error("Transport Error: ", exception); } /** * Invoked when a new Slack event(WebSocket text message) arrives. * * @param session websocket session between bot and slack * @param textMessage websocket message received from slack */ public final void handleTextMessage(WebSocketSession session, TextMessage textMessage) { ObjectMapper mapper = new ObjectMapper(); logger.debug("Response from Slack: {}", textMessage.getPayload()); try { Event event = mapper.readValue(textMessage.getPayload(), Event.class); if (event.getType() != null) { if (event.getType().equalsIgnoreCase(EventType.IM_OPEN.name()) || event.getType().equalsIgnoreCase(EventType.IM_CREATED.name())) { if (event.getChannelId() != null) { slackService.addImChannelId(event.getChannelId()); } else if (event.getChannel() != null) { slackService.addImChannelId(event.getChannel().getId()); } } else if (event.getType().equalsIgnoreCase(EventType.MESSAGE.name())) { if (event.getText() != null && event.getText().contains(slackService.getCurrentUser().getId())) { // direct mention event.setType(EventType.DIRECT_MENTION.name()); } else if (slackService.getImChannelIds().contains(event.getChannelId())) { // direct message event.setType(EventType.DIRECT_MESSAGE.name()); } } else if (event.getType().equalsIgnoreCase(EventType.HELLO.name())) { pingAtRegularIntervals(session); } } else { // slack does not send any TYPE for acknowledgement messages event.setType(EventType.ACK.name()); } if (isConversationOn(event)) { invokeChainedMethod(session, event); } else { invokeMethods(session, event); } } catch (Exception e) { logger.error("Error handling response from Slack: {} \nException: ", textMessage.getPayload(), e); } } /** * Method to send a reply back to Slack after receiving an {@link Event}. * Learn <a href="https://api.slack.com/rtm">more on sending responses to Slack.</a> * * @param session websocket session between bot and slack * @param event received from slack * @param reply the message to send to slack */ protected final void reply(WebSocketSession session, Event event, Message reply) { try { if (StringUtils.isEmpty(reply.getType())) { reply.setType(EventType.MESSAGE.name().toLowerCase()); } reply.setText(encode(reply.getText())); if (reply.getChannel() == null && event.getChannelId() != null) { reply.setChannel(event.getChannelId()); } synchronized (sendMessageLock) { session.sendMessage(new TextMessage(reply.toJSONString())); } if (logger.isDebugEnabled()) { // For debugging purpose only logger.debug("Reply (Message): {}", reply.toJSONString()); } } catch (IOException e) { logger.error("Error sending event: {}. Exception: {}", event.getText(), e.getMessage()); } } protected final void reply(WebSocketSession session, Event event, String text) { reply(session, event, new Message(text)); } /** * Call this method to start a conversation. * * @param event received from slack */ protected final void startConversation(Event event, String methodName) { startConversation(event.getChannelId(), methodName); } /** * Call this method to jump to the next method in a conversation. * * @param event received from slack */ protected final void nextConversation(Event event) { nextConversation(event.getChannelId()); } /** * Call this method to stop the end the conversation. * * @param event received from slack */ protected final void stopConversation(Event event) { stopConversation(event.getChannelId()); } /** * Check whether a conversation is up in a particular slack channel. * * @param event received from slack * @return true if a conversation is on, false otherwise. */ protected final boolean isConversationOn(Event event) { return isConversationOn(event.getChannelId()); } /** * Invoke the methods with matching {@link Controller#events()} * and {@link Controller#pattern()} in events received from Slack. * * @param session websocket session between bot and slack * @param event received from slack */ private void invokeMethods(WebSocketSession session, Event event) { try { List<MethodWrapper> methodWrappers = eventToMethodsMap.get(event.getType().toUpperCase()); if (methodWrappers == null) return; methodWrappers = new ArrayList<>(methodWrappers); MethodWrapper matchedMethod = getMethodWithMatchingPatternAndFilterUnmatchedMethods(event.getText(), methodWrappers); if (matchedMethod != null) { methodWrappers = new ArrayList<>(); methodWrappers.add(matchedMethod); } for (MethodWrapper methodWrapper : methodWrappers) { Method method = methodWrapper.getMethod(); if (Arrays.asList(method.getParameterTypes()).contains(Matcher.class)) { method.invoke(this, session, event, methodWrapper.getMatcher()); } else { method.invoke(this, session, event); } } } catch (Exception e) { logger.error("Error invoking controller: ", e); } } /** * Invoke the appropriate method in a conversation. * * @param session websocket session between bot and slack * @param event received from slack */ private void invokeChainedMethod(WebSocketSession session, Event event) { Queue<MethodWrapper> queue = conversationQueueMap.get(event.getChannelId()); if (queue != null && !queue.isEmpty()) { MethodWrapper methodWrapper = queue.peek(); try { EventType[] eventTypes = methodWrapper.getMethod().getAnnotation(Controller.class).events(); for (EventType eventType : eventTypes) { if (eventType.name().equalsIgnoreCase(event.getType())) { methodWrapper.getMethod().invoke(this, session, event); return; } } } catch (Exception e) { logger.error("Error invoking chained method: ", e); } } } /** * Encode the text before sending to Slack. * Learn <a href="https://api.slack.com/docs/formatting">more on message formatting in Slack</a> * * @param message to encode * @return encoded message */ private String encode(String message) { return message == null ? null : message.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;"); } private StandardWebSocketClient client() { return new StandardWebSocketClient(); } private BotWebSocketHandler handler() { return new BotWebSocketHandler(getSlackBot()); } /** * Entry point where the web socket connection starts * and after which your bot becomes live. */ @PostConstruct protected void startRTMAndWebSocketConnection() { slackService.connectRTM(getSlackToken()); if (slackService.getWebSocketUrl() != null) { manager = new WebSocketConnectionManager(client(), handler(), slackService.getWebSocketUrl()); manager.start(); } else { logger.error("No web socket url returned by Slack."); } } /** * Is websocket open */ protected boolean isOpen() { return pingTask != null && pingTask.isConnected(); } /** * Shutdown ping scheduler when application shuts down. */ @PreDestroy public void destroy() { if (pingScheduledExecutorService != null) { pingScheduledExecutorService.shutdownNow(); } } private void pingAtRegularIntervals(WebSocketSession session) { // only get called on hello response (connect) pingTask = new PingTask(session); if (pingScheduledExecutorService != null) { pingScheduledExecutorService.shutdownNow(); } pingScheduledExecutorService = Executors.newSingleThreadScheduledExecutor(); pingScheduledExecutorService.scheduleAtFixedRate(pingTask, 1L, 30L, TimeUnit.SECONDS); } class PingTask implements Runnable { WebSocketSession webSocketSession; boolean isRunning; boolean isException; PingTask(WebSocketSession webSocketSession) { this.webSocketSession = webSocketSession; } @Override public void run() { try { logger.debug("Pinging Slack..."); isRunning = true; Message message = new Message(); message.setType(EventType.PING.name().toLowerCase()); synchronized (sendMessageLock) { webSocketSession.sendMessage(new TextMessage(message.toJSONString())); } isException = false; } catch (Exception e) { logger.error("Error pinging Slack. Slack bot may go offline when not active. Exception: ", e); isException = true; if (!isOpen()) { try { manager.stop(); } catch (Throwable t) { logger.error("Error closing websocket after failed ping. Exception: ", t); } pingTask = null; if (pingScheduledExecutorService != null) { pingScheduledExecutorService.shutdownNow(); } pingScheduledExecutorService = null; startRTMAndWebSocketConnection(); } } } boolean isConnected() { return webSocketSession.isOpen(); } boolean isRunning() { return isRunning; } boolean isException() { return isException; } } }
jbot/src/main/java/me/ramswaroop/jbot/core/slack/Bot.java
package me.ramswaroop.jbot.core.slack; import com.fasterxml.jackson.databind.ObjectMapper; import me.ramswaroop.jbot.core.common.BaseBot; import me.ramswaroop.jbot.core.common.BotWebSocketHandler; import me.ramswaroop.jbot.core.common.Controller; import me.ramswaroop.jbot.core.common.EventType; import me.ramswaroop.jbot.core.slack.models.Event; import me.ramswaroop.jbot.core.slack.models.Message; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.util.StringUtils; import org.springframework.web.socket.CloseStatus; import org.springframework.web.socket.TextMessage; import org.springframework.web.socket.WebSocketHandler; import org.springframework.web.socket.WebSocketSession; import org.springframework.web.socket.client.WebSocketConnectionManager; import org.springframework.web.socket.client.standard.StandardWebSocketClient; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import java.io.IOException; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Queue; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.regex.Matcher; /** * Base class for making Slack Bots. Any class extending * this will get all powers of a Slack Bot. * * @author ramswaroop * @version 1.0.0, 05/06/2016 */ public abstract class Bot extends BaseBot { private static final Logger logger = LoggerFactory.getLogger(Bot.class); private final Object sendMessageLock = new Object(); /** * Service to access Slack APIs. */ @Autowired protected SlackService slackService; /** * Task to ping Slack at regular intervals to prevent * closing of web socket connection. */ private PingTask pingTask; /** * Executor service which houses the ping task. */ private ScheduledExecutorService pingScheduledExecutorService; /** * Web socket manager */ private WebSocketConnectionManager manager; /** * Class extending this must implement this as it's * required to make the initial RTM.start() call. * * @return the slack token of the bot */ public abstract String getSlackToken(); /** * An instance of the Bot is required by * the {@link BotWebSocketHandler} class. * * @return the Bot instance overriding this method */ public abstract Bot getSlackBot(); /** * Invoked after a successful web socket connection is * established. You can override this method in the child classes. * * @param session websocket session between bot and slack * @see WebSocketHandler#afterConnectionEstablished */ public void afterConnectionEstablished(WebSocketSession session) { logger.debug("WebSocket connected: {}", session); } /** * Invoked after the web socket connection is closed. * You can override this method in the child classes. * * @param session websocket session between bot and slack * @param status websocket close status * @see WebSocketHandler#afterConnectionClosed */ public void afterConnectionClosed(WebSocketSession session, CloseStatus status) { logger.debug("WebSocket closed: {}, Close Status: {}", session, status.toString()); } /** * Handle an error from the underlying WebSocket message transport. * * @param session websocket session between bot and slack * @param exception thrown because of transport error * @see WebSocketHandler#handleTransportError */ public void handleTransportError(WebSocketSession session, Throwable exception) { logger.error("Transport Error: ", exception); } /** * Invoked when a new Slack event(WebSocket text message) arrives. * * @param session websocket session between bot and slack * @param textMessage websocket message received from slack */ public final void handleTextMessage(WebSocketSession session, TextMessage textMessage) { ObjectMapper mapper = new ObjectMapper(); logger.debug("Response from Slack: {}", textMessage.getPayload()); try { Event event = mapper.readValue(textMessage.getPayload(), Event.class); if (event.getType() != null) { if (event.getType().equalsIgnoreCase(EventType.IM_OPEN.name()) || event.getType().equalsIgnoreCase(EventType.IM_CREATED.name())) { if (event.getChannelId() != null) { slackService.addImChannelId(event.getChannelId()); } else if (event.getChannel() != null) { slackService.addImChannelId(event.getChannel().getId()); } } else if (event.getType().equalsIgnoreCase(EventType.MESSAGE.name())) { if (event.getText() != null && event.getText().contains(slackService.getCurrentUser().getId())) { // direct mention event.setType(EventType.DIRECT_MENTION.name()); } else if (slackService.getImChannelIds().contains(event.getChannelId())) { // direct message event.setType(EventType.DIRECT_MESSAGE.name()); } } else if (event.getType().equalsIgnoreCase(EventType.HELLO.name())) { pingAtRegularIntervals(session); } } else { // slack does not send any TYPE for acknowledgement messages event.setType(EventType.ACK.name()); } if (isConversationOn(event)) { invokeChainedMethod(session, event); } else { invokeMethods(session, event); } } catch (Exception e) { logger.error("Error handling response from Slack: {} \nException: ", textMessage.getPayload(), e); } } /** * Method to send a reply back to Slack after receiving an {@link Event}. * Learn <a href="https://api.slack.com/rtm">more on sending responses to Slack.</a> * * @param session websocket session between bot and slack * @param event received from slack * @param reply the message to send to slack */ protected final void reply(WebSocketSession session, Event event, Message reply) { try { if (StringUtils.isEmpty(reply.getType())) { reply.setType(EventType.MESSAGE.name().toLowerCase()); } reply.setText(encode(reply.getText())); if (reply.getChannel() == null && event.getChannelId() != null) { reply.setChannel(event.getChannelId()); } synchronized (sendMessageLock) { session.sendMessage(new TextMessage(reply.toJSONString())); } if (logger.isDebugEnabled()) { // For debugging purpose only logger.debug("Reply (Message): {}", reply.toJSONString()); } } catch (IOException e) { logger.error("Error sending event: {}. Exception: {}", event.getText(), e.getMessage()); } } protected final void reply(WebSocketSession session, Event event, String text) { reply(session, event, new Message(text)); } /** * Call this method to start a conversation. * * @param event received from slack */ protected final void startConversation(Event event, String methodName) { startConversation(event.getChannelId(), methodName); } /** * Call this method to jump to the next method in a conversation. * * @param event received from slack */ protected final void nextConversation(Event event) { nextConversation(event.getChannelId()); } /** * Call this method to stop the end the conversation. * * @param event received from slack */ protected final void stopConversation(Event event) { stopConversation(event.getChannelId()); } /** * Check whether a conversation is up in a particular slack channel. * * @param event received from slack * @return true if a conversation is on, false otherwise. */ protected final boolean isConversationOn(Event event) { return isConversationOn(event.getChannelId()); } /** * Invoke the methods with matching {@link Controller#events()} * and {@link Controller#pattern()} in events received from Slack. * * @param session websocket session between bot and slack * @param event received from slack */ private void invokeMethods(WebSocketSession session, Event event) { try { List<MethodWrapper> methodWrappers = eventToMethodsMap.get(event.getType().toUpperCase()); if (methodWrappers == null) return; methodWrappers = new ArrayList<>(methodWrappers); MethodWrapper matchedMethod = getMethodWithMatchingPatternAndFilterUnmatchedMethods(event.getText(), methodWrappers); if (matchedMethod != null) { methodWrappers = new ArrayList<>(); methodWrappers.add(matchedMethod); } for (MethodWrapper methodWrapper : methodWrappers) { Method method = methodWrapper.getMethod(); if (Arrays.asList(method.getParameterTypes()).contains(Matcher.class)) { method.invoke(this, session, event, methodWrapper.getMatcher()); } else { method.invoke(this, session, event); } } } catch (Exception e) { logger.error("Error invoking controller: ", e); } } /** * Invoke the appropriate method in a conversation. * * @param session websocket session between bot and slack * @param event received from slack */ private void invokeChainedMethod(WebSocketSession session, Event event) { Queue<MethodWrapper> queue = conversationQueueMap.get(event.getChannelId()); if (queue != null && !queue.isEmpty()) { MethodWrapper methodWrapper = queue.peek(); try { EventType[] eventTypes = methodWrapper.getMethod().getAnnotation(Controller.class).events(); for (EventType eventType : eventTypes) { if (eventType.name().equalsIgnoreCase(event.getType())) { methodWrapper.getMethod().invoke(this, session, event); return; } } } catch (Exception e) { logger.error("Error invoking chained method: ", e); } } } /** * Encode the text before sending to Slack. * Learn <a href="https://api.slack.com/docs/formatting">more on message formatting in Slack</a> * * @param message to encode * @return encoded message */ private String encode(String message) { return message == null ? null : message.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;"); } private StandardWebSocketClient client() { return new StandardWebSocketClient(); } private BotWebSocketHandler handler() { return new BotWebSocketHandler(getSlackBot()); } /** * Entry point where the web socket connection starts * and after which your bot becomes live. */ @PostConstruct protected void startRTMAndWebSocketConnection() { slackService.connectRTM(getSlackToken()); if (slackService.getWebSocketUrl() != null) { manager = new WebSocketConnectionManager(client(), handler(), slackService.getWebSocketUrl()); manager.start(); } else { logger.error("No web socket url returned by Slack."); } } /** * Is websocket open */ protected boolean isOpen() { return pingTask != null && pingTask.isConnected(); } /** * Shutdown ping scheduler when application shuts down. */ @PreDestroy public void destroy() { if (pingScheduledExecutorService != null) { pingScheduledExecutorService.shutdownNow(); } } private void pingAtRegularIntervals(WebSocketSession session) { // only get called on hello response (connect) pingTask = new PingTask(session); if (pingScheduledExecutorService != null) { pingScheduledExecutorService.shutdownNow(); } pingScheduledExecutorService = Executors.newSingleThreadScheduledExecutor(); pingScheduledExecutorService.scheduleAtFixedRate(pingTask, 1L, 30L, TimeUnit.SECONDS); } class PingTask implements Runnable { WebSocketSession webSocketSession; boolean isRunning; boolean isException; PingTask(WebSocketSession webSocketSession) { this.webSocketSession = webSocketSession; } @Override public void run() { try { logger.debug("Pinging Slack..."); isRunning = true; Message message = new Message(); message.setType(EventType.PING.name().toLowerCase()); synchronized (sendMessageLock) { webSocketSession.sendMessage(new TextMessage(message.toJSONString())); } isException = false; } catch (Exception e) { logger.error("Error pinging Slack. Slack bot may go offline when not active. Exception: ", e); isException = true; if (!isOpen()) { try { manager.stop(); } catch (Throwable t) { logger.error("Error closing websocket after failed ping. Exception: ", t); } pingTask = null; if (pingScheduledExecutorService != null) { pingScheduledExecutorService.shutdownNow(); } pingScheduledExecutorService = null; startRTMAndWebSocketConnection(); } } } boolean isConnected() { return webSocketSession.isOpen(); } boolean isRunning() { return isRunning; } boolean isException() { return isException; } } }
Update jbot/src/main/java/me/ramswaroop/jbot/core/slack/Bot.java Co-Authored-By: nmorenor <[email protected]>
jbot/src/main/java/me/ramswaroop/jbot/core/slack/Bot.java
Update jbot/src/main/java/me/ramswaroop/jbot/core/slack/Bot.java
Java
mit
30ae4c6ea7958587ec86808e373e07cfc59cd51d
0
KosherBacon/Buffons-Needle-Problem
public class BuffonsNeedle { public static void main(String[] args) { int l = 1, d = 1; // Define length of needle and distance int w = 2 * d, h = d; YesOther yo = new YesOther(); boolean running = true; Center c = (x,theta) -> {return new Point(x,theta % 90D);}; Runnable r = new Runnable() { @Override public void run() { while (running) { Point t = c.center(Math.random() * (double) d, Math.random() * 180D); if (t.theta % 180D == 0) { yo.yes++; } else { if (l / 2D * Math.cos(t.theta * Math.PI / 180D) < l / 2D) { } } yo.other++; } System.out.println(2D * yo.yes / yo.other); } }; Thread t = new Thread(r); t.start(); } interface Center { Point center(double x, double theta); } } class Point { double x,theta; public Point(double x, double theta) { this.x = x; this.theta = theta; } } class YesOther { public int yes = 0, other = 0; }
src/BuffonsNeedle.java
public class BuffonsNeedle { public static void main(String[] args) { int l = 1, d = 1; // Define length of needle and distance int w = 2 * d, h = d; YesOther yo = new YesOther(); boolean running = true; Center c = (x,theta) -> {return new Point(x,theta);}; Runnable r = new Runnable() { @Override public void run() { while (running) { Point t = c.center(Math.random() * (double) d, Math.random() * 180D); if (t.theta % 180D == 0) { yo.yes++; } else { System.out.println(t.theta); } yo.other++; } System.out.println(2D * yo.yes / yo.other); } }; Thread t = new Thread(r); t.start(); } interface Center { Point center(double x, double theta); } } class Point { double x,theta; public Point(double x, double theta) { this.x = x; this.theta = theta; } } class YesOther { public int yes = 0, other = 0; }
Started between check
src/BuffonsNeedle.java
Started between check
Java
agpl-3.0
97076447239b29ad3bd6e77f29bc5240034cb62b
0
sba1/simpledance
/** * @author Standard * * To change this generated comment edit the template variable "typecomment": * Window>Preferences>Java>Templates. * To enable and disable the creation of type comments go to * Window>Preferences>Java>Code Generation. */ public class GraphicsData { /* 21cm hoch */ static private int ladyBaleX = 0; static private int ladyBaleY = -29; static private int [] ladyBale = new int [] { 12,-7, 12,-16, 9,-23, 6,-28, 2,-32, -2,-34, -5,-34, -7,-32, -8,-30, -10,-25, -12,-18, -12,-4, -6,9, -4,15, -4,22, 3,22, 3,14, 6,5 }; static private int ladyHeelX = 0; static private int ladyHeelY = 29; static private int [] ladyHeel = new int [] { -4,22, -6,23, -6,30, -3,34, 2,34, 5,30, 5,23, 3,22, }; static private int ladyBaleStart = 1; static private int ladyBaleEnd = 9; /* 25cm hoch */ static private int gentBaleX = 0; static private int gentBaleY = -29; static private int [] gentBale = new int [] { -14,-24, -12,-33, -8,-38, -5,-40, -1,-40, 4,-37, 8,-32, 11,-26, 13,-20, 14,-13, 14,-8, 13,-2, 11,4, 9,8, 8,11, 8,14, -8,14, -8,4, -11,-3, -13,-12, -14,-19, }; static private int gentHeelX = 0; static private int gentHeelY = 29; static private int [] gentHeel = new int [] { 12,14, 12,30, 10,35, 8,37, 5,39, 1,40, -1,40, -5,39, -8,37, -10,35, -12,30, -12,14, }; static private int gentBaleStart = 0; static private int gentBaleEnd = 9; public int baleX; public int baleY; public int [] baleData; public int heelX; public int heelY; public int [] heelData; public int feetDataYSize; public int realYSize; public int baleStart; public int baleEnd; public int baleTapStart; public int baleTapEnd; public GraphicsData(int type) { int minY = 0; int maxY = 0; if (type == 0) { baleX = gentBaleX; baleY = gentBaleY; baleData = gentBale; heelX = gentHeelX; heelY = gentHeelY; heelData = gentHeel; realYSize = 32; baleStart = gentBaleStart; baleEnd = gentBaleEnd; baleTapStart = 0; baleTapEnd = 5; } else if (type == 1) { baleX = ladyBaleX; baleY = ladyBaleY; baleData = ladyBale; heelX = ladyHeelX; heelY = ladyHeelY; heelData = ladyHeel; realYSize = 26; baleStart = ladyBaleStart; baleEnd = ladyBaleEnd; baleTapStart = 1; baleTapEnd = 7; } for (int i=0;i<baleData.length;i+=2) { if (baleData[i+1] < minY) minY = baleData[i+1]; else if (baleData[i+1] > maxY) maxY = baleData[i+1]; } for (int i=0;i<heelData.length;i+=2) { if (heelData[i+1] < minY) minY = heelData[i+1]; else if (heelData[i+1] > maxY) maxY = heelData[i+1]; } feetDataYSize = maxY - minY + 1; } public int [] getBale() { int length = baleEnd - baleStart + 1; int array[] = new int[length*2]; for (int i=0;i<length*2;i++) { array[i]=baleData[i + baleStart*2]; } return array; } public int[] getBaleTap() { int length = baleTapEnd - baleTapStart + 1; int array[] = new int[length*2]; for (int i=0;i<length*2;i++) { array[i]=baleData[i + baleTapStart*2]; } return array; } public int [] getHeel() { return heelData; } }
src/main/java/GraphicsData.java
/** * @author Standard * * To change this generated comment edit the template variable "typecomment": * Window>Preferences>Java>Templates. * To enable and disable the creation of type comments go to * Window>Preferences>Java>Code Generation. */ public class GraphicsData { /* 21cm hoch */ static private int ladyBaleX = 0; static private int ladyBaleY = -29; static private int [] ladyBale = new int [] { 12,-7, 12,-16, 9,-23, 6,-28, 2,-32, -2,-34, -5,-34, -7,-32, -8,-30, -10,-25, -12,-18, -12,-4, -6,9, -4,15, -4,22, 3,22, 3,14, 6,5 }; static private int ladyHeelX = 0; static private int ladyHeelY = 29; static private int [] ladyHeel = new int [] { -4,22, -6,23, -6,30, -3,34, 2,34, 5,30, 5,23, 3,22, }; static private int ladyBaleStart = 1; static private int ladyBaleEnd = 9; /* 25cm hoch */ static private int gentBaleX = 0; static private int gentBaleY = -29; static private int [] gentBale = new int [] { -14,-24, -12,-33, -8,-38, -5,-40, -1,-40, 4,-37, 8,-32, 11,-26, 13,-20, 14,-13, 14,-8, 13,-2, 11,4, 9,8, 8,11, 8,14, -8,14, -8,4, -11,-3, -13,-12, -14,-19, }; static private int gentHeelX = 0; static private int gentHeelY = 29; static private int [] gentHeel = new int [] { 12,14, 12,30, 10,35, 8,37, 5,39, 1,40, -1,40, -5,39, -8,37, -10,35, -12,30, -12,14, }; static private int gentBaleStart = 0; static private int gentBaleEnd = 9; public int baleX; public int baleY; public int [] baleData; public int heelX; public int heelY; public int [] heelData; public int feetDataYSize; public int realYSize; public int baleStart; public int baleEnd; public int baleTapStart; public int baleTapEnd; public GraphicsData(int type) { int minY = 0; int maxY = 0; if (type == 0) { baleX = gentBaleX; baleY = gentBaleY; baleData = gentBale; heelX = gentHeelX; heelY = gentHeelY; heelData = gentHeel; realYSize = 22; baleStart = gentBaleStart; baleEnd = gentBaleEnd; baleTapStart = 0; baleTapEnd = 5; } else if (type == 1) { baleX = ladyBaleX; baleY = ladyBaleY; baleData = ladyBale; heelX = ladyHeelX; heelY = ladyHeelY; heelData = ladyHeel; realYSize = 21; baleStart = ladyBaleStart; baleEnd = ladyBaleEnd; baleTapStart = 1; baleTapEnd = 7; } for (int i=0;i<baleData.length;i+=2) { if (baleData[i+1] < minY) minY = baleData[i+1]; else if (baleData[i+1] > maxY) maxY = baleData[i+1]; } for (int i=0;i<baleData.length;i+=2) { if (baleData[i+1] < minY) minY = heelData[i+1]; else if (baleData[i+1] > maxY) maxY = heelData[i+1]; } feetDataYSize = maxY - minY + 1; } public int [] getBale() { int length = baleEnd - baleStart + 1; int array[] = new int[length*2]; for (int i=0;i<length*2;i++) { array[i]=baleData[i + baleStart*2]; } return array; } public int[] getBaleTap() { int length = baleTapEnd - baleTapStart + 1; int array[] = new int[length*2]; for (int i=0;i<length*2;i++) { array[i]=baleData[i + baleTapStart*2]; } return array; } public int [] getHeel() { return heelData; } }
Calculate the y size of the feet corectly. Adjusted real size accordingly.
src/main/java/GraphicsData.java
Calculate the y size of the feet corectly. Adjusted real size accordingly.
Java
lgpl-2.1
9a199ebaf8c1bf65dc4e7d556c48969acc890081
0
netarchivesuite/netarchivesuite-svngit-migration,netarchivesuite/netarchivesuite-svngit-migration,netarchivesuite/netarchivesuite-svngit-migration,netarchivesuite/netarchivesuite-svngit-migration,netarchivesuite/netarchivesuite-svngit-migration,netarchivesuite/netarchivesuite-svngit-migration
/*$Id$ * $Revision$ * $Author$ * $Date$ * * The Netarchive Suite - Software to harvest and preserve websites * Copyright 2004-2012 The Royal Danish Library, the Danish State and * University Library, the National Library of France and the Austrian * National Library. * * 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 dk.netarkivet.common; import java.text.SimpleDateFormat; import java.util.regex.Pattern; /** * This class is used for global constants only. * * If your constant is only to be used in a single package, put it in a * Constants-class in that package, and make sure it is package private (no * modifiers). * * If your constant is used in a single class only, put it in that class, and * make sure it is private. * * Remember everything placed here MUST be constants. * * This class is never instantiated, so thread security is not an issue. * */ public final class Constants { /** The pattern for an IP-address key. */ public static final String IP_REGEX_STRING = "[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}"; /** A full string matcher for an IP-address. */ public static final Pattern IP_KEY_REGEXP = Pattern.compile("^" + IP_REGEX_STRING + "$"); /** A full string matcher for an IPv6-address. */ public static final Pattern IPv6_KEY_REGEXP = Pattern.compile("^([0-9A-F]{1,2}\\:){5}[0-9A-F]{1,2}$"); /** * The suffix of a regular expression that matches the metadata files. * Add job IDs to the front as necessary. */ public static final String METADATA_FILE_PATTERN_SUFFIX = "-metadata-[0-9]+.arc"; /** The mimetype for a list of CDX entries. */ public static final String CDX_MIME_TYPE = "application/x-cdx"; /** Possible states of code. */ private static enum CodeStatus { /** Released code. */ RELEASE, /** Code is under codefreeze. The code is a release candidate. */ CODEFREEZE, /** The code is not production ready. Although it usually compiles, * all code has not necessarily been tested. */ UNSTABLE } /** Extension of XML file names. */ public static final String XML_EXTENSION = ".xml"; //It is QA's responsibility to update the following parameters on all // release and codefreeze actions /** Major version number. */ public static final int MAJORVERSION = 3; /** Minor version number. */ public static final int MINORVERSION = 19; /** Patch version number. */ public static final int PATCHVERSION = 0; /** Current status of code. */ private static final CodeStatus BUILDSTATUS = CodeStatus.CODEFREEZE; /** Current version of Heritrix used by netarkivet-code. */ private static final String HERITRIX_VERSION = "1.14.4"; /** * Read this much data when copying data from a file channel. Note that due * to a bug in java, this should never be set larger than Integer.MAX_VALUE, * since a call to fileChannel.transferFrom/To fails with an error while * calling mmap. */ public static final long IO_CHUNK_SIZE = 65536L; /** The directory name of the heritrix directory with arcfiles. */ public static final String ARCDIRECTORY_NAME = "arcs"; /** * How big a buffer we use for read()/write() operations on InputStream/ * OutputStream. */ public static final int IO_BUFFER_SIZE = 4096; /** * The organization behind the harvesting. Only used by the * HarvestDocumentation class */ public static final String ORGANIZATION_NAME = "netarkivet.dk"; /** The date format used for NetarchiveSuite dateformatting. */ private static final String ISO_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss Z"; /** Internationalisation resource bundle for common module. */ public static final String TRANSLATIONS_BUNDLE = "dk.netarkivet.common.Translations"; /** * Private constructor that does absolutely nothing. Necessary in order to * prevent initialization. */ private Constants() { //Not to be initialised } /** * Get a human-readable version string. * * @return A string telling current version and status of code. */ public static String getVersionString() { if (BUILDSTATUS.equals(CodeStatus.RELEASE)) { return "Version: " + MAJORVERSION + "." + MINORVERSION + "." + PATCHVERSION + " status " + BUILDSTATUS; } else { String version = "Version: " + MAJORVERSION + "." + MINORVERSION + "." + PATCHVERSION + " status " + BUILDSTATUS; String implementationVersion = Constants.class.getPackage() .getImplementationVersion(); if (implementationVersion != null) { version += " (r" + implementationVersion + ")"; } return version; } } /** * Get the Heritrix version presently in use. * * @return the Heritrix version presently in use */ public static String getHeritrixVersionString() { return HERITRIX_VERSION; } /** * Get a formatter that can read and write a date in ISO format including * hours/minutes/seconds and timezone. * * @return The formatter. */ public static SimpleDateFormat getIsoDateFormatter() { return new SimpleDateFormat(ISO_DATE_FORMAT); } /** One minute in milliseconds. */ public static final long ONE_MIN_IN_MILLIES = 60 * 1000; /** One day in milliseconds. */ public static final long ONE_DAY_IN_MILLIES = 24 * 60 * ONE_MIN_IN_MILLIES; /** Pattern that matches our our CDX mimetype. */ public static final String CDX_MIME_PATTERN = "application/x-cdx"; /** Pattern that matches everything. */ public static final String ALL_PATTERN = ".*"; }
src/dk/netarkivet/common/Constants.java
/*$Id$ * $Revision$ * $Author$ * $Date$ * * The Netarchive Suite - Software to harvest and preserve websites * Copyright 2004-2012 The Royal Danish Library, the Danish State and * University Library, the National Library of France and the Austrian * National Library. * * 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 dk.netarkivet.common; import java.text.SimpleDateFormat; import java.util.regex.Pattern; /** * This class is used for global constants only. * * If your constant is only to be used in a single package, put it in a * Constants-class in that package, and make sure it is package private (no * modifiers). * * If your constant is used in a single class only, put it in that class, and * make sure it is private * * Remember everything placed here MUST be constants. * * This class is never instantiated, so thread security is not an issue. * */ public final class Constants { /** The pattern for an IP-address key. */ public static final String IP_REGEX_STRING = "[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}"; /** A full string matcher for an IP-address. */ public static final Pattern IP_KEY_REGEXP = Pattern.compile("^" + IP_REGEX_STRING + "$"); /** A full string matcher for an IPv6-address. */ public static final Pattern IPv6_KEY_REGEXP = Pattern.compile("^([0-9A-F]{1,2}\\:){5}[0-9A-F]{1,2}$"); /** * The suffix of a regular expression that matches the metadata files. * Add job IDs to the front as necessary. */ public static final String METADATA_FILE_PATTERN_SUFFIX = "-metadata-[0-9]+.arc"; /** The mimetype for a list of CDX entries. */ public static final String CDX_MIME_TYPE = "application/x-cdx"; /** Possible states of code. */ private static enum CodeStatus { /** Released code. */ RELEASE, /** Code is under codefreeze. The code is a release candidate. */ CODEFREEZE, /** The code is not production ready. Although it usually compiles, * all code has not necessarily been tested. */ UNSTABLE } /** Extension of XML file names. */ public static final String XML_EXTENSION = ".xml"; //It is QA's responsibility to update the following parameters on all // release and codefreeze actions /** Major version number. */ public static final int MAJORVERSION = 3; /** Minor version number. */ public static final int MINORVERSION = 19; /** Patch version number. */ public static final int PATCHVERSION = 0; /** Current status of code. */ private static final CodeStatus BUILDSTATUS = CodeStatus.UNSTABLE; /** Current version of Heritrix used by netarkivet-code. */ private static final String HERITRIX_VERSION = "1.14.4"; /** * Read this much data when copying data from a file channel. Note that due * to a bug in java, this should never be set larger than Integer.MAX_VALUE, * since a call to fileChannel.transferFrom/To fails with an error while * calling mmap. */ public static final long IO_CHUNK_SIZE = 65536L; /** The directory name of the heritrix directory with arcfiles. */ public static final String ARCDIRECTORY_NAME = "arcs"; /** * How big a buffer we use for read()/write() operations on InputStream/ * OutputStream. */ public static final int IO_BUFFER_SIZE = 4096; /** * The organization behind the harvesting. Only used by the * HarvestDocumentation class */ public static final String ORGANIZATION_NAME = "netarkivet.dk"; /** The date format used for NetarchiveSuite dateformatting. */ private static final String ISO_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss Z"; /** Internationalisation resource bundle for common module. */ public static final String TRANSLATIONS_BUNDLE = "dk.netarkivet.common.Translations"; /** * Private constructor that does absolutely nothing. Necessary in order to * prevent initialization. */ private Constants() { //Not to be initialised } /** * Get a human-readable version string. * * @return A string telling current version and status of code. */ public static String getVersionString() { if (BUILDSTATUS.equals(CodeStatus.RELEASE)) { return "Version: " + MAJORVERSION + "." + MINORVERSION + "." + PATCHVERSION + " status " + BUILDSTATUS; } else { String version = "Version: " + MAJORVERSION + "." + MINORVERSION + "." + PATCHVERSION + " status " + BUILDSTATUS; String implementationVersion = Constants.class.getPackage() .getImplementationVersion(); if (implementationVersion != null) { version += " (r" + implementationVersion + ")"; } return version; } } /** * Get the Heritrix version presently in use. * * @return the Heritrix version presently in use */ public static String getHeritrixVersionString() { return HERITRIX_VERSION; } /** * Get a formatter that can read and write a date in ISO format including * hours/minutes/seconds and timezone. * * @return The formatter. */ public static SimpleDateFormat getIsoDateFormatter() { return new SimpleDateFormat(ISO_DATE_FORMAT); } /** One minute in milliseconds. */ public static final long ONE_MIN_IN_MILLIES = 60 * 1000; /** One day in milliseconds. */ public static final long ONE_DAY_IN_MILLIES = 24 * 60 * ONE_MIN_IN_MILLIES; /** Pattern that matches our our CDX mimetype. */ public static final String CDX_MIME_PATTERN = "application/x-cdx"; /** Pattern that matches everything. */ public static final String ALL_PATTERN = ".*"; }
CODEFREEZE for development release 3.19.0 now in effect
src/dk/netarkivet/common/Constants.java
CODEFREEZE for development release 3.19.0 now in effect
Java
lgpl-2.1
cb8fca52e7b32e3ca3c541551e7ff5b1136c2be3
0
guillaume-alvarez/ShapeOfThingsThatWere
package com.galvarez.ttw.screens; import static java.lang.Math.max; import static java.lang.String.format; import java.util.Map; import java.util.Map.Entry; import com.artemis.Entity; import com.artemis.World; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.galvarez.ttw.ThingsThatWereGame; import com.galvarez.ttw.model.DiscoverySystem; import com.galvarez.ttw.model.Faction; import com.galvarez.ttw.model.components.Discoveries; import com.galvarez.ttw.model.components.InfluenceSource; import com.galvarez.ttw.model.components.Research; import com.galvarez.ttw.model.data.Discovery; import com.galvarez.ttw.model.map.Terrain; import com.galvarez.ttw.rendering.ui.FramedMenu; import com.galvarez.ttw.screens.overworld.OverworldScreen; /** * This screen appears when user tries to pause or escape from the main game * screen. * * @author Guillaume Alvarez */ public final class DiscoveryMenuScreen extends AbstractPausedScreen<OverworldScreen> { private final FramedMenu topMenu, lastDiscovery, terrains, discoveryChoices; private final Discoveries empire; private final InfluenceSource source; private final DiscoverySystem discoverySystem; private final Entity entity; public DiscoveryMenuScreen(ThingsThatWereGame game, World world, SpriteBatch batch, OverworldScreen gameScreen, Entity empire, DiscoverySystem discoverySystem) { super(game, world, batch, gameScreen); this.entity = empire; this.empire = empire.getComponent(Discoveries.class); this.source = empire.getComponent(InfluenceSource.class); this.discoverySystem = discoverySystem; topMenu = new FramedMenu(skin, 800, 600); lastDiscovery = new FramedMenu(skin, 800, 600); terrains = new FramedMenu(skin, 800, 600); discoveryChoices = new FramedMenu(skin, 800, 600); } @Override protected void initMenu() { topMenu.clear(); topMenu.addButton("Resume game", this::resumeGame); topMenu.addToStage(stage, 30, stage.getHeight() - 30, false); lastDiscovery.clear(); if (empire.last == null) { lastDiscovery.addLabel("- No last discovery -"); } else { lastDiscovery.addLabel("- Last discovery (effect doubled): " + empire.last.target.name + " -"); lastDiscovery.addLabel("Discovered from " + previousString(empire.last)); lastDiscovery.addLabel("Effects:"); for (String effect : discoverySystem.effectsStrings(empire.last.target)) lastDiscovery.addLabel(" - " + effect); } lastDiscovery.addToStage(stage, 30, topMenu.getY() - 30, false); terrains.clear(); terrains.addLabel("- Terrains influence costs -"); for (Terrain t : Terrain.values()) { Integer mod = source.modifiers.terrainBonus.get(t); int cost = max(1, mod != null ? t.moveCost() - mod : t.moveCost()); terrains.addLabel(format("%s: %d (%s)", t.getDesc(), cost, mod != null && mod != 0 ? -mod : "no modifier")); } terrains.addToStage(stage, 30, lastDiscovery.getY() - 30, false); discoveryChoices.clear(); if (empire.next != null) { discoveryChoices.addLabel("Progress toward new discovery from " + previousString(empire.next) + ": " + empire.next.progress + "% (+" + empire.progressPerTurn + "%/turn)"); discoveryChoices.addLabel(" "); discoveryChoices.addButton("Change discovery (progress will be reset)!", this::changeResearch); } else { Map<Faction, Research> possible = discoverySystem.possibleDiscoveries(entity, empire); if (possible.isEmpty()) { discoveryChoices.addLabel("No discoveries to combine!"); } else { discoveryChoices.addLabel("Which faction do you choose to make new discoveries?"); for (Entry<Faction, Research> next : possible.entrySet()) discoveryChoices.addButton( action(next.getKey()), previousString(next.getValue()) + " (~" + discoverySystem.guessNbTurns(empire, entity, next.getValue().target) + " turns)", // new Runnable() { @Override public void run() { empire.next = next.getValue(); resumeGame(); } }, true); } } discoveryChoices.addToStage(stage, 30, terrains.getY() - 30, false); } private static String action(Faction faction) { switch (faction) { case CULTURAL: return "Cultural faction advises to meditate on "; case ECONOMIC: return "Economic faction recommends we pursue profit in "; case MILITARY: return "Military faction commands us to investigate "; default: throw new IllegalStateException("Unknown faction " + faction); } } private static String previousString(Research next) { if (next.previous.isEmpty()) return "our environment"; StringBuilder sb = new StringBuilder(); for (Discovery previous : next.previous) sb.append(previous.name).append(", "); sb.setLength(sb.length() - 2); return sb.toString(); } private void changeResearch() { empire.next = null; initMenu(); } }
core/src/com/galvarez/ttw/screens/DiscoveryMenuScreen.java
package com.galvarez.ttw.screens; import static java.lang.Math.max; import static java.lang.String.format; import java.util.Map; import java.util.Map.Entry; import com.artemis.Entity; import com.artemis.World; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.galvarez.ttw.ThingsThatWereGame; import com.galvarez.ttw.model.DiscoverySystem; import com.galvarez.ttw.model.Faction; import com.galvarez.ttw.model.components.Discoveries; import com.galvarez.ttw.model.components.InfluenceSource; import com.galvarez.ttw.model.components.Research; import com.galvarez.ttw.model.data.Discovery; import com.galvarez.ttw.model.map.Terrain; import com.galvarez.ttw.rendering.ui.FramedMenu; import com.galvarez.ttw.screens.overworld.OverworldScreen; /** * This screen appears when user tries to pause or escape from the main game * screen. * * @author Guillaume Alvarez */ public final class DiscoveryMenuScreen extends AbstractPausedScreen<OverworldScreen> { private final FramedMenu topMenu, lastDiscovery, terrains, discoveryChoices; private final Discoveries empire; private final InfluenceSource source; private final DiscoverySystem discoverySystem; private final Entity entity; public DiscoveryMenuScreen(ThingsThatWereGame game, World world, SpriteBatch batch, OverworldScreen gameScreen, Entity empire, DiscoverySystem discoverySystem) { super(game, world, batch, gameScreen); this.entity = empire; this.empire = empire.getComponent(Discoveries.class); this.source = empire.getComponent(InfluenceSource.class); this.discoverySystem = discoverySystem; topMenu = new FramedMenu(skin, 800, 600); lastDiscovery = new FramedMenu(skin, 800, 600); terrains = new FramedMenu(skin, 800, 600); discoveryChoices = new FramedMenu(skin, 800, 600); } @Override protected void initMenu() { topMenu.clear(); topMenu.addButton("Resume game", this::resumeGame); topMenu.addToStage(stage, 30, stage.getHeight() - 30, false); lastDiscovery.clear(); if (empire.last == null) { lastDiscovery.addLabel("- No last discovery -"); } else { lastDiscovery.addLabel("- Last discovery (effect doubled): " + empire.last.target.name + " -"); lastDiscovery.addLabel("Discovered from " + previousString(empire.last)); lastDiscovery.addLabel("Effects:"); for (String effect : discoverySystem.effectsStrings(empire.last.target)) lastDiscovery.addLabel(" - " + effect); } lastDiscovery.addToStage(stage, 30, topMenu.getY() - 30, false); terrains.clear(); terrains.addLabel("- Terrains influence costs -"); for (Terrain t : Terrain.values()) { Integer mod = source.modifiers.terrainBonus.get(t); int cost = max(1, mod != null ? t.moveCost() - mod : t.moveCost()); terrains.addLabel(format("%s: %d (%s)", t.getDesc(), cost, mod != null && mod != 0 ? -mod : "no modifier")); } terrains.addToStage(stage, 30, lastDiscovery.getY() - 30, false); discoveryChoices.clear(); if (empire.next != null) { discoveryChoices.addLabel("Progress toward new discovery from " + previousString(empire.next) + ": " + empire.next.progress + "% (+" + empire.progressPerTurn + "%/turn)"); } else { Map<Faction, Research> possible = discoverySystem.possibleDiscoveries(entity, empire); if (possible.isEmpty()) { discoveryChoices.addLabel("No discoveries to combine!"); } else { discoveryChoices.addLabel("Which faction do you choose to make new discoveries?"); for (Entry<Faction, Research> next : possible.entrySet()) discoveryChoices.addButton( action(next.getKey()), previousString(next.getValue()) + " (~" + discoverySystem.guessNbTurns(empire, entity, next.getValue().target) + " turns)", // new Runnable() { @Override public void run() { empire.next = next.getValue(); resumeGame(); } }, true); } } discoveryChoices.addToStage(stage, 30, terrains.getY() - 30, false); } private static String action(Faction faction) { switch (faction) { case CULTURAL: return "Cultural faction advises to meditate on "; case ECONOMIC: return "Economic faction recommends we pursue profit in "; case MILITARY: return "Military faction commands us to investigate "; default: throw new IllegalStateException("Unknown faction " + faction); } } private static String previousString(Research next) { if (next.previous.isEmpty()) return "our environment"; StringBuilder sb = new StringBuilder(); for (Discovery previous : next.previous) sb.append(previous.name).append(", "); sb.setLength(sb.length() - 2); return sb.toString(); } }
Let change current research, fix #38.
core/src/com/galvarez/ttw/screens/DiscoveryMenuScreen.java
Let change current research, fix #38.
Java
lgpl-2.1
4db0ae21fbdafdd5ad40154320d378bc462b26e8
0
netarchivesuite/netarchivesuite-svngit-migration,netarchivesuite/netarchivesuite-svngit-migration,netarchivesuite/netarchivesuite-svngit-migration,netarchivesuite/netarchivesuite-svngit-migration,netarchivesuite/netarchivesuite-svngit-migration,netarchivesuite/netarchivesuite-svngit-migration
/*$Id$ * $Revision$ * $Author$ * $Date$ * * The Netarchive Suite - Software to harvest and preserve websites * Copyright 2004-2007 Det Kongelige Bibliotek and Statsbiblioteket, Denmark * * 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 dk.netarkivet.common; import java.text.SimpleDateFormat; import java.util.regex.Pattern; /** * This class is used for global constants only. * * If your constant is only to be used in a single package, put it in a * Constants-class in that package, and make sure it is package private * (no modifiers). * * If your constant is used in a single class only, put it in that class, * and make sure it is private * * Remember everything placed here MUST be constants. * * This class is never instantiated, so thread security is not an issue. * * Date: Feb 15, 2005 * Time: 6:04:25 PM */ public class Constants { /** The pattern for an IP-address key. */ public static final String IP_REGEX_STRING = "[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}"; /** A full string matcher for an IP-address. */ public static final Pattern IP_KEY_REGEXP = Pattern.compile("^" + IP_REGEX_STRING + "$"); /** A full string matcher for an IPv6-address. */ public static final Pattern IPv6_KEY_REGEXP = Pattern.compile("^([0-9A-F]{1,2}\\:){5}[0-9A-F]{1,2}$"); /** The suffic of a regexp that matches the metadata files. Add * job IDs to the front as necessary. */ public static final String METADATA_FILE_PATTERN_SUFFIX = "-metadata-[0-9]+.arc"; public static final String CDX_MIME_TYPE = "application/x-cdx"; public static final String WEBINTERFACE_LANGUAGE = "language"; public static final String WEBINTERFACE_LANGUAGE_LOCALE = "locale"; public static final String WEBINTERFACE_LANGUAGE_NAME = "name"; /** Possible states of code. */ private static enum CodeStatus {RELEASE, CODEFREEZE, UNSTABLE} /** Extension of xml file names. */ public static final String XML_EXTENSION = ".xml"; //It is QA's responsibility to update the following parameters on all release //and codefreeze actions /** Major version number. */ public static final int MAJORVERSION = 3; /** Minor version number. */ public static final int MINORVERSION = 5; /** Patch version number. */ public static final int PATCHVERSION = 1; /** Current status of code. */ private static final CodeStatus BUILDSTATUS = CodeStatus.CODEFREEZE; /** Current version of Heritrix used by netarkivet-code. */ private static final String HERITRIX_VERSION = "1.12.1b"; /** Read this much data when copying data from a file channel. * Note that due to a bug in java, this should never be set larger * than Integer.MAX_VALUE, since a call to fileChannel.transferFrom/To * fails with an error while calling mmap. */ public static final long IO_CHUNK_SIZE = 65536L; /** The dirname of the heritrix directory with arcfiles */ public static final String ARCDIRECTORY_NAME = "arcs"; /** How big a buffer we use for read()/write() operations on InputStream/ * OutputStream. */ public static final int IO_BUFFER_SIZE = 4096; public static final String ORGANIZATION_NAME = "netarkivet.dk"; private static final String ISO_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss Z"; /** * Internationalisation resource bundle for common module. */ public static final String TRANSLATIONS_BUNDLE = "dk.netarkivet.common.Translations"; private Constants() { //Not to be initialised } /** Get a human-readable version string. * @return A string telling current version and status of code. * */ public static String getVersionString() { return "Version: " + MAJORVERSION + "." + MINORVERSION + "." + PATCHVERSION + " status " + BUILDSTATUS; } /** * Get the Heritrix version presently in use. * @return the Heritrix version presently in use */ public static String getHeritrixVersionString() { return HERITRIX_VERSION; } /** Get a formatter that can read and write a date in ISO format including * hours/minutes/seconds and timezone. * @return The formatter. * */ public static SimpleDateFormat getIsoDateFormatter() { return new SimpleDateFormat(ISO_DATE_FORMAT); } }
src/dk/netarkivet/common/Constants.java
/*$Id$ * $Revision$ * $Author$ * $Date$ * * The Netarchive Suite - Software to harvest and preserve websites * Copyright 2004-2007 Det Kongelige Bibliotek and Statsbiblioteket, Denmark * * 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 dk.netarkivet.common; import java.text.SimpleDateFormat; import java.util.regex.Pattern; /** * This class is used for global constants only. * * If your constant is only to be used in a single package, put it in a * Constants-class in that package, and make sure it is package private * (no modifiers). * * If your constant is used in a single class only, put it in that class, * and make sure it is private * * Remember everything placed here MUST be constants. * * This class is never instantiated, so thread security is not an issue. * * Date: Feb 15, 2005 * Time: 6:04:25 PM */ public class Constants { /** The pattern for an IP-address key. */ public static final String IP_REGEX_STRING = "[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}"; /** A full string matcher for an IP-address. */ public static final Pattern IP_KEY_REGEXP = Pattern.compile("^" + IP_REGEX_STRING + "$"); /** A full string matcher for an IPv6-address. */ public static final Pattern IPv6_KEY_REGEXP = Pattern.compile("^([0-9A-F]{1,2}\\:){5}[0-9A-F]{1,2}$"); /** The suffic of a regexp that matches the metadata files. Add * job IDs to the front as necessary. */ public static final String METADATA_FILE_PATTERN_SUFFIX = "-metadata-[0-9]+.arc"; public static final String CDX_MIME_TYPE = "application/x-cdx"; public static final String WEBINTERFACE_LANGUAGE = "language"; public static final String WEBINTERFACE_LANGUAGE_LOCALE = "locale"; public static final String WEBINTERFACE_LANGUAGE_NAME = "name"; /** Possible states of code. */ private static enum CodeStatus {RELEASE, CODEFREEZE, UNSTABLE} /** Extension of xml file names. */ public static final String XML_EXTENSION = ".xml"; //It is QA's responsibility to update the following parameters on all release //and codefreeze actions /** Major version number. */ public static final int MAJORVERSION = 3; /** Minor version number. */ public static final int MINORVERSION = 5; /** Patch version number. */ public static final int PATCHVERSION = 1; /** Current status of code. */ private static final CodeStatus BUILDSTATUS = CodeStatus.UNSTABLE; /** Current version of Heritrix used by netarkivet-code. */ private static final String HERITRIX_VERSION = "1.12.1b"; /** Read this much data when copying data from a file channel. * Note that due to a bug in java, this should never be set larger * than Integer.MAX_VALUE, since a call to fileChannel.transferFrom/To * fails with an error while calling mmap. */ public static final long IO_CHUNK_SIZE = 65536L; /** The dirname of the heritrix directory with arcfiles */ public static final String ARCDIRECTORY_NAME = "arcs"; /** How big a buffer we use for read()/write() operations on InputStream/ * OutputStream. */ public static final int IO_BUFFER_SIZE = 4096; public static final String ORGANIZATION_NAME = "netarkivet.dk"; private static final String ISO_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss Z"; /** * Internationalisation resource bundle for common module. */ public static final String TRANSLATIONS_BUNDLE = "dk.netarkivet.common.Translations"; private Constants() { //Not to be initialised } /** Get a human-readable version string. * @return A string telling current version and status of code. * */ public static String getVersionString() { return "Version: " + MAJORVERSION + "." + MINORVERSION + "." + PATCHVERSION + " status " + BUILDSTATUS; } /** * Get the Heritrix version presently in use. * @return the Heritrix version presently in use */ public static String getHeritrixVersionString() { return HERITRIX_VERSION; } /** Get a formatter that can read and write a date in ISO format including * hours/minutes/seconds and timezone. * @return The formatter. * */ public static SimpleDateFormat getIsoDateFormatter() { return new SimpleDateFormat(ISO_DATE_FORMAT); } }
Codefreeze for 3.5.1 (will be released as 3.6.0)
src/dk/netarkivet/common/Constants.java
Codefreeze for 3.5.1 (will be released as 3.6.0)
Java
lgpl-2.1
a944d4d75cb928348dd9ca24fea68bd8ef3fcf97
0
cwarden/kettle,juanmjacobs/kettle,juanmjacobs/kettle,cwarden/kettle,cwarden/kettle,juanmjacobs/kettle
/* Copyright (c) 2007 Pentaho Corporation. All rights reserved. * This software was developed by Pentaho Corporation and is provided under the terms * of the GNU Lesser General Public License, Version 2.1. You may not use * this file except in compliance with the license. If you need a copy of the license, * please go to http://www.gnu.org/licenses/lgpl-2.1.txt. The Original Code is Pentaho * Data Integration. The Initial Developer is Pentaho Corporation. * * Software distributed under the GNU Lesser Public License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. Please refer to * the license for the specific language governing your rights and limitations.*/ package org.pentaho.di.trans; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.Hashtable; import java.util.List; import java.util.Map; import org.apache.commons.vfs.FileName; import org.apache.commons.vfs.FileObject; import org.apache.commons.vfs.FileSystemException; import org.pentaho.di.cluster.ClusterSchema; import org.pentaho.di.cluster.SlaveServer; import org.pentaho.di.core.CheckResult; import org.pentaho.di.core.CheckResultInterface; import org.pentaho.di.core.Const; import org.pentaho.di.core.Counter; import org.pentaho.di.core.DBCache; import org.pentaho.di.core.EngineMetaInterface; import org.pentaho.di.core.LastUsedFile; import org.pentaho.di.core.NotePadMeta; import org.pentaho.di.core.ProgressMonitorListener; import org.pentaho.di.core.Props; import org.pentaho.di.core.Result; import org.pentaho.di.core.ResultFile; import org.pentaho.di.core.RowMetaAndData; import org.pentaho.di.core.SQLStatement; import org.pentaho.di.core.changed.ChangedFlag; import org.pentaho.di.core.database.Database; import org.pentaho.di.core.database.DatabaseMeta; import org.pentaho.di.core.exception.KettleDatabaseException; import org.pentaho.di.core.exception.KettleException; import org.pentaho.di.core.exception.KettleRowException; import org.pentaho.di.core.exception.KettleStepException; import org.pentaho.di.core.exception.KettleXMLException; import org.pentaho.di.core.gui.GUIPositionInterface; import org.pentaho.di.core.gui.Point; import org.pentaho.di.core.gui.SpoonFactory; import org.pentaho.di.core.gui.UndoInterface; import org.pentaho.di.core.logging.LogWriter; import org.pentaho.di.core.reflection.StringSearchResult; import org.pentaho.di.core.reflection.StringSearcher; import org.pentaho.di.core.row.RowMeta; import org.pentaho.di.core.row.RowMetaInterface; import org.pentaho.di.core.row.ValueMeta; import org.pentaho.di.core.row.ValueMetaInterface; import org.pentaho.di.core.undo.TransAction; import org.pentaho.di.core.util.StringUtil; import org.pentaho.di.core.variables.VariableSpace; import org.pentaho.di.core.variables.Variables; import org.pentaho.di.core.vfs.KettleVFS; import org.pentaho.di.core.xml.XMLHandler; import org.pentaho.di.core.xml.XMLInterface; import org.pentaho.di.partition.PartitionSchema; import org.pentaho.di.repository.Repository; import org.pentaho.di.repository.RepositoryDirectory; import org.pentaho.di.resource.ResourceDefinition; import org.pentaho.di.resource.ResourceExportInterface; import org.pentaho.di.resource.ResourceNamingInterface; import org.pentaho.di.resource.ResourceReference; import org.pentaho.di.shared.SharedObjectInterface; import org.pentaho.di.shared.SharedObjects; import org.pentaho.di.trans.step.BaseStep; import org.pentaho.di.trans.step.StepErrorMeta; import org.pentaho.di.trans.step.StepMeta; import org.pentaho.di.trans.step.StepMetaInterface; import org.pentaho.di.trans.step.StepPartitioningMeta; import org.pentaho.di.trans.steps.mapping.MappingMeta; import org.w3c.dom.Document; import org.w3c.dom.Node; /** * This class defines a transformation and offers methods to save and load it * from XML or a PDI database repository. * * @since 20-jun-2003 * @author Matt */ public class TransMeta extends ChangedFlag implements XMLInterface, Comparator<TransMeta>, Comparable<TransMeta>, Cloneable, UndoInterface, HasDatabasesInterface, VariableSpace, EngineMetaInterface, ResourceExportInterface, HasSlaveServersInterface { public static final String XML_TAG = "transformation"; private static LogWriter log = LogWriter.getInstance(); // private List inputFiles; private List<DatabaseMeta> databases; private List<StepMeta> steps; private List<TransHopMeta> hops; private List<NotePadMeta> notes; private List<TransDependency> dependencies; private List<SlaveServer> slaveServers; private List<ClusterSchema> clusterSchemas; private List<PartitionSchema> partitionSchemas; private RepositoryDirectory directory; private RepositoryDirectory directoryTree; private String name; private String description; private String extended_description; private String trans_version; private int trans_status; private String filename; private StepMeta readStep; private StepMeta writeStep; private StepMeta inputStep; private StepMeta outputStep; private StepMeta updateStep; private StepMeta rejectedStep; private String logTable; private DatabaseMeta logConnection; private int sizeRowset; private DatabaseMeta maxDateConnection; private String maxDateTable; private String maxDateField; private double maxDateOffset; private double maxDateDifference; private String arguments[]; private Hashtable<String,Counter> counters; private boolean changed_steps, changed_databases, changed_hops, changed_notes; private List<TransAction> undo; private int max_undo; private int undo_position; private DBCache dbCache; private long id; private boolean useBatchId; private boolean logfieldUsed; private String createdUser, modifiedUser; private Date createdDate, modifiedDate; private int sleepTimeEmpty; private int sleepTimeFull; private Result previousResult; private List<RowMetaAndData> resultRows; private List<ResultFile> resultFiles; private boolean usingUniqueConnections; private boolean feedbackShown; private int feedbackSize; /** flag to indicate thread management usage. Set to default to false from version 2.5.0 on. Before that it was enabled by default. */ private boolean usingThreadPriorityManagment; /** If this is null, we load from the default shared objects file : $KETTLE_HOME/.kettle/shared.xml */ private String sharedObjectsFile; /** The last load of the shared objects file by this TransMet object */ private SharedObjects sharedObjects; private VariableSpace variables = new Variables(); /** The slave-step-copy/partition distribution. Only used for slave transformations in a clustering environment. */ private SlaveStepCopyPartitionDistribution slaveStepCopyPartitionDistribution; /** Just a flag indicating that this is a slave transformation - internal use only, no GUI option */ private boolean slaveTransformation; /** The repository to reference in the one-off case that it is needed */ private Repository repository; private boolean capturingStepPerformanceSnapShots; private long stepPerformanceCapturingDelay; private Map<String, RowMetaInterface> stepsFieldsCache; // ////////////////////////////////////////////////////////////////////////// public static final int TYPE_UNDO_CHANGE = 1; public static final int TYPE_UNDO_NEW = 2; public static final int TYPE_UNDO_DELETE = 3; public static final int TYPE_UNDO_POSITION = 4; public static final String desc_type_undo[] = { "", Messages.getString("TransMeta.UndoTypeDesc.UndoChange"), Messages.getString("TransMeta.UndoTypeDesc.UndoNew"), Messages.getString("TransMeta.UndoTypeDesc.UndoDelete"), Messages.getString("TransMeta.UndoTypeDesc.UndoPosition") }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ private static final String XML_TAG_INFO = "info"; private static final String XML_TAG_ORDER = "order"; private static final String XML_TAG_NOTEPADS = "notepads"; private static final String XML_TAG_DEPENDENCIES = "dependencies"; private static final String XML_TAG_PARTITIONSCHEMAS = "partitionschemas"; private static final String XML_TAG_SLAVESERVERS = "slaveservers"; private static final String XML_TAG_CLUSTERSCHEMAS = "clusterschemas"; private static final String XML_TAG_STEP_ERROR_HANDLING = "step_error_handling"; /** * Builds a new empty transformation. */ public TransMeta() { clear(); initializeVariablesFrom(null); } /** * Builds a new empty transformation with a set of variables to inherit from. * @param parent the variable space to inherit from */ public TransMeta(VariableSpace parent) { clear(); initializeVariablesFrom(parent); } /** * Constructs a new transformation specifying the filename, name and arguments. * * @param filename The filename of the transformation * @param name The name of the transformation * @param arguments The arguments as Strings */ public TransMeta(String filename, String name, String arguments[]) { clear(); this.filename = filename; this.name = name; this.arguments = arguments; initializeVariablesFrom(null); } /** * Compares two transformation on name, filename */ public int compare(TransMeta t1, TransMeta t2) { if (Const.isEmpty(t1.getName()) && !Const.isEmpty(t2.getName())) return -1; if (!Const.isEmpty(t1.getName()) && Const.isEmpty(t2.getName())) return 1; if (Const.isEmpty(t1.getName()) && Const.isEmpty(t2.getName())) { if (Const.isEmpty(t1.getFilename()) && !Const.isEmpty(t2.getFilename())) return -1; if (!Const.isEmpty(t1.getFilename()) && Const.isEmpty(t2.getFilename())) return 1; if (Const.isEmpty(t1.getFilename()) && Const.isEmpty(t2.getFilename())) { return 0; } return t1.getFilename().compareTo(t2.getFilename()); } return t1.getName().compareTo(t2.getName()); } public int compareTo(TransMeta o) { return compare(this, o); } public boolean equals(Object obj) { if (!(obj instanceof TransMeta)) return false; return compare(this, (TransMeta)obj)==0; } @Override public Object clone() { return realClone(true); } public Object realClone(boolean doClear) { try { TransMeta transMeta = (TransMeta) super.clone(); if (doClear) { transMeta.clear(); } else { // Clear out the things we're replacing below transMeta.databases = new ArrayList<DatabaseMeta>(); transMeta.steps = new ArrayList<StepMeta>(); transMeta.hops = new ArrayList<TransHopMeta>(); transMeta.notes = new ArrayList<NotePadMeta>(); transMeta.dependencies = new ArrayList<TransDependency>(); transMeta.partitionSchemas = new ArrayList<PartitionSchema>(); transMeta.slaveServers = new ArrayList<SlaveServer>(); transMeta.clusterSchemas = new ArrayList<ClusterSchema>(); } for (DatabaseMeta db : databases) transMeta.addDatabase((DatabaseMeta)db.clone()); for (StepMeta step : steps) transMeta.addStep((StepMeta) step.clone()); for (TransHopMeta hop : hops) transMeta.addTransHop((TransHopMeta) hop.clone()); for (NotePadMeta note : notes) transMeta.addNote((NotePadMeta)note.clone()); for (TransDependency dep : dependencies) transMeta.addDependency((TransDependency)dep.clone()); for (SlaveServer slave : slaveServers) transMeta.getSlaveServers().add((SlaveServer)slave.clone()); for (ClusterSchema schema : clusterSchemas) transMeta.getClusterSchemas().add((ClusterSchema)schema.clone()); for (PartitionSchema schema : partitionSchemas) transMeta.getPartitionSchemas().add((PartitionSchema)schema.clone()); return transMeta; } catch (CloneNotSupportedException e) { e.printStackTrace(); return null; } } /** * Get the database ID in the repository for this object. * * @return the database ID in the repository for this object. */ public long getID() { return id; } /** * Set the database ID for this object in the repository. * * @param id the database ID for this object in the repository. */ public void setID(long id) { this.id = id; } /** * Clears the transformation. */ public void clear() { setID(-1L); databases = new ArrayList<DatabaseMeta>(); steps = new ArrayList<StepMeta>(); hops = new ArrayList<TransHopMeta>(); notes = new ArrayList<NotePadMeta>(); dependencies = new ArrayList<TransDependency>(); partitionSchemas = new ArrayList<PartitionSchema>(); slaveServers = new ArrayList<SlaveServer>(); clusterSchemas = new ArrayList<ClusterSchema>(); slaveStepCopyPartitionDistribution = new SlaveStepCopyPartitionDistribution(); name = null; description=null; trans_status=-1; trans_version=null; extended_description=null; filename = null; readStep = null; writeStep = null; inputStep = null; outputStep = null; updateStep = null; logTable = null; logConnection = null; sizeRowset = Const.ROWS_IN_ROWSET; sleepTimeEmpty = Const.TIMEOUT_GET_MILLIS; sleepTimeFull = Const.TIMEOUT_PUT_MILLIS; maxDateConnection = null; maxDateTable = null; maxDateField = null; maxDateOffset = 0.0; maxDateDifference = 0.0; undo = new ArrayList<TransAction>(); max_undo = Const.MAX_UNDO; undo_position = -1; counters = new Hashtable<String,Counter>(); resultRows = null; clearUndo(); clearChanged(); useBatchId = true; // Make this one the default from now on... logfieldUsed = false; // Don't use the log-field by default... createdUser = "-"; //$NON-NLS-1$ createdDate = new Date(); //$NON-NLS-1$ modifiedUser = "-"; //$NON-NLS-1$ modifiedDate = new Date(); //$NON-NLS-1$ // LOAD THE DATABASE CACHE! dbCache = DBCache.getInstance(); directoryTree = new RepositoryDirectory(); // Default directory: root directory = directoryTree; resultRows = new ArrayList<RowMetaAndData>(); resultFiles = new ArrayList<ResultFile>(); feedbackShown = true; feedbackSize = Const.ROWS_UPDATE; // Thread priority: // - set to false in version 2.5.0 // - re-enabling in version 3.0.1 to prevent excessive locking (PDI-491) // usingThreadPriorityManagment = true; // TODO FIXME Make these performance monitoring options configurable // capturingStepPerformanceSnapShots = true; stepPerformanceCapturingDelay = 1000; // every 1 seconds stepsFieldsCache = new HashMap<String, RowMetaInterface>(); } public void clearUndo() { undo = new ArrayList<TransAction>(); undo_position = -1; } /* (non-Javadoc) * @see org.pentaho.di.trans.HasDatabaseInterface#getDatabases() */ public List<DatabaseMeta> getDatabases() { return databases; } /* (non-Javadoc) * @see org.pentaho.di.trans.HasDatabaseInterface#setDatabases(java.util.ArrayList) */ public void setDatabases(List<DatabaseMeta> databases) { this.databases = databases; } /* (non-Javadoc) * @see org.pentaho.di.trans.HasDatabaseInterface#addDatabase(org.pentaho.di.core.database.DatabaseMeta) */ public void addDatabase(DatabaseMeta databaseMeta) { databases.add(databaseMeta); } /* (non-Javadoc) * @see org.pentaho.di.trans.HasDatabaseInterface#addOrReplaceDatabase(org.pentaho.di.core.database.DatabaseMeta) */ public void addOrReplaceDatabase(DatabaseMeta databaseMeta) { int index = databases.indexOf(databaseMeta); if (index<0) { databases.add(databaseMeta); } else { DatabaseMeta previous = getDatabase(index); previous.replaceMeta(databaseMeta); } changed_databases = true; } /** * Add a new step to the transformation * * @param stepMeta The step to be added. */ public void addStep(StepMeta stepMeta) { steps.add(stepMeta); changed_steps = true; } /** * Add a new step to the transformation if that step didn't exist yet. * Otherwise, replace the step. * * @param stepMeta The step to be added. */ public void addOrReplaceStep(StepMeta stepMeta) { int index = steps.indexOf(stepMeta); if (index<0) { steps.add(stepMeta); } else { StepMeta previous = getStep(index); previous.replaceMeta(stepMeta); } changed_steps = true; } /** * Add a new hop to the transformation. * * @param hi The hop to be added. */ public void addTransHop(TransHopMeta hi) { hops.add(hi); changed_hops = true; } /** * Add a new note to the transformation. * * @param ni The note to be added. */ public void addNote(NotePadMeta ni) { notes.add(ni); changed_notes = true; } /** * Add a new dependency to the transformation. * * @param td The transformation dependency to be added. */ public void addDependency(TransDependency td) { dependencies.add(td); } /* (non-Javadoc) * @see org.pentaho.di.trans.HasDatabaseInterface#addDatabase(int, org.pentaho.di.core.database.DatabaseMeta) */ public void addDatabase(int p, DatabaseMeta ci) { databases.add(p, ci); } /** * Add a new step to the transformation * * @param p The location * @param stepMeta The step to be added. */ public void addStep(int p, StepMeta stepMeta) { steps.add(p, stepMeta); changed_steps = true; } /** * Add a new hop to the transformation on a certain location. * * @param p the location * @param hi The hop to be added. */ public void addTransHop(int p, TransHopMeta hi) { hops.add(p, hi); changed_hops = true; } /** * Add a new note to the transformation on a certain location. * * @param p The location * @param ni The note to be added. */ public void addNote(int p, NotePadMeta ni) { notes.add(p, ni); changed_notes = true; } /** * Add a new dependency to the transformation on a certain location * * @param p The location. * @param td The transformation dependency to be added. */ public void addDependency(int p, TransDependency td) { dependencies.add(p, td); } /* (non-Javadoc) * @see org.pentaho.di.trans.HasDatabaseInterface#getDatabase(int) */ public DatabaseMeta getDatabase(int i) { return databases.get(i); } /** * Get an ArrayList of defined steps. * * @return an ArrayList of defined steps. */ public List<StepMeta> getSteps() { return steps; } /** * Retrieves a step on a certain location. * * @param i The location. * @return The step information. */ public StepMeta getStep(int i) { return steps.get(i); } /** * Retrieves a hop on a certain location. * * @param i The location. * @return The hop information. */ public TransHopMeta getTransHop(int i) { return hops.get(i); } /** * Retrieves notepad information on a certain location. * * @param i The location * @return The notepad information. */ public NotePadMeta getNote(int i) { return notes.get(i); } /** * Retrieves a dependency on a certain location. * * @param i The location. * @return The dependency. */ public TransDependency getDependency(int i) { return dependencies.get(i); } /* (non-Javadoc) * @see org.pentaho.di.trans.HasDatabaseInterface#removeDatabase(int) */ public void removeDatabase(int i) { if (i < 0 || i >= databases.size()) return; databases.remove(i); changed_databases = true; } /** * Removes a step from the transformation on a certain location. * * @param i The location */ public void removeStep(int i) { if (i < 0 || i >= steps.size()) return; steps.remove(i); changed_steps = true; } /** * Removes a hop from the transformation on a certain location. * * @param i The location */ public void removeTransHop(int i) { if (i < 0 || i >= hops.size()) return; hops.remove(i); changed_hops = true; } /** * Removes a note from the transformation on a certain location. * * @param i The location */ public void removeNote(int i) { if (i < 0 || i >= notes.size()) return; notes.remove(i); changed_notes = true; } public void raiseNote(int p) { // if valid index and not last index if ((p >=0) && (p < notes.size()-1)) { NotePadMeta note = notes.remove(p); notes.add(note); changed_notes = true; } } public void lowerNote(int p) { // if valid index and not first index if ((p >0) && (p < notes.size())) { NotePadMeta note = notes.remove(p); notes.add(0, note); changed_notes = true; } } /** * Removes a dependency from the transformation on a certain location. * * @param i The location */ public void removeDependency(int i) { if (i < 0 || i >= dependencies.size()) return; dependencies.remove(i); } /** * Clears all the dependencies from the transformation. */ public void removeAllDependencies() { dependencies.clear(); } /* (non-Javadoc) * @see org.pentaho.di.trans.HasDatabaseInterface#nrDatabases() */ public int nrDatabases() { return databases.size(); } /** * Count the nr of steps in the transformation. * * @return The nr of steps */ public int nrSteps() { return steps.size(); } /** * Count the nr of hops in the transformation. * * @return The nr of hops */ public int nrTransHops() { return hops.size(); } /** * Count the nr of notes in the transformation. * * @return The nr of notes */ public int nrNotes() { return notes.size(); } /** * Count the nr of dependencies in the transformation. * * @return The nr of dependencies */ public int nrDependencies() { return dependencies.size(); } /** * Changes the content of a step on a certain position * * @param i The position * @param stepMeta The Step */ public void setStep(int i, StepMeta stepMeta) { steps.set(i, stepMeta); } /** * Changes the content of a hop on a certain position * * @param i The position * @param hi The hop */ public void setTransHop(int i, TransHopMeta hi) { hops.set(i, hi); } /** * Counts the number of steps that are actually used in the transformation. * * @return the number of used steps. */ public int nrUsedSteps() { int nr = 0; for (int i = 0; i < nrSteps(); i++) { StepMeta stepMeta = getStep(i); if (isStepUsedInTransHops(stepMeta)) nr++; } return nr; } /** * Gets a used step on a certain location * * @param lu The location * @return The used step. */ public StepMeta getUsedStep(int lu) { int nr = 0; for (int i = 0; i < nrSteps(); i++) { StepMeta stepMeta = getStep(i); if (isStepUsedInTransHops(stepMeta)) { if (lu == nr) return stepMeta; nr++; } } return null; } /* (non-Javadoc) * @see org.pentaho.di.trans.HasDatabaseInterface#findDatabase(java.lang.String) */ public DatabaseMeta findDatabase(String name) { int i; for (i = 0; i < nrDatabases(); i++) { DatabaseMeta ci = getDatabase(i); if (ci.getName().equalsIgnoreCase(name)) { return ci; } } return null; } /** * Searches the list of steps for a step with a certain name * * @param name The name of the step to look for * @return The step information or null if no nothing was found. */ public StepMeta findStep(String name) { return findStep(name, null); } /** * Searches the list of steps for a step with a certain name while excluding one step. * * @param name The name of the step to look for * @param exclude The step information to exclude. * @return The step information or null if nothing was found. */ public StepMeta findStep(String name, StepMeta exclude) { if (name==null) return null; int excl = -1; if (exclude != null) excl = indexOfStep(exclude); for (int i = 0; i < nrSteps(); i++) { StepMeta stepMeta = getStep(i); if (i != excl && stepMeta.getName().equalsIgnoreCase(name)) { return stepMeta; } } return null; } /** * Searches the list of hops for a hop with a certain name * * @param name The name of the hop to look for * @return The hop information or null if nothing was found. */ public TransHopMeta findTransHop(String name) { int i; for (i = 0; i < nrTransHops(); i++) { TransHopMeta hi = getTransHop(i); if (hi.toString().equalsIgnoreCase(name)) { return hi; } } return null; } /** * Search all hops for a hop where a certain step is at the start. * * @param fromstep The step at the start of the hop. * @return The hop or null if no hop was found. */ public TransHopMeta findTransHopFrom(StepMeta fromstep) { int i; for (i = 0; i < nrTransHops(); i++) { TransHopMeta hi = getTransHop(i); if (hi.getFromStep() != null && hi.getFromStep().equals(fromstep)) // return the first { return hi; } } return null; } /** * Find a certain hop in the transformation.. * * @param hi The hop information to look for. * @return The hop or null if no hop was found. */ public TransHopMeta findTransHop(TransHopMeta hi) { return findTransHop(hi.getFromStep(), hi.getToStep()); } /** * Search all hops for a hop where a certain step is at the start and another is at the end. * * @param from The step at the start of the hop. * @param to The step at the end of the hop. * @return The hop or null if no hop was found. */ public TransHopMeta findTransHop(StepMeta from, StepMeta to) { return findTransHop(from, to, false); } /** * Search all hops for a hop where a certain step is at the start and another is at the end. * * @param from The step at the start of the hop. * @param to The step at the end of the hop. * @return The hop or null if no hop was found. */ public TransHopMeta findTransHop(StepMeta from, StepMeta to, boolean disabledToo) { int i; for (i = 0; i < nrTransHops(); i++) { TransHopMeta hi = getTransHop(i); if (hi.isEnabled() || disabledToo) { if (hi.getFromStep() != null && hi.getToStep() != null && hi.getFromStep().equals(from) && hi.getToStep().equals(to)) { return hi; } } } return null; } /** * Search all hops for a hop where a certain step is at the end. * * @param tostep The step at the end of the hop. * @return The hop or null if no hop was found. */ public TransHopMeta findTransHopTo(StepMeta tostep) { int i; for (i = 0; i < nrTransHops(); i++) { TransHopMeta hi = getTransHop(i); if (hi.getToStep() != null && hi.getToStep().equals(tostep)) // Return the first! { return hi; } } return null; } /** * Determines whether or not a certain step is informative. This means that the previous step is sending information * to this step, but only informative. This means that this step is using the information to process the actual * stream of data. We use this in StreamLookup, TableInput and other types of steps. * * @param this_step The step that is receiving information. * @param prev_step The step that is sending information * @return true if prev_step if informative for this_step. */ public boolean isStepInformative(StepMeta this_step, StepMeta prev_step) { String[] infoSteps = this_step.getStepMetaInterface().getInfoSteps(); if (infoSteps == null) return false; for (int i = 0; i < infoSteps.length; i++) { if (prev_step.getName().equalsIgnoreCase(infoSteps[i])) return true; } return false; } /** * Counts the number of previous steps for a step name. * * @param stepname The name of the step to start from * @return The number of preceding steps. */ public int findNrPrevSteps(String stepname) { return findNrPrevSteps(findStep(stepname), false); } /** * Counts the number of previous steps for a step name taking into account whether or not they are informational. * * @param stepname The name of the step to start from * @return The number of preceding steps. */ public int findNrPrevSteps(String stepname, boolean info) { return findNrPrevSteps(findStep(stepname), info); } /** * Find the number of steps that precede the indicated step. * * @param stepMeta The source step * * @return The number of preceding steps found. */ public int findNrPrevSteps(StepMeta stepMeta) { return findNrPrevSteps(stepMeta, false); } /** * Find the previous step on a certain location. * * @param stepname The source step name * @param nr the location * * @return The preceding step found. */ public StepMeta findPrevStep(String stepname, int nr) { return findPrevStep(findStep(stepname), nr); } /** * Find the previous step on a certain location taking into account the steps being informational or not. * * @param stepname The name of the step * @param nr The location * @param info true if we only want the informational steps. * @return The step information */ public StepMeta findPrevStep(String stepname, int nr, boolean info) { return findPrevStep(findStep(stepname), nr, info); } /** * Find the previous step on a certain location. * * @param stepMeta The source step information * @param nr the location * * @return The preceding step found. */ public StepMeta findPrevStep(StepMeta stepMeta, int nr) { return findPrevStep(stepMeta, nr, false); } /** * Count the number of previous steps on a certain location taking into account the steps being informational or * not. * * @param stepMeta The name of the step * @param info true if we only want the informational steps. * @return The number of preceding steps */ public int findNrPrevSteps(StepMeta stepMeta, boolean info) { int count = 0; int i; for (i = 0; i < nrTransHops(); i++) // Look at all the hops; { TransHopMeta hi = getTransHop(i); if (hi.getToStep() != null && hi.isEnabled() && hi.getToStep().equals(stepMeta)) { // Check if this previous step isn't informative (StreamValueLookup) // We don't want fields from this stream to show up! if (info || !isStepInformative(stepMeta, hi.getFromStep())) { count++; } } } return count; } /** * Find the previous step on a certain location taking into account the steps being informational or not. * * @param stepMeta The step * @param nr The location * @param info true if we only want the informational steps. * @return The preceding step information */ public StepMeta findPrevStep(StepMeta stepMeta, int nr, boolean info) { int count = 0; int i; for (i = 0; i < nrTransHops(); i++) // Look at all the hops; { TransHopMeta hi = getTransHop(i); if (hi.getToStep() != null && hi.isEnabled() && hi.getToStep().equals(stepMeta)) { if (info || !isStepInformative(stepMeta, hi.getFromStep())) { if (count == nr) { return hi.getFromStep(); } count++; } } } return null; } /** * Get the informational steps for a certain step. An informational step is a step that provides information for * lookups etc. * * @param stepMeta The name of the step * @return The informational steps found */ public StepMeta[] getInfoStep(StepMeta stepMeta) { String[] infoStepName = stepMeta.getStepMetaInterface().getInfoSteps(); if (infoStepName == null) return null; StepMeta[] infoStep = new StepMeta[infoStepName.length]; for (int i = 0; i < infoStep.length; i++) { infoStep[i] = findStep(infoStepName[i]); } return infoStep; } /** * Find the the number of informational steps for a certains step. * * @param stepMeta The step * @return The number of informational steps found. */ public int findNrInfoSteps(StepMeta stepMeta) { if (stepMeta == null) return 0; int count = 0; for (int i = 0; i < nrTransHops(); i++) // Look at all the hops; { TransHopMeta hi = getTransHop(i); if (hi == null || hi.getToStep() == null) { log.logError(toString(), Messages.getString("TransMeta.Log.DestinationOfHopCannotBeNull")); //$NON-NLS-1$ } if (hi != null && hi.getToStep() != null && hi.isEnabled() && hi.getToStep().equals(stepMeta)) { // Check if this previous step isn't informative (StreamValueLookup) // We don't want fields from this stream to show up! if (isStepInformative(stepMeta, hi.getFromStep())) { count++; } } } return count; } /** * Find the informational fields coming from an informational step into the step specified. * * @param stepname The name of the step * @return A row containing fields with origin. */ public RowMetaInterface getPrevInfoFields(String stepname) throws KettleStepException { return getPrevInfoFields(findStep(stepname)); } /** * Find the informational fields coming from an informational step into the step specified. * * @param stepMeta The receiving step * @return A row containing fields with origin. */ public RowMetaInterface getPrevInfoFields(StepMeta stepMeta) throws KettleStepException { RowMetaInterface row = new RowMeta(); for (int i = 0; i < nrTransHops(); i++) // Look at all the hops; { TransHopMeta hi = getTransHop(i); if (hi.isEnabled() && hi.getToStep().equals(stepMeta)) { if (isStepInformative(stepMeta, hi.getFromStep())) { getThisStepFields(stepMeta, null, row); return row; } } } return row; } /** * Find the number of succeeding steps for a certain originating step. * * @param stepMeta The originating step * @return The number of succeeding steps. */ public int findNrNextSteps(StepMeta stepMeta) { int count = 0; int i; for (i = 0; i < nrTransHops(); i++) // Look at all the hops; { TransHopMeta hi = getTransHop(i); if (hi.isEnabled() && hi.getFromStep().equals(stepMeta)) count++; } return count; } /** * Find the succeeding step at a location for an originating step. * * @param stepMeta The originating step * @param nr The location * @return The step found. */ public StepMeta findNextStep(StepMeta stepMeta, int nr) { int count = 0; int i; for (i = 0; i < nrTransHops(); i++) // Look at all the hops; { TransHopMeta hi = getTransHop(i); if (hi.isEnabled() && hi.getFromStep().equals(stepMeta)) { if (count == nr) { return hi.getToStep(); } count++; } } return null; } /** * Retrieve an array of preceding steps for a certain destination step. * * @param stepMeta The destination step * @return An array containing the preceding steps. */ public StepMeta[] getPrevSteps(StepMeta stepMeta) { int nr = findNrPrevSteps(stepMeta, true); StepMeta retval[] = new StepMeta[nr]; for (int i = 0; i < nr; i++) { retval[i] = findPrevStep(stepMeta, i, true); } return retval; } /** * Retrieve an array of succeeding step names for a certain originating step name. * * @param stepname The originating step name * @return An array of succeeding step names */ public String[] getPrevStepNames(String stepname) { return getPrevStepNames(findStep(stepname)); } /** * Retrieve an array of preceding steps for a certain destination step. * * @param stepMeta The destination step * @return an array of preceding step names. */ public String[] getPrevStepNames(StepMeta stepMeta) { StepMeta prevStepMetas[] = getPrevSteps(stepMeta); String retval[] = new String[prevStepMetas.length]; for (int x = 0; x < prevStepMetas.length; x++) retval[x] = prevStepMetas[x].getName(); return retval; } /** * Retrieve an array of succeeding steps for a certain originating step. * * @param stepMeta The originating step * @return an array of succeeding steps. */ public StepMeta[] getNextSteps(StepMeta stepMeta) { int nr = findNrNextSteps(stepMeta); StepMeta retval[] = new StepMeta[nr]; for (int i = 0; i < nr; i++) { retval[i] = findNextStep(stepMeta, i); } return retval; } /** * Retrieve an array of succeeding step names for a certain originating step. * * @param stepMeta The originating step * @return an array of succeeding step names. */ public String[] getNextStepNames(StepMeta stepMeta) { StepMeta nextStepMeta[] = getNextSteps(stepMeta); String retval[] = new String[nextStepMeta.length]; for (int x = 0; x < nextStepMeta.length; x++) retval[x] = nextStepMeta[x].getName(); return retval; } /** * Find the step that is located on a certain point on the canvas, taking into account the icon size. * * @param x the x-coordinate of the point queried * @param y the y-coordinate of the point queried * @return The step information if a step is located at the point. Otherwise, if no step was found: null. */ public StepMeta getStep(int x, int y, int iconsize) { int i, s; s = steps.size(); for (i = s - 1; i >= 0; i--) // Back to front because drawing goes from start to end { StepMeta stepMeta = steps.get(i); if (partOfTransHop(stepMeta) || stepMeta.isDrawn()) // Only consider steps from active or inactive hops! { Point p = stepMeta.getLocation(); if (p != null) { if (x >= p.x && x <= p.x + iconsize && y >= p.y && y <= p.y + iconsize + 20) { return stepMeta; } } } } return null; } /** * Find the note that is located on a certain point on the canvas. * * @param x the x-coordinate of the point queried * @param y the y-coordinate of the point queried * @return The note information if a note is located at the point. Otherwise, if nothing was found: null. */ public NotePadMeta getNote(int x, int y) { int i, s; s = notes.size(); for (i = s - 1; i >= 0; i--) // Back to front because drawing goes from start to end { NotePadMeta ni = notes.get(i); Point loc = ni.getLocation(); Point p = new Point(loc.x, loc.y); if (x >= p.x && x <= p.x + ni.width + 2 * Const.NOTE_MARGIN && y >= p.y && y <= p.y + ni.height + 2 * Const.NOTE_MARGIN) { return ni; } } return null; } /** * Determines whether or not a certain step is part of a hop. * * @param stepMeta The step queried * @return true if the step is part of a hop. */ public boolean partOfTransHop(StepMeta stepMeta) { int i; for (i = 0; i < nrTransHops(); i++) { TransHopMeta hi = getTransHop(i); if (hi.getFromStep() == null || hi.getToStep() == null) return false; if (hi.getFromStep().equals(stepMeta) || hi.getToStep().equals(stepMeta)) return true; } return false; } /** * Returns the fields that are emitted by a certain step name * * @param stepname The stepname of the step to be queried. * @return A row containing the fields emitted. */ public RowMetaInterface getStepFields(String stepname) throws KettleStepException { StepMeta stepMeta = findStep(stepname); if (stepMeta != null) return getStepFields(stepMeta); else return null; } /** * Returns the fields that are emitted by a certain step * * @param stepMeta The step to be queried. * @return A row containing the fields emitted. */ public RowMetaInterface getStepFields(StepMeta stepMeta) throws KettleStepException { return getStepFields(stepMeta, null); } public RowMetaInterface getStepFields(StepMeta[] stepMeta) throws KettleStepException { RowMetaInterface fields = new RowMeta(); for (int i = 0; i < stepMeta.length; i++) { RowMetaInterface flds = getStepFields(stepMeta[i]); if (flds != null) fields.mergeRowMeta(flds); } return fields; } /** * Returns the fields that are emitted by a certain step * * @param stepMeta The step to be queried. * @param monitor The progress monitor for progress dialog. (null if not used!) * @return A row containing the fields emitted. */ public RowMetaInterface getStepFields(StepMeta stepMeta, ProgressMonitorListener monitor) throws KettleStepException { clearStepFieldsCachce(); return getStepFields(stepMeta, null, monitor); } /** * Returns the fields that are emitted by a certain step * * @param stepMeta The step to be queried. * @param targetStep the target step * @param monitor The progress monitor for progress dialog. (null if not used!) * @return A row containing the fields emitted. */ public RowMetaInterface getStepFields(StepMeta stepMeta, StepMeta targetStep, ProgressMonitorListener monitor) throws KettleStepException { RowMetaInterface row = new RowMeta(); if (stepMeta == null) return row; String fromToCacheEntry = stepMeta.getName()+ ( targetStep!=null ? ("-"+targetStep.getName()) : "" ); RowMetaInterface rowMeta = stepsFieldsCache.get(fromToCacheEntry); if (rowMeta!=null) { return rowMeta; } // See if the step is sending ERROR rows to the specified target step. // if (targetStep!=null && stepMeta.isSendingErrorRowsToStep(targetStep)) { // The error rows are the same as the input rows for // the step but with the selected error fields added // row = getPrevStepFields(stepMeta); // Add to this the error fields... StepErrorMeta stepErrorMeta = stepMeta.getStepErrorMeta(); row.addRowMeta(stepErrorMeta.getErrorFields()); // Store this row in the cache // stepsFieldsCache.put(fromToCacheEntry, row); return row; } // Resume the regular program... log.logDebug(toString(), Messages.getString("TransMeta.Log.FromStepALookingAtPreviousStep", stepMeta.getName(), String.valueOf(findNrPrevSteps(stepMeta)) )); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ for (int i = 0; i < findNrPrevSteps(stepMeta); i++) { StepMeta prevStepMeta = findPrevStep(stepMeta, i); if (monitor != null) { monitor.subTask(Messages.getString("TransMeta.Monitor.CheckingStepTask.Title", prevStepMeta.getName() )); //$NON-NLS-1$ //$NON-NLS-2$ } RowMetaInterface add = getStepFields(prevStepMeta, stepMeta, monitor); if (add == null) add = new RowMeta(); log.logDebug(toString(), Messages.getString("TransMeta.Log.FoundFieldsToAdd") + add.toString()); //$NON-NLS-1$ if (i == 0) { row.addRowMeta(add); } else { // See if the add fields are not already in the row for (int x = 0; x < add.size(); x++) { ValueMetaInterface v = add.getValueMeta(x); ValueMetaInterface s = row.searchValueMeta(v.getName()); if (s == null) { row.addValueMeta(v); } } } } // Finally, see if we need to add/modify/delete fields with this step "name" rowMeta = getThisStepFields(stepMeta, targetStep, row, monitor); // Store this row in the cache // stepsFieldsCache.put(fromToCacheEntry, rowMeta); return rowMeta; } /** * Find the fields that are entering a step with a certain name. * * @param stepname The name of the step queried * @return A row containing the fields (w/ origin) entering the step */ public RowMetaInterface getPrevStepFields(String stepname) throws KettleStepException { clearStepFieldsCachce(); return getPrevStepFields(findStep(stepname)); } /** * Find the fields that are entering a certain step. * * @param stepMeta The step queried * @return A row containing the fields (w/ origin) entering the step */ public RowMetaInterface getPrevStepFields(StepMeta stepMeta) throws KettleStepException { clearStepFieldsCachce(); return getPrevStepFields(stepMeta, null); } /** * Find the fields that are entering a certain step. * * @param stepMeta The step queried * @param monitor The progress monitor for progress dialog. (null if not used!) * @return A row containing the fields (w/ origin) entering the step */ public RowMetaInterface getPrevStepFields(StepMeta stepMeta, ProgressMonitorListener monitor) throws KettleStepException { clearStepFieldsCachce(); RowMetaInterface row = new RowMeta(); if (stepMeta == null) { return null; } log.logDebug(toString(), Messages.getString("TransMeta.Log.FromStepALookingAtPreviousStep", stepMeta.getName(), String.valueOf(findNrPrevSteps(stepMeta)) )); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ for (int i = 0; i < findNrPrevSteps(stepMeta); i++) { StepMeta prevStepMeta = findPrevStep(stepMeta, i); if (monitor != null) { monitor.subTask(Messages.getString("TransMeta.Monitor.CheckingStepTask.Title", prevStepMeta.getName() )); //$NON-NLS-1$ //$NON-NLS-2$ } RowMetaInterface add = getStepFields(prevStepMeta, stepMeta, monitor); log.logDebug(toString(), Messages.getString("TransMeta.Log.FoundFieldsToAdd2") + add.toString()); //$NON-NLS-1$ if (i == 0) // we expect all input streams to be of the same layout! { row.addRowMeta(add); // recursive! } else { // See if the add fields are not already in the row for (int x = 0; x < add.size(); x++) { ValueMetaInterface v = add.getValueMeta(x); ValueMetaInterface s = row.searchValueMeta(v.getName()); if (s == null) { row.addValueMeta(v); } } } } return row; } /** * Return the fields that are emitted by a step with a certain name * * @param stepname The name of the step that's being queried. * @param row A row containing the input fields or an empty row if no input is required. * @return A Row containing the output fields. */ public RowMetaInterface getThisStepFields(String stepname, RowMetaInterface row) throws KettleStepException { return getThisStepFields(findStep(stepname), null, row); } /** * Returns the fields that are emitted by a step * * @param stepMeta : The StepMeta object that's being queried * @param nextStep : if non-null this is the next step that's call back to ask what's being sent * @param row : A row containing the input fields or an empty row if no input is required. * * @return A Row containing the output fields. */ public RowMetaInterface getThisStepFields(StepMeta stepMeta, StepMeta nextStep, RowMetaInterface row) throws KettleStepException { return getThisStepFields(stepMeta, nextStep, row, null); } /** * Returns the fields that are emitted by a step * * @param stepMeta : The StepMeta object that's being queried * @param nextStep : if non-null this is the next step that's call back to ask what's being sent * @param row : A row containing the input fields or an empty row if no input is required. * * @return A Row containing the output fields. */ public RowMetaInterface getThisStepFields(StepMeta stepMeta, StepMeta nextStep, RowMetaInterface row, ProgressMonitorListener monitor) throws KettleStepException { // Then this one. log.logDebug(toString(), Messages.getString("TransMeta.Log.GettingFieldsFromStep",stepMeta.getName(), stepMeta.getStepID())); //$NON-NLS-1$ //$NON-NLS-2$ String name = stepMeta.getName(); if (monitor != null) { monitor.subTask(Messages.getString("TransMeta.Monitor.GettingFieldsFromStepTask.Title", name )); //$NON-NLS-1$ //$NON-NLS-2$ } StepMetaInterface stepint = stepMeta.getStepMetaInterface(); RowMetaInterface inform[] = null; StepMeta[] lu = getInfoStep(stepMeta); if (Const.isEmpty(lu)) { inform = new RowMetaInterface[] { stepint.getTableFields(), }; } else { inform = new RowMetaInterface[lu.length]; for (int i=0;i<lu.length;i++) inform[i] = getStepFields(lu[i]); } // Set the Repository object on the Mapping step // That way the mapping step can determine the output fields for repository hosted mappings... // This is the exception to the rule so we don't pass this through the getFields() method. // for (StepMeta step : steps) { if (step.getStepMetaInterface() instanceof MappingMeta) { ((MappingMeta)step.getStepMetaInterface()).setRepository(repository); } } // Go get the fields... // stepint.getFields(row, name, inform, nextStep, this); return row; } /** * Determine if we should put a replace warning or not for the transformation in a certain repository. * * @param rep The repository. * @return True if we should show a replace warning, false if not. */ public boolean showReplaceWarning(Repository rep) { if (getID() < 0) { try { if (rep.getTransformationID(getName(), directory.getID()) > 0) return true; } catch (KettleException dbe) { log.logError(toString(), Messages.getString("TransMeta.Log.DatabaseError") + dbe.getMessage()); //$NON-NLS-1$ return true; } } return false; } public void saveRep(Repository rep) throws KettleException { saveRep(rep, null); } /** * Saves the transformation to a repository. * * @param rep The repository. * @throws KettleException if an error occurrs. */ public void saveRep(Repository rep, ProgressMonitorListener monitor) throws KettleException { try { if (monitor!=null) monitor.subTask(Messages.getString("TransMeta.Monitor.LockingRepository")); //$NON-NLS-1$ rep.lockRepository(); // make sure we're they only one using the repository at the moment rep.insertLogEntry("save transformation '"+getName()+"'"); // Clear attribute id cache rep.clearNextIDCounters(); // force repository lookup. // Do we have a valid directory? if (directory.getID() < 0) { throw new KettleException(Messages.getString("TransMeta.Exception.PlsSelectAValidDirectoryBeforeSavingTheTransformation")); } //$NON-NLS-1$ int nrWorks = 2 + nrDatabases() + nrNotes() + nrSteps() + nrTransHops(); if (monitor != null) monitor.beginTask(Messages.getString("TransMeta.Monitor.SavingTransformationTask.Title") + getPathAndName(), nrWorks); //$NON-NLS-1$ log.logDebug(toString(), Messages.getString("TransMeta.Log.SavingOfTransformationStarted")); //$NON-NLS-1$ if (monitor!=null && monitor.isCanceled()) throw new KettleDatabaseException(); // Before we start, make sure we have a valid transformation ID! // Two possibilities: // 1) We have a ID: keep it // 2) We don't have an ID: look it up. // If we find a transformation with the same name: ask! // if (monitor != null) monitor.subTask(Messages.getString("TransMeta.Monitor.HandlingOldVersionTransformationTask.Title")); //$NON-NLS-1$ setID(rep.getTransformationID(getName(), directory.getID())); // If no valid id is available in the database, assign one... if (getID() <= 0) { setID(rep.getNextTransformationID()); } else { // If we have a valid ID, we need to make sure everything is cleared out // of the database for this id_transformation, before we put it back in... if (monitor != null) monitor.subTask(Messages.getString("TransMeta.Monitor.DeletingOldVersionTransformationTask.Title")); //$NON-NLS-1$ log.logDebug(toString(), Messages.getString("TransMeta.Log.DeletingOldVersionTransformation")); //$NON-NLS-1$ rep.delAllFromTrans(getID()); log.logDebug(toString(), Messages.getString("TransMeta.Log.OldVersionOfTransformationRemoved")); //$NON-NLS-1$ } if (monitor != null) monitor.worked(1); log.logDebug(toString(), Messages.getString("TransMeta.Log.SavingNotes")); //$NON-NLS-1$ for (int i = 0; i < nrNotes(); i++) { if (monitor!=null && monitor.isCanceled()) throw new KettleDatabaseException(Messages.getString("TransMeta.Log.UserCancelledTransSave")); if (monitor != null) monitor.subTask(Messages.getString("TransMeta.Monitor.SavingNoteTask.Title") + (i + 1) + "/" + nrNotes()); //$NON-NLS-1$ //$NON-NLS-2$ NotePadMeta ni = getNote(i); ni.saveRep(rep, getID()); if (ni.getID() > 0) rep.insertTransNote(getID(), ni.getID()); if (monitor != null) monitor.worked(1); } log.logDebug(toString(), Messages.getString("TransMeta.Log.SavingDatabaseConnections")); //$NON-NLS-1$ for (int i = 0; i < nrDatabases(); i++) { if (monitor!=null && monitor.isCanceled()) throw new KettleDatabaseException(Messages.getString("TransMeta.Log.UserCancelledTransSave")); if (monitor != null) monitor.subTask(Messages.getString("TransMeta.Monitor.SavingDatabaseTask.Title") + (i + 1) + "/" + nrDatabases()); //$NON-NLS-1$ //$NON-NLS-2$ DatabaseMeta databaseMeta = getDatabase(i); // ONLY save the database connection if it has changed and nothing was saved in the repository if(databaseMeta.hasChanged() || databaseMeta.getID()<=0) { databaseMeta.saveRep(rep); } if (monitor != null) monitor.worked(1); } // Before saving the steps, make sure we have all the step-types. // It is possible that we received another step through a plugin. log.logDebug(toString(), Messages.getString("TransMeta.Log.CheckingStepTypes")); //$NON-NLS-1$ rep.updateStepTypes(); log.logDebug(toString(), Messages.getString("TransMeta.Log.SavingSteps")); //$NON-NLS-1$ for (int i = 0; i < nrSteps(); i++) { if (monitor!=null && monitor.isCanceled()) throw new KettleDatabaseException(Messages.getString("TransMeta.Log.UserCancelledTransSave")); if (monitor != null) monitor.subTask(Messages.getString("TransMeta.Monitor.SavingStepTask.Title") + (i + 1) + "/" + nrSteps()); //$NON-NLS-1$ //$NON-NLS-2$ StepMeta stepMeta = getStep(i); stepMeta.saveRep(rep, getID()); if (monitor != null) monitor.worked(1); } rep.closeStepAttributeInsertPreparedStatement(); log.logDebug(toString(), Messages.getString("TransMeta.Log.SavingHops")); //$NON-NLS-1$ for (int i = 0; i < nrTransHops(); i++) { if (monitor!=null && monitor.isCanceled()) throw new KettleDatabaseException(Messages.getString("TransMeta.Log.UserCancelledTransSave")); if (monitor != null) monitor.subTask(Messages.getString("TransMeta.Monitor.SavingHopTask.Title") + (i + 1) + "/" + nrTransHops()); //$NON-NLS-1$ //$NON-NLS-2$ TransHopMeta hi = getTransHop(i); hi.saveRep(rep, getID()); if (monitor != null) monitor.worked(1); } if (monitor != null) monitor.subTask(Messages.getString("TransMeta.Monitor.FinishingTask.Title")); //$NON-NLS-1$ log.logDebug(toString(), Messages.getString("TransMeta.Log.SavingTransformationInfo")); //$NON-NLS-1$ rep.insertTransformation(this); // save the top level information for the transformation rep.closeTransAttributeInsertPreparedStatement(); // Save the partition schemas // for (int i=0;i<partitionSchemas.size();i++) { if (monitor!=null && monitor.isCanceled()) throw new KettleDatabaseException(Messages.getString("TransMeta.Log.UserCancelledTransSave")); PartitionSchema partitionSchema = partitionSchemas.get(i); // See if this transformation really is a consumer of this object // It might be simply loaded as a shared object from the repository // boolean isUsedByTransformation = isUsingPartitionSchema(partitionSchema); partitionSchema.saveRep(rep, getID(), isUsedByTransformation); } // Save the slaves // for (int i=0;i<slaveServers.size();i++) { if (monitor!=null && monitor.isCanceled()) throw new KettleDatabaseException(Messages.getString("TransMeta.Log.UserCancelledTransSave")); SlaveServer slaveServer = slaveServers.get(i); boolean isUsedByTransformation = isUsingSlaveServer(slaveServer); slaveServer.saveRep(rep, getID(), isUsedByTransformation); } // Save the clustering schemas for (int i=0;i<clusterSchemas.size();i++) { if (monitor!=null && monitor.isCanceled()) throw new KettleDatabaseException(Messages.getString("TransMeta.Log.UserCancelledTransSave")); ClusterSchema clusterSchema = clusterSchemas.get(i); boolean isUsedByTransformation = isUsingClusterSchema(clusterSchema); clusterSchema.saveRep(rep, getID(), isUsedByTransformation); } log.logDebug(toString(), Messages.getString("TransMeta.Log.SavingDependencies")); //$NON-NLS-1$ for (int i = 0; i < nrDependencies(); i++) { if (monitor!=null && monitor.isCanceled()) throw new KettleDatabaseException(Messages.getString("TransMeta.Log.UserCancelledTransSave")); TransDependency td = getDependency(i); td.saveRep(rep, getID()); } // Save the step error handling information as well! for (int i=0;i<nrSteps();i++) { StepMeta stepMeta = getStep(i); StepErrorMeta stepErrorMeta = stepMeta.getStepErrorMeta(); if (stepErrorMeta!=null) { stepErrorMeta.saveRep(rep, getId(), stepMeta.getID()); } } rep.closeStepAttributeInsertPreparedStatement(); log.logDebug(toString(), Messages.getString("TransMeta.Log.SavingFinished")); //$NON-NLS-1$ if (monitor!=null) monitor.subTask(Messages.getString("TransMeta.Monitor.UnlockingRepository")); //$NON-NLS-1$ rep.unlockRepository(); // Perform a commit! rep.commit(); clearChanged(); if (monitor != null) monitor.worked(1); if (monitor != null) monitor.done(); } catch (KettleDatabaseException dbe) { // Oops, roll back! rep.rollback(); log.logError(toString(), Messages.getString("TransMeta.Log.ErrorSavingTransformationToRepository") + Const.CR + dbe.getMessage()); //$NON-NLS-1$ throw new KettleException(Messages.getString("TransMeta.Log.ErrorSavingTransformationToRepository"), dbe); //$NON-NLS-1$ } finally { // don't forget to unlock the repository. // Normally this is done by the commit / rollback statement, but hey there are some freaky database out // there... rep.unlockRepository(); } } public boolean isUsingPartitionSchema(PartitionSchema partitionSchema) { // Loop over all steps and see if the partition schema is used. for (int i=0;i<nrSteps();i++) { StepPartitioningMeta stepPartitioningMeta = getStep(i).getStepPartitioningMeta(); if (stepPartitioningMeta!=null) { PartitionSchema check = stepPartitioningMeta.getPartitionSchema(); if (check!=null && check.equals(partitionSchema)) { return true; } } } return false; } public boolean isUsingClusterSchema(ClusterSchema clusterSchema) { // Loop over all steps and see if the partition schema is used. for (int i=0;i<nrSteps();i++) { ClusterSchema check = getStep(i).getClusterSchema(); if (check!=null && check.equals(clusterSchema)) { return true; } } return false; } public boolean isUsingSlaveServer(SlaveServer slaveServer) { // Loop over all steps and see if the slave server is used. for (int i=0;i<nrSteps();i++) { ClusterSchema clusterSchema = getStep(i).getClusterSchema(); if (clusterSchema!=null) { for (SlaveServer check : clusterSchema.getSlaveServers()) { if (check.equals(slaveServer)) { return true; } } return true; } } return false; } /* (non-Javadoc) * @see org.pentaho.di.trans.HasDatabaseInterface#readDatabases(org.pentaho.di.repository.Repository, boolean) */ public void readDatabases(Repository rep, boolean overWriteShared) throws KettleException { try { long dbids[] = rep.getDatabaseIDs(); for (int i = 0; i < dbids.length; i++) { DatabaseMeta databaseMeta = new DatabaseMeta(rep, dbids[i]); databaseMeta.shareVariablesWith(this); DatabaseMeta check = findDatabase(databaseMeta.getName()); // Check if there already is one in the transformation if (check==null || overWriteShared) // We only add, never overwrite database connections. { if (databaseMeta.getName() != null) { addOrReplaceDatabase(databaseMeta); if (!overWriteShared) databaseMeta.setChanged(false); } } } changed_databases = false; } catch (KettleDatabaseException dbe) { throw new KettleException(Messages.getString("TransMeta.Log.UnableToReadDatabaseIDSFromRepository"), dbe); //$NON-NLS-1$ } catch (KettleException ke) { throw new KettleException(Messages.getString("TransMeta.Log.UnableToReadDatabasesFromRepository"), ke); //$NON-NLS-1$ } } /** * Read the partitions in the repository and add them to this transformation if they are not yet present. * @param rep The repository to load from. * @param overWriteShared if an object with the same name exists, overwrite * @throws KettleException */ public void readPartitionSchemas(Repository rep, boolean overWriteShared) throws KettleException { try { long dbids[] = rep.getPartitionSchemaIDs(); for (int i = 0; i < dbids.length; i++) { PartitionSchema partitionSchema = new PartitionSchema(rep, dbids[i]); PartitionSchema check = findPartitionSchema(partitionSchema.getName()); // Check if there already is one in the transformation if (check==null || overWriteShared) { if (!Const.isEmpty(partitionSchema.getName())) { addOrReplacePartitionSchema(partitionSchema); if (!overWriteShared) partitionSchema.setChanged(false); } } } } catch (KettleException dbe) { throw new KettleException(Messages.getString("TransMeta.Log.UnableToReadPartitionSchemaFromRepository"), dbe); //$NON-NLS-1$ } } /** * Read the slave servers in the repository and add them to this transformation if they are not yet present. * @param rep The repository to load from. * @param overWriteShared if an object with the same name exists, overwrite * @throws KettleException */ public void readSlaves(Repository rep, boolean overWriteShared) throws KettleException { try { long dbids[] = rep.getSlaveIDs(); for (int i = 0; i < dbids.length; i++) { SlaveServer slaveServer = new SlaveServer(rep, dbids[i]); SlaveServer check = findSlaveServer(slaveServer.getName()); // Check if there already is one in the transformation if (check==null || overWriteShared) { if (!Const.isEmpty(slaveServer.getName())) { addOrReplaceSlaveServer(slaveServer); if (!overWriteShared) slaveServer.setChanged(false); } } } } catch (KettleDatabaseException dbe) { throw new KettleException(Messages.getString("TransMeta.Log.UnableToReadSlaveServersFromRepository"), dbe); //$NON-NLS-1$ } } /** * Read the clusters in the repository and add them to this transformation if they are not yet present. * @param rep The repository to load from. * @param overWriteShared if an object with the same name exists, overwrite * @throws KettleException */ public void readClusters(Repository rep, boolean overWriteShared) throws KettleException { try { long dbids[] = rep.getClusterIDs(); for (int i = 0; i < dbids.length; i++) { ClusterSchema cluster = new ClusterSchema(rep, dbids[i], slaveServers); ClusterSchema check = findClusterSchema(cluster.getName()); // Check if there already is one in the transformation if (check==null || overWriteShared) { if (!Const.isEmpty(cluster.getName())) { addOrReplaceClusterSchema(cluster); if (!overWriteShared) cluster.setChanged(false); } } } } catch (KettleDatabaseException dbe) { throw new KettleException(Messages.getString("TransMeta.Log.UnableToReadClustersFromRepository"), dbe); //$NON-NLS-1$ } } /** * Load the transformation name & other details from a repository. * * @param rep The repository to load the details from. */ public void loadRepTrans(Repository rep) throws KettleException { try { RowMetaAndData r = rep.getTransformation(getID()); if (r != null) { name = r.getString("NAME", null); //$NON-NLS-1$ // Trans description description = r.getString("DESCRIPTION", null); extended_description = r.getString("EXTENDED_DESCRIPTION", null); trans_version = r.getString("TRANS_VERSION", null); trans_status=(int) r.getInteger("TRANS_STATUS", -1L); readStep = StepMeta.findStep(steps, r.getInteger("ID_STEP_READ", -1L)); //$NON-NLS-1$ writeStep = StepMeta.findStep(steps, r.getInteger("ID_STEP_WRITE", -1L)); //$NON-NLS-1$ inputStep = StepMeta.findStep(steps, r.getInteger("ID_STEP_INPUT", -1L)); //$NON-NLS-1$ outputStep = StepMeta.findStep(steps, r.getInteger("ID_STEP_OUTPUT", -1L)); //$NON-NLS-1$ updateStep = StepMeta.findStep(steps, r.getInteger("ID_STEP_UPDATE", -1L)); //$NON-NLS-1$ long id_rejected = rep.getTransAttributeInteger(getID(), 0, "ID_STEP_REJECTED"); // $NON-NLS-1$ if (id_rejected>0) { rejectedStep = StepMeta.findStep(steps, id_rejected); //$NON-NLS-1$ } logConnection = DatabaseMeta.findDatabase(databases, r.getInteger("ID_DATABASE_LOG", -1L)); //$NON-NLS-1$ logTable = r.getString("TABLE_NAME_LOG", null); //$NON-NLS-1$ useBatchId = r.getBoolean("USE_BATCHID", false); //$NON-NLS-1$ logfieldUsed = r.getBoolean("USE_LOGFIELD", false); //$NON-NLS-1$ maxDateConnection = DatabaseMeta.findDatabase(databases, r.getInteger("ID_DATABASE_MAXDATE", -1L)); //$NON-NLS-1$ maxDateTable = r.getString("TABLE_NAME_MAXDATE", null); //$NON-NLS-1$ maxDateField = r.getString("FIELD_NAME_MAXDATE", null); //$NON-NLS-1$ maxDateOffset = r.getNumber("OFFSET_MAXDATE", 0.0); //$NON-NLS-1$ maxDateDifference = r.getNumber("DIFF_MAXDATE", 0.0); //$NON-NLS-1$ createdUser = r.getString("CREATED_USER", null); //$NON-NLS-1$ createdDate = r.getDate("CREATED_DATE", null); //$NON-NLS-1$ modifiedUser = r.getString("MODIFIED_USER", null); //$NON-NLS-1$ modifiedDate = r.getDate("MODIFIED_DATE", null); //$NON-NLS-1$ // Optional: sizeRowset = Const.ROWS_IN_ROWSET; Long val_size_rowset = r.getInteger("SIZE_ROWSET"); //$NON-NLS-1$ if (val_size_rowset != null ) { sizeRowset = val_size_rowset.intValue(); } long id_directory = r.getInteger("ID_DIRECTORY", -1L); //$NON-NLS-1$ if (id_directory >= 0) { log.logDetailed(toString(), "ID_DIRECTORY=" + id_directory); //$NON-NLS-1$ // Set right directory... directory = directoryTree.findDirectory(id_directory); } usingUniqueConnections = rep.getTransAttributeBoolean(getID(), 0, Repository.TRANS_ATTRIBUTE_UNIQUE_CONNECTIONS); feedbackShown = !"N".equalsIgnoreCase( rep.getTransAttributeString(getID(), 0, Repository.TRANS_ATTRIBUTE_FEEDBACK_SHOWN) ); feedbackSize = (int) rep.getTransAttributeInteger(getID(), 0, Repository.TRANS_ATTRIBUTE_FEEDBACK_SIZE); usingThreadPriorityManagment = !"N".equalsIgnoreCase( rep.getTransAttributeString(getID(), 0, Repository.TRANS_ATTRIBUTE_USING_THREAD_PRIORITIES) ); // Performance monitoring for steps... // capturingStepPerformanceSnapShots = rep.getTransAttributeBoolean(getID(), 0, Repository.TRANS_ATTRIBUTE_CAPTURE_STEP_PERFORMANCE); stepPerformanceCapturingDelay = rep.getTransAttributeInteger(getID(), 0, Repository.TRANS_ATTRIBUTE_STEP_PERFORMANCE_CAPTURING_DELAY); } } catch (KettleDatabaseException dbe) { throw new KettleException(Messages.getString("TransMeta.Exception.UnableToLoadTransformationInfoFromRepository"), dbe); //$NON-NLS-1$ } finally { initializeVariablesFrom(null); setInternalKettleVariables(); } } public boolean isRepReference() { return isRepReference(getFilename(), this.getName()); } public boolean isFileReference() { return !isRepReference(getFilename(), this.getName()); } public static boolean isRepReference(String exactFilename, String exactTransname) { return Const.isEmpty(exactFilename) && !Const.isEmpty(exactTransname); } public static boolean isFileReference(String exactFilename, String exactTransname) { return !isRepReference(exactFilename, exactTransname); } /** Read a transformation with a certain name from a repository * * @param rep The repository to read from. * @param transname The name of the transformation. * @param repdir the path to the repository directory */ public TransMeta(Repository rep, String transname, RepositoryDirectory repdir) throws KettleException { this(rep, transname, repdir, null, true); } /** * Read a transformation with a certain name from a repository * * @param rep The repository to read from. * @param transname The name of the transformation. * @param repdir the path to the repository directory * @param setInternalVariables true if you want to set the internal variables based on this transformation information */ public TransMeta(Repository rep, String transname, RepositoryDirectory repdir, boolean setInternalVariables) throws KettleException { this(rep, transname, repdir, null, setInternalVariables); } /** Read a transformation with a certain name from a repository * * @param rep The repository to read from. * @param transname The name of the transformation. * @param repdir the path to the repository directory * @param monitor The progress monitor to display the progress of the file-open operation in a dialog */ public TransMeta(Repository rep, String transname, RepositoryDirectory repdir, ProgressMonitorListener monitor) throws KettleException { this(rep, transname, repdir, monitor, true); } /** Read a transformation with a certain name from a repository * * @param rep The repository to read from. * @param transname The name of the transformation. * @param repdir the path to the repository directory * @param monitor The progress monitor to display the progress of the file-open operation in a dialog * @param setInternalVariables true if you want to set the internal variables based on this transformation information */ public TransMeta(Repository rep, String transname, RepositoryDirectory repdir, ProgressMonitorListener monitor, boolean setInternalVariables) throws KettleException { this(); try { String pathAndName = repdir.isRoot() ? repdir + transname : repdir + RepositoryDirectory.DIRECTORY_SEPARATOR + transname; setName(transname); directory = repdir; directoryTree = directory.findRoot(); // Get the transformation id log.logDetailed(toString(), Messages.getString("TransMeta.Log.LookingForTransformation", transname ,directory.getPath() )); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (monitor != null) monitor.subTask(Messages.getString("TransMeta.Monitor.ReadingTransformationInfoTask.Title")); //$NON-NLS-1$ setID(rep.getTransformationID(transname, directory.getID())); if (monitor != null) monitor.worked(1); // If no valid id is available in the database, then give error... if (getID() > 0) { long noteids[] = rep.getTransNoteIDs(getID()); long stepids[] = rep.getStepIDs(getID()); long hopids[] = rep.getTransHopIDs(getID()); int nrWork = 3 + noteids.length + stepids.length + hopids.length; if (monitor != null) monitor.beginTask(Messages.getString("TransMeta.Monitor.LoadingTransformationTask.Title") + pathAndName, nrWork); //$NON-NLS-1$ log.logDetailed(toString(), Messages.getString("TransMeta.Log.LoadingTransformation", getName() )); //$NON-NLS-1$ //$NON-NLS-2$ // Load the common database connections if (monitor != null) monitor.subTask(Messages.getString("TransMeta.Monitor.ReadingTheAvailableSharedObjectsTask.Title")); //$NON-NLS-1$ try { sharedObjects = readSharedObjects(rep); } catch(Exception e) { LogWriter.getInstance().logError(toString(), Messages.getString("TransMeta.ErrorReadingSharedObjects.Message", e.toString())); LogWriter.getInstance().logError(toString(), Const.getStackTracker(e)); } if (monitor != null) monitor.worked(1); // Load the notes... if (monitor != null) monitor.subTask(Messages.getString("TransMeta.Monitor.ReadingNoteTask.Title")); //$NON-NLS-1$ for (int i = 0; i < noteids.length; i++) { NotePadMeta ni = new NotePadMeta(log, rep, noteids[i]); if (indexOfNote(ni) < 0) addNote(ni); if (monitor != null) monitor.worked(1); } if (monitor != null) monitor.subTask(Messages.getString("TransMeta.Monitor.ReadingStepsTask.Title")); //$NON-NLS-1$ rep.fillStepAttributesBuffer(getID()); // read all the attributes on one go! for (int i = 0; i < stepids.length; i++) { log.logDetailed(toString(), Messages.getString("TransMeta.Log.LoadingStepWithID") + stepids[i]); //$NON-NLS-1$ if (monitor != null) monitor.subTask(Messages.getString("TransMeta.Monitor.ReadingStepTask.Title") + (i + 1) + "/" + (stepids.length)); //$NON-NLS-1$ //$NON-NLS-2$ StepMeta stepMeta = new StepMeta(rep, stepids[i], databases, counters, partitionSchemas); // In this case, we just add or replace the shared steps. // The repository is considered "more central" addOrReplaceStep(stepMeta); if (monitor != null) monitor.worked(1); } if (monitor != null) monitor.worked(1); rep.setStepAttributesBuffer(null); // clear the buffer (should be empty anyway) // Have all StreamValueLookups, etc. reference the correct source steps... for (int i = 0; i < nrSteps(); i++) { StepMetaInterface sii = getStep(i).getStepMetaInterface(); sii.searchInfoAndTargetSteps(steps); } if (monitor != null) monitor.subTask(Messages.getString("TransMeta.Monitor.LoadingTransformationDetailsTask.Title")); //$NON-NLS-1$ loadRepTrans(rep); if (monitor != null) monitor.worked(1); if (monitor != null) monitor.subTask(Messages.getString("TransMeta.Monitor.ReadingHopTask.Title")); //$NON-NLS-1$ for (int i = 0; i < hopids.length; i++) { TransHopMeta hi = new TransHopMeta(rep, hopids[i], steps); addTransHop(hi); if (monitor != null) monitor.worked(1); } // Have all step partitioning meta-data reference the correct schemas that we just loaded // for (int i = 0; i < nrSteps(); i++) { StepPartitioningMeta stepPartitioningMeta = getStep(i).getStepPartitioningMeta(); if (stepPartitioningMeta!=null) { stepPartitioningMeta.setPartitionSchemaAfterLoading(partitionSchemas); } } // Have all step clustering schema meta-data reference the correct cluster schemas that we just loaded // for (int i = 0; i < nrSteps(); i++) { getStep(i).setClusterSchemaAfterLoading(clusterSchemas); } if (monitor != null) monitor.subTask(Messages.getString("TransMeta.Monitor.ReadingTheDependenciesTask.Title")); //$NON-NLS-1$ long depids[] = rep.getTransDependencyIDs(getID()); for (int i = 0; i < depids.length; i++) { TransDependency td = new TransDependency(rep, depids[i], databases); addDependency(td); } if (monitor != null) monitor.worked(1); // Also load the step error handling metadata // for (int i=0;i<nrSteps();i++) { StepMeta stepMeta = getStep(i); String sourceStep = rep.getStepAttributeString(stepMeta.getID(), "step_error_handling_source_step"); if (sourceStep!=null) { StepErrorMeta stepErrorMeta = new StepErrorMeta(this, rep, stepMeta, steps); stepErrorMeta.getSourceStep().setStepErrorMeta(stepErrorMeta); // a bit of a trick, I know. } } if (monitor != null) monitor.subTask(Messages.getString("TransMeta.Monitor.SortingStepsTask.Title")); //$NON-NLS-1$ sortSteps(); if (monitor != null) monitor.worked(1); if (monitor != null) monitor.done(); } else { throw new KettleException(Messages.getString("TransMeta.Exception.TransformationDoesNotExist") + name); //$NON-NLS-1$ } log.logDetailed(toString(), Messages.getString("TransMeta.Log.LoadedTransformation2", transname , String.valueOf(directory == null))); //$NON-NLS-1$ //$NON-NLS-2$ log.logDetailed(toString(), Messages.getString("TransMeta.Log.LoadedTransformation", transname , directory.getPath() )); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } catch (KettleDatabaseException e) { log.logError(toString(), Messages.getString("TransMeta.Log.DatabaseErrorOccuredReadingTransformation") + Const.CR + e); //$NON-NLS-1$ throw new KettleException(Messages.getString("TransMeta.Exception.DatabaseErrorOccuredReadingTransformation"), e); //$NON-NLS-1$ } catch (Exception e) { log.logError(toString(), Messages.getString("TransMeta.Log.DatabaseErrorOccuredReadingTransformation") + Const.CR + e); //$NON-NLS-1$ throw new KettleException(Messages.getString("TransMeta.Exception.DatabaseErrorOccuredReadingTransformation2"), e); //$NON-NLS-1$ } finally { initializeVariablesFrom(null); if (setInternalVariables) setInternalKettleVariables(); } } /** * Find the location of hop * * @param hi The hop queried * @return The location of the hop, -1 if nothing was found. */ public int indexOfTransHop(TransHopMeta hi) { return hops.indexOf(hi); } /** * Find the location of step * * @param stepMeta The step queried * @return The location of the step, -1 if nothing was found. */ public int indexOfStep(StepMeta stepMeta) { return steps.indexOf(stepMeta); } /* (non-Javadoc) * @see org.pentaho.di.trans.HasDatabaseInterface#indexOfDatabase(org.pentaho.di.core.database.DatabaseMeta) */ public int indexOfDatabase(DatabaseMeta ci) { return databases.indexOf(ci); } /** * Find the location of a note * * @param ni The note queried * @return The location of the note, -1 if nothing was found. */ public int indexOfNote(NotePadMeta ni) { return notes.indexOf(ni); } public String getFileType() { return LastUsedFile.FILE_TYPE_TRANSFORMATION; } public String[] getFilterNames() { return Const.getTransformationFilterNames(); } public String[] getFilterExtensions() { return Const.STRING_TRANS_FILTER_EXT; } public String getDefaultExtension() { return Const.STRING_TRANS_DEFAULT_EXT; } public String getXML() { Props props = null; if (Props.isInitialized()) props=Props.getInstance(); StringBuffer retval = new StringBuffer(800); retval.append(XMLHandler.openTag(XML_TAG)).append(Const.CR); //$NON-NLS-1$ retval.append(" ").append(XMLHandler.openTag(XML_TAG_INFO)).append(Const.CR); //$NON-NLS-1$ retval.append(" ").append(XMLHandler.addTagValue("name", name)); //$NON-NLS-1$ //$NON-NLS-2$ retval.append(" ").append(XMLHandler.addTagValue("description", description)); //$NON-NLS-1$ //$NON-NLS-2$ retval.append(" ").append(XMLHandler.addTagValue("extended_description", extended_description)); retval.append(" ").append(XMLHandler.addTagValue("trans_version", trans_version)); if ( trans_status >= 0 ) { retval.append(" ").append(XMLHandler.addTagValue("trans_status", trans_status)); } retval.append(" ").append(XMLHandler.addTagValue("directory", directory != null ? directory.getPath() : RepositoryDirectory.DIRECTORY_SEPARATOR)); //$NON-NLS-1$ //$NON-NLS-2$ retval.append(" <log>").append(Const.CR); //$NON-NLS-1$ retval.append(" ").append(XMLHandler.addTagValue("read", readStep == null ? "" : readStep.getName())); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ retval.append(" ").append(XMLHandler.addTagValue("write", writeStep == null ? "" : writeStep.getName())); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ retval.append(" ").append(XMLHandler.addTagValue("input", inputStep == null ? "" : inputStep.getName())); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ retval.append(" ").append(XMLHandler.addTagValue("output", outputStep == null ? "" : outputStep.getName())); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ retval.append(" ").append(XMLHandler.addTagValue("update", updateStep == null ? "" : updateStep.getName())); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ retval.append(" ").append(XMLHandler.addTagValue("rejected", rejectedStep == null ? "" : rejectedStep.getName())); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ retval.append(" ").append(XMLHandler.addTagValue("connection", logConnection == null ? "" : logConnection.getName())); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ retval.append(" ").append(XMLHandler.addTagValue("table", logTable)); //$NON-NLS-1$ //$NON-NLS-2$ retval.append(" ").append(XMLHandler.addTagValue("use_batchid", useBatchId)); //$NON-NLS-1$ //$NON-NLS-2$ retval.append(" ").append(XMLHandler.addTagValue("use_logfield", logfieldUsed)); //$NON-NLS-1$ //$NON-NLS-2$ retval.append(" </log>").append(Const.CR); //$NON-NLS-1$ retval.append(" <maxdate>").append(Const.CR); //$NON-NLS-1$ retval.append(" ").append(XMLHandler.addTagValue("connection", maxDateConnection == null ? "" : maxDateConnection.getName())); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ retval.append(" ").append(XMLHandler.addTagValue("table", maxDateTable)); //$NON-NLS-1$ //$NON-NLS-2$ retval.append(" ").append(XMLHandler.addTagValue("field", maxDateField)); //$NON-NLS-1$ //$NON-NLS-2$ retval.append(" ").append(XMLHandler.addTagValue("offset", maxDateOffset)); //$NON-NLS-1$ //$NON-NLS-2$ retval.append(" ").append(XMLHandler.addTagValue("maxdiff", maxDateDifference)); //$NON-NLS-1$ //$NON-NLS-2$ retval.append(" </maxdate>").append(Const.CR); //$NON-NLS-1$ retval.append(" ").append(XMLHandler.addTagValue("size_rowset", sizeRowset)); //$NON-NLS-1$ //$NON-NLS-2$ retval.append(" ").append(XMLHandler.addTagValue("sleep_time_empty", sleepTimeEmpty)); //$NON-NLS-1$ //$NON-NLS-2$ retval.append(" ").append(XMLHandler.addTagValue("sleep_time_full", sleepTimeFull)); //$NON-NLS-1$ //$NON-NLS-2$ retval.append(" ").append(XMLHandler.addTagValue("unique_connections", usingUniqueConnections)); //$NON-NLS-1$ //$NON-NLS-2$ retval.append(" ").append(XMLHandler.addTagValue("feedback_shown", feedbackShown)); //$NON-NLS-1$ //$NON-NLS-2$ retval.append(" ").append(XMLHandler.addTagValue("feedback_size", feedbackSize)); //$NON-NLS-1$ //$NON-NLS-2$ retval.append(" ").append(XMLHandler.addTagValue("using_thread_priorities", usingThreadPriorityManagment)); // $NON-NLS-1$ retval.append(" ").append(XMLHandler.addTagValue("shared_objects_file", sharedObjectsFile)); // $NON-NLS-1$ // Performance monitoring // retval.append(" ").append(XMLHandler.addTagValue("capture_step_performance", capturingStepPerformanceSnapShots)); // $NON-NLS-1$ retval.append(" ").append(XMLHandler.addTagValue("step_performance_capturing_delay", stepPerformanceCapturingDelay)); // $NON-NLS-1$ retval.append(" ").append(XMLHandler.openTag(XML_TAG_DEPENDENCIES)).append(Const.CR); //$NON-NLS-1$ for (int i = 0; i < nrDependencies(); i++) { TransDependency td = getDependency(i); retval.append(td.getXML()); } retval.append(" ").append(XMLHandler.closeTag(XML_TAG_DEPENDENCIES)).append(Const.CR); //$NON-NLS-1$ // The partitioning schemas... // retval.append(" ").append(XMLHandler.openTag(XML_TAG_PARTITIONSCHEMAS)).append(Const.CR); //$NON-NLS-1$ for (int i = 0; i < partitionSchemas.size(); i++) { PartitionSchema partitionSchema = partitionSchemas.get(i); retval.append(partitionSchema.getXML()); } retval.append(" ").append(XMLHandler.closeTag(XML_TAG_PARTITIONSCHEMAS)).append(Const.CR); //$NON-NLS-1$ // The slave servers... // retval.append(" ").append(XMLHandler.openTag(XML_TAG_SLAVESERVERS)).append(Const.CR); //$NON-NLS-1$ for (int i = 0; i < slaveServers.size(); i++) { SlaveServer slaveServer = slaveServers.get(i); retval.append(" ").append(slaveServer.getXML()).append(Const.CR); } retval.append(" ").append(XMLHandler.closeTag(XML_TAG_SLAVESERVERS)).append(Const.CR); //$NON-NLS-1$ // The cluster schemas... // retval.append(" ").append(XMLHandler.openTag(XML_TAG_CLUSTERSCHEMAS)).append(Const.CR); //$NON-NLS-1$ for (int i = 0; i < clusterSchemas.size(); i++) { ClusterSchema clusterSchema = clusterSchemas.get(i); retval.append(clusterSchema.getXML()); } retval.append(" ").append(XMLHandler.closeTag(XML_TAG_CLUSTERSCHEMAS)).append(Const.CR); //$NON-NLS-1$ retval.append(" ").append(XMLHandler.addTagValue("modified_user", modifiedUser)); retval.append(" ").append(XMLHandler.addTagValue("modified_date", modifiedDate)); retval.append(" ").append(XMLHandler.closeTag(XML_TAG_INFO)).append(Const.CR); //$NON-NLS-1$ retval.append(" ").append(XMLHandler.openTag(XML_TAG_NOTEPADS)).append(Const.CR); //$NON-NLS-1$ if (notes != null) for (int i = 0; i < nrNotes(); i++) { NotePadMeta ni = getNote(i); retval.append(ni.getXML()); } retval.append(" ").append(XMLHandler.closeTag(XML_TAG_NOTEPADS)).append(Const.CR); //$NON-NLS-1$ // The database connections... for (int i = 0; i < nrDatabases(); i++) { DatabaseMeta dbMeta = getDatabase(i); if (props!=null && props.areOnlyUsedConnectionsSavedToXML()) { if (isDatabaseConnectionUsed(dbMeta)) retval.append(dbMeta.getXML()); } else { retval.append(dbMeta.getXML()); } } retval.append(" ").append(XMLHandler.openTag(XML_TAG_ORDER)).append(Const.CR); //$NON-NLS-1$ for (int i = 0; i < nrTransHops(); i++) { TransHopMeta transHopMeta = getTransHop(i); retval.append(transHopMeta.getXML()); } retval.append(" ").append(XMLHandler.closeTag(XML_TAG_ORDER)).append(Const.CR); //$NON-NLS-1$ /* The steps... */ for (int i = 0; i < nrSteps(); i++) { StepMeta stepMeta = getStep(i); retval.append(stepMeta.getXML()); } /* The error handling metadata on the steps */ retval.append(" ").append(XMLHandler.openTag(XML_TAG_STEP_ERROR_HANDLING)).append(Const.CR); for (int i = 0; i < nrSteps(); i++) { StepMeta stepMeta = getStep(i); if (stepMeta.getStepErrorMeta()!=null) { retval.append(stepMeta.getStepErrorMeta().getXML()); } } retval.append(" ").append(XMLHandler.closeTag(XML_TAG_STEP_ERROR_HANDLING)).append(Const.CR); // The slave-step-copy/partition distribution. Only used for slave transformations in a clustering environment. retval.append(" ").append(slaveStepCopyPartitionDistribution.getXML()); // Is this a slave transformation or not? retval.append(" ").append(XMLHandler.addTagValue("slave_transformation", slaveTransformation)); retval.append("</").append(XML_TAG+">").append(Const.CR); //$NON-NLS-1$ return retval.toString(); } /** * Parse a file containing the XML that describes the transformation. * No default connections are loaded since no repository is available at this time. * Since the filename is set, internal variables are being set that relate to this. * * @param fname The filename */ public TransMeta(String fname) throws KettleXMLException { this(fname, true); } /** * Parse a file containing the XML that describes the transformation. * No default connections are loaded since no repository is available at this time. * * @param fname The filename * @param setInternalVariables true if you want to set the internal variables based on this transformation information */ public TransMeta(String fname, boolean setInternalVariables) throws KettleXMLException { this(fname, null, setInternalVariables); } /** * Parse a file containing the XML that describes the transformation. * * @param fname The filename * @param rep The repository to load the default set of connections from, null if no repository is avaailable */ public TransMeta(String fname, Repository rep) throws KettleXMLException { this(fname, rep, true); } /** * Parse a file containing the XML that describes the transformation. * * @param fname The filename * @param rep The repository to load the default set of connections from, null if no repository is avaailable * @param setInternalVariables true if you want to set the internal variables based on this transformation information */ public TransMeta(String fname, Repository rep, boolean setInternalVariables ) throws KettleXMLException { // OK, try to load using the VFS stuff... Document doc=null; try { doc = XMLHandler.loadXMLFile(KettleVFS.getFileObject(fname)); } catch (IOException e) { throw new KettleXMLException(Messages.getString("TransMeta.Exception.ErrorOpeningOrValidatingTheXMLFile", fname)+" : "+e.toString(), e); } if (doc != null) { // Clear the transformation clearUndo(); clear(); // Root node: Node transnode = XMLHandler.getSubNode(doc, XML_TAG); //$NON-NLS-1$ // Load from this node... loadXML(transnode, rep, setInternalVariables); setFilename(fname); } else { throw new KettleXMLException(Messages.getString("TransMeta.Exception.ErrorOpeningOrValidatingTheXMLFile", fname)); //$NON-NLS-1$ } } /* * Load the transformation from an XML node * * @param transnode The XML node to parse * @throws KettleXMLException * public TransMeta(Node transnode) throws KettleXMLException { loadXML(transnode); } */ /* * Parse a file containing the XML that describes the transformation. * (no repository is available to load default list of database connections from) * * @param transnode The XML node to load from * @throws KettleXMLException * private void loadXML(Node transnode) throws KettleXMLException { loadXML(transnode, null, false); } */ /** * Parse a file containing the XML that describes the transformation. * Specify a repository to load default list of database connections from and to reference in mappings etc. * * @param transnode The XML node to load from * @param rep the repository to reference. * @throws KettleXMLException */ public TransMeta(Node transnode, Repository rep) throws KettleXMLException { loadXML(transnode, rep, false); } /** * Parse a file containing the XML that describes the transformation. * * @param transnode The XML node to load from * @param rep The repository to load the default list of database connections from (null if no repository is available) * @param setInternalVariables true if you want to set the internal variables based on this transformation information * @throws KettleXMLException */ public void loadXML(Node transnode, Repository rep, boolean setInternalVariables ) throws KettleXMLException { Props props = null; if (Props.isInitialized()) { props=Props.getInstance(); } try { // Clear the transformation clearUndo(); clear(); // Read all the database connections from the repository to make sure that we don't overwrite any there by loading from XML. try { sharedObjectsFile = XMLHandler.getTagValue(transnode, "info", "shared_objects_file"); //$NON-NLS-1$ //$NON-NLS-2$ sharedObjects = readSharedObjects(rep); } catch(Exception e) { LogWriter.getInstance().logError(toString(), Messages.getString("TransMeta.ErrorReadingSharedObjects.Message", e.toString())); LogWriter.getInstance().logError(toString(), Const.getStackTracker(e)); } // Handle connections int n = XMLHandler.countNodes(transnode, DatabaseMeta.XML_TAG); //$NON-NLS-1$ log.logDebug(toString(), Messages.getString("TransMeta.Log.WeHaveConnections", String.valueOf(n) )); //$NON-NLS-1$ //$NON-NLS-2$ for (int i = 0; i < n; i++) { log.logDebug(toString(), Messages.getString("TransMeta.Log.LookingAtConnection") + i); //$NON-NLS-1$ Node nodecon = XMLHandler.getSubNodeByNr(transnode, DatabaseMeta.XML_TAG, i); //$NON-NLS-1$ DatabaseMeta dbcon = new DatabaseMeta(nodecon); dbcon.shareVariablesWith(this); DatabaseMeta exist = findDatabase(dbcon.getName()); if (exist == null) { addDatabase(dbcon); } else { if (!exist.isShared()) // otherwise, we just keep the shared connection. { boolean askOverwrite = Props.isInitialized() ? props.askAboutReplacingDatabaseConnections() : false; boolean overwrite = Props.isInitialized() ? props.replaceExistingDatabaseConnections() : true; if (askOverwrite) { if( SpoonFactory.getInstance() != null ) { Object res[] = SpoonFactory.getInstance().messageDialogWithToggle("Warning", null, "Connection ["+dbcon.getName()+"] already exists, do you want to overwrite this database connection?", Const.WARNING, new String[] { Messages.getString("System.Button.Yes"), //$NON-NLS-1$ Messages.getString("System.Button.No") },//$NON-NLS-1$ 1, "Please, don't show this warning anymore.", !props.askAboutReplacingDatabaseConnections() ); int idx = ((Integer)res[0]).intValue(); boolean toggleState = ((Boolean)res[1]).booleanValue(); props.setAskAboutReplacingDatabaseConnections(!toggleState); overwrite = ((idx&0xFF)==0); // Yes means: overwrite } } if (overwrite) { int idx = indexOfDatabase(exist); removeDatabase(idx); addDatabase(idx, dbcon); } } } } // Read the notes... Node notepadsnode = XMLHandler.getSubNode(transnode, XML_TAG_NOTEPADS); //$NON-NLS-1$ int nrnotes = XMLHandler.countNodes(notepadsnode, NotePadMeta.XML_TAG); //$NON-NLS-1$ for (int i = 0; i < nrnotes; i++) { Node notepadnode = XMLHandler.getSubNodeByNr(notepadsnode, NotePadMeta.XML_TAG, i); //$NON-NLS-1$ NotePadMeta ni = new NotePadMeta(notepadnode); notes.add(ni); } // Handle Steps int s = XMLHandler.countNodes(transnode, StepMeta.XML_TAG); //$NON-NLS-1$ log.logDebug(toString(), Messages.getString("TransMeta.Log.ReadingSteps") + s + " steps..."); //$NON-NLS-1$ //$NON-NLS-2$ for (int i = 0; i < s; i++) { Node stepnode = XMLHandler.getSubNodeByNr(transnode, StepMeta.XML_TAG, i); //$NON-NLS-1$ log.logDebug(toString(), Messages.getString("TransMeta.Log.LookingAtStep") + i); //$NON-NLS-1$ StepMeta stepMeta = new StepMeta(stepnode, databases, counters); // Check if the step exists and if it's a shared step. // If so, then we will keep the shared version, not this one. // The stored XML is only for backup purposes. // StepMeta check = findStep(stepMeta.getName()); if (check!=null) { if (!check.isShared()) // Don't overwrite shared objects { addOrReplaceStep(stepMeta); } else { check.setDraw(stepMeta.isDrawn()); // Just keep the drawn flag and location check.setLocation(stepMeta.getLocation()); } } else { addStep(stepMeta); // simply add it. } } // Read the error handling code of the steps... // Node errorHandlingNode = XMLHandler.getSubNode(transnode, XML_TAG_STEP_ERROR_HANDLING); int nrErrorHandlers = XMLHandler.countNodes(errorHandlingNode, StepErrorMeta.XML_TAG); for (int i=0;i<nrErrorHandlers;i++) { Node stepErrorMetaNode = XMLHandler.getSubNodeByNr(errorHandlingNode, StepErrorMeta.XML_TAG, i); StepErrorMeta stepErrorMeta = new StepErrorMeta(this, stepErrorMetaNode, steps); stepErrorMeta.getSourceStep().setStepErrorMeta(stepErrorMeta); // a bit of a trick, I know. } // Have all StreamValueLookups, etc. reference the correct source steps... // for (int i = 0; i < nrSteps(); i++) { StepMeta stepMeta = getStep(i); StepMetaInterface sii = stepMeta.getStepMetaInterface(); if (sii != null) sii.searchInfoAndTargetSteps(steps); } // Handle Hops // Node ordernode = XMLHandler.getSubNode(transnode, XML_TAG_ORDER); //$NON-NLS-1$ n = XMLHandler.countNodes(ordernode, TransHopMeta.XML_TAG); //$NON-NLS-1$ log.logDebug(toString(), Messages.getString("TransMeta.Log.WeHaveHops") + n + " hops..."); //$NON-NLS-1$ //$NON-NLS-2$ for (int i = 0; i < n; i++) { log.logDebug(toString(), Messages.getString("TransMeta.Log.LookingAtHop") + i); //$NON-NLS-1$ Node hopnode = XMLHandler.getSubNodeByNr(ordernode, TransHopMeta.XML_TAG, i); //$NON-NLS-1$ TransHopMeta hopinf = new TransHopMeta(hopnode, steps); addTransHop(hopinf); } // // get transformation info: // Node infonode = XMLHandler.getSubNode(transnode, XML_TAG_INFO); //$NON-NLS-1$ // Name // name = XMLHandler.getTagValue(infonode, "name"); //$NON-NLS-1$ // description // description = XMLHandler.getTagValue(infonode, "description"); // extended description // extended_description = XMLHandler.getTagValue(infonode, "extended_description"); // trans version // trans_version = XMLHandler.getTagValue(infonode, "trans_version"); // trans status // trans_status = Const.toInt(XMLHandler.getTagValue(infonode, "trans_status"),-1); // Optionally load the repository directory... // if (rep!=null) { String directoryPath = XMLHandler.getTagValue(infonode, "directory"); if (directoryPath!=null) { directory = rep.getDirectoryTree().findDirectory(directoryPath); } } // Logging method... readStep = findStep(XMLHandler.getTagValue(infonode, "log", "read")); //$NON-NLS-1$ //$NON-NLS-2$ writeStep = findStep(XMLHandler.getTagValue(infonode, "log", "write")); //$NON-NLS-1$ //$NON-NLS-2$ inputStep = findStep(XMLHandler.getTagValue(infonode, "log", "input")); //$NON-NLS-1$ //$NON-NLS-2$ outputStep = findStep(XMLHandler.getTagValue(infonode, "log", "output")); //$NON-NLS-1$ //$NON-NLS-2$ updateStep = findStep(XMLHandler.getTagValue(infonode, "log", "update")); //$NON-NLS-1$ //$NON-NLS-2$ rejectedStep = findStep(XMLHandler.getTagValue(infonode, "log", "rejected")); //$NON-NLS-1$ //$NON-NLS-2$ String logcon = XMLHandler.getTagValue(infonode, "log", "connection"); //$NON-NLS-1$ //$NON-NLS-2$ logConnection = findDatabase(logcon); logTable = XMLHandler.getTagValue(infonode, "log", "table"); //$NON-NLS-1$ //$NON-NLS-2$ useBatchId = "Y".equalsIgnoreCase(XMLHandler.getTagValue(infonode, "log", "use_batchid")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ logfieldUsed= "Y".equalsIgnoreCase(XMLHandler.getTagValue(infonode, "log", "USE_LOGFIELD")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ // Maxdate range options... String maxdatcon = XMLHandler.getTagValue(infonode, "maxdate", "connection"); //$NON-NLS-1$ //$NON-NLS-2$ maxDateConnection = findDatabase(maxdatcon); maxDateTable = XMLHandler.getTagValue(infonode, "maxdate", "table"); //$NON-NLS-1$ //$NON-NLS-2$ maxDateField = XMLHandler.getTagValue(infonode, "maxdate", "field"); //$NON-NLS-1$ //$NON-NLS-2$ String offset = XMLHandler.getTagValue(infonode, "maxdate", "offset"); //$NON-NLS-1$ //$NON-NLS-2$ maxDateOffset = Const.toDouble(offset, 0.0); String mdiff = XMLHandler.getTagValue(infonode, "maxdate", "maxdiff"); //$NON-NLS-1$ //$NON-NLS-2$ maxDateDifference = Const.toDouble(mdiff, 0.0); // Check the dependencies as far as dates are concerned... // We calculate BEFORE we run the MAX of these dates // If the date is larger then enddate, startdate is set to MIN_DATE // Node depsNode = XMLHandler.getSubNode(infonode, XML_TAG_DEPENDENCIES); //$NON-NLS-1$ int nrDeps = XMLHandler.countNodes(depsNode, TransDependency.XML_TAG); //$NON-NLS-1$ for (int i = 0; i < nrDeps; i++) { Node depNode = XMLHandler.getSubNodeByNr(depsNode, TransDependency.XML_TAG, i); //$NON-NLS-1$ TransDependency transDependency = new TransDependency(depNode, databases); if (transDependency.getDatabase() != null && transDependency.getFieldname() != null) { addDependency(transDependency); } } // Read the partitioning schemas // Node partSchemasNode = XMLHandler.getSubNode(infonode, XML_TAG_PARTITIONSCHEMAS); //$NON-NLS-1$ int nrPartSchemas = XMLHandler.countNodes(partSchemasNode, PartitionSchema.XML_TAG); //$NON-NLS-1$ for (int i = 0 ; i < nrPartSchemas ; i++) { Node partSchemaNode = XMLHandler.getSubNodeByNr(partSchemasNode, PartitionSchema.XML_TAG, i); PartitionSchema partitionSchema = new PartitionSchema(partSchemaNode); // Check if the step exists and if it's a shared step. // If so, then we will keep the shared version, not this one. // The stored XML is only for backup purposes. // PartitionSchema check = findPartitionSchema(partitionSchema.getName()); if (check!=null) { if (!check.isShared()) // we don't overwrite shared objects. { addOrReplacePartitionSchema(partitionSchema); } } else { partitionSchemas.add(partitionSchema); } } // Have all step partitioning meta-data reference the correct schemas that we just loaded // for (int i = 0; i < nrSteps(); i++) { StepPartitioningMeta stepPartitioningMeta = getStep(i).getStepPartitioningMeta(); if (stepPartitioningMeta!=null) { stepPartitioningMeta.setPartitionSchemaAfterLoading(partitionSchemas); } StepPartitioningMeta targetStepPartitioningMeta = getStep(i).getTargetStepPartitioningMeta(); if (targetStepPartitioningMeta!=null) { targetStepPartitioningMeta.setPartitionSchemaAfterLoading(partitionSchemas); } } // Read the slave servers... // Node slaveServersNode = XMLHandler.getSubNode(infonode, XML_TAG_SLAVESERVERS); //$NON-NLS-1$ int nrSlaveServers = XMLHandler.countNodes(slaveServersNode, SlaveServer.XML_TAG); //$NON-NLS-1$ for (int i = 0 ; i < nrSlaveServers ; i++) { Node slaveServerNode = XMLHandler.getSubNodeByNr(slaveServersNode, SlaveServer.XML_TAG, i); SlaveServer slaveServer = new SlaveServer(slaveServerNode); // Check if the object exists and if it's a shared object. // If so, then we will keep the shared version, not this one. // The stored XML is only for backup purposes. SlaveServer check = findSlaveServer(slaveServer.getName()); if (check!=null) { if (!check.isShared()) // we don't overwrite shared objects. { addOrReplaceSlaveServer(slaveServer); } } else { slaveServers.add(slaveServer); } } // Read the cluster schemas // Node clusterSchemasNode = XMLHandler.getSubNode(infonode, XML_TAG_CLUSTERSCHEMAS); //$NON-NLS-1$ int nrClusterSchemas = XMLHandler.countNodes(clusterSchemasNode, ClusterSchema.XML_TAG); //$NON-NLS-1$ for (int i = 0 ; i < nrClusterSchemas ; i++) { Node clusterSchemaNode = XMLHandler.getSubNodeByNr(clusterSchemasNode, ClusterSchema.XML_TAG, i); ClusterSchema clusterSchema = new ClusterSchema(clusterSchemaNode, slaveServers); // Check if the object exists and if it's a shared object. // If so, then we will keep the shared version, not this one. // The stored XML is only for backup purposes. ClusterSchema check = findClusterSchema(clusterSchema.getName()); if (check!=null) { if (!check.isShared()) // we don't overwrite shared objects. { addOrReplaceClusterSchema(clusterSchema); } } else { clusterSchemas.add(clusterSchema); } } // Have all step clustering schema meta-data reference the correct cluster schemas that we just loaded // for (int i = 0; i < nrSteps(); i++) { getStep(i).setClusterSchemaAfterLoading(clusterSchemas); } String srowset = XMLHandler.getTagValue(infonode, "size_rowset"); //$NON-NLS-1$ sizeRowset = Const.toInt(srowset, Const.ROWS_IN_ROWSET); sleepTimeEmpty = Const.toInt(XMLHandler.getTagValue(infonode, "sleep_time_empty"), Const.TIMEOUT_GET_MILLIS); //$NON-NLS-1$ sleepTimeFull = Const.toInt(XMLHandler.getTagValue(infonode, "sleep_time_full"), Const.TIMEOUT_PUT_MILLIS); //$NON-NLS-1$ usingUniqueConnections = "Y".equalsIgnoreCase( XMLHandler.getTagValue(infonode, "unique_connections") ); //$NON-NLS-1$ feedbackShown = !"N".equalsIgnoreCase( XMLHandler.getTagValue(infonode, "feedback_shown") ); //$NON-NLS-1$ feedbackSize = Const.toInt(XMLHandler.getTagValue(infonode, "feedback_size"), Const.ROWS_UPDATE); //$NON-NLS-1$ usingThreadPriorityManagment = !"N".equalsIgnoreCase( XMLHandler.getTagValue(infonode, "using_thread_priorities") ); //$NON-NLS-1$ // Performance monitoring for steps... // capturingStepPerformanceSnapShots = "Y".equalsIgnoreCase(XMLHandler.getTagValue(infonode, "capture_step_performance")); // $NON-NLS-1$ $NON-NLS-2$ stepPerformanceCapturingDelay = Const.toLong(XMLHandler.getTagValue(infonode, "step_performance_capturing_delay"), 1000); // $NON-NLS-1$ // Created user/date createdUser = XMLHandler.getTagValue(infonode, "created_user"); String createDate = XMLHandler.getTagValue(infonode, "created_date"); if (createDate!=null) { createdDate = XMLHandler.stringToDate(createDate); } // Changed user/date modifiedUser = XMLHandler.getTagValue(infonode, "modified_user"); String modDate = XMLHandler.getTagValue(infonode, "modified_date"); if (modDate!=null) { modifiedDate = XMLHandler.stringToDate(modDate); } Node partitionDistNode = XMLHandler.getSubNode(transnode, SlaveStepCopyPartitionDistribution.XML_TAG); if (partitionDistNode!=null) { slaveStepCopyPartitionDistribution = new SlaveStepCopyPartitionDistribution(partitionDistNode); } else { slaveStepCopyPartitionDistribution = new SlaveStepCopyPartitionDistribution(); // leave empty } // Is this a slave transformation? // slaveTransformation = "Y".equalsIgnoreCase(XMLHandler.getTagValue(transnode, "slave_transformation")); log.logDebug(toString(), Messages.getString("TransMeta.Log.NumberOfStepsReaded") + nrSteps()); //$NON-NLS-1$ log.logDebug(toString(), Messages.getString("TransMeta.Log.NumberOfHopsReaded") + nrTransHops()); //$NON-NLS-1$ sortSteps(); } catch (KettleXMLException xe) { throw new KettleXMLException(Messages.getString("TransMeta.Exception.ErrorReadingTransformation"), xe); //$NON-NLS-1$ } catch (KettleException e) { throw new KettleXMLException(e); } finally { initializeVariablesFrom(null); if (setInternalVariables) setInternalKettleVariables(); } } public SharedObjects readSharedObjects(Repository rep) throws KettleException { if ( rep != null ) { sharedObjectsFile = rep.getTransAttributeString(getId(), 0, "SHARED_FILE"); } // Extract the shared steps, connections, etc. using the SharedObjects class // String soFile = environmentSubstitute(sharedObjectsFile); SharedObjects sharedObjects = new SharedObjects(soFile); // First read the databases... // We read databases & slaves first because there might be dependencies that need to be resolved. // for (SharedObjectInterface object : sharedObjects.getObjectsMap().values()) { if (object instanceof DatabaseMeta) { DatabaseMeta databaseMeta = (DatabaseMeta) object; databaseMeta.shareVariablesWith(this); addOrReplaceDatabase(databaseMeta); } else if (object instanceof SlaveServer) { SlaveServer slaveServer = (SlaveServer) object; addOrReplaceSlaveServer(slaveServer); } else if (object instanceof StepMeta) { StepMeta stepMeta = (StepMeta) object; addOrReplaceStep(stepMeta); } else if (object instanceof PartitionSchema) { PartitionSchema partitionSchema = (PartitionSchema) object; addOrReplacePartitionSchema(partitionSchema); } else if (object instanceof ClusterSchema) { ClusterSchema clusterSchema = (ClusterSchema) object; addOrReplaceClusterSchema(clusterSchema); } } if (rep!=null) { readDatabases(rep, true); readPartitionSchemas(rep, true); readSlaves(rep, true); readClusters(rep, true); } return sharedObjects; } /** * Gives you an List of all the steps that are at least used in one active hop. These steps will be used to * execute the transformation. The others will not be executed. * Update 3.0 : we also add those steps that are not linked to another hop, but have at least one remote input or output step defined. * * @param all Set to true if you want to get ALL the steps from the transformation. * @return A ArrayList of steps */ public List<StepMeta> getTransHopSteps(boolean all) { List<StepMeta> st = new ArrayList<StepMeta>(); int idx; for (int x = 0; x < nrTransHops(); x++) { TransHopMeta hi = getTransHop(x); if (hi.isEnabled() || all) { idx = st.indexOf(hi.getFromStep()); // FROM if (idx < 0) st.add(hi.getFromStep()); idx = st.indexOf(hi.getToStep()); // TO if (idx < 0) st.add(hi.getToStep()); } } // Also, add the steps that need to be painted, but are not part of a hop for (int x = 0; x < nrSteps(); x++) { StepMeta stepMeta = getStep(x); if (stepMeta.isDrawn() && !isStepUsedInTransHops(stepMeta)) { st.add(stepMeta); } if (!stepMeta.getRemoteInputSteps().isEmpty() || !stepMeta.getRemoteOutputSteps().isEmpty()) { if (!st.contains(stepMeta)) st.add(stepMeta); } } return st; } /** * Get the name of the transformation * * @return The name of the transformation */ public String getName() { return name; } /** * Set the name of the transformation. * * @param n The new name of the transformation */ public void setName(String n) { name = n; setInternalKettleVariables(); } /** * Builds a name - if no name is set, yet - from the filename */ public void nameFromFilename() { if (!Const.isEmpty(filename)) { name = Const.createName(filename); } } /** * Get the filename (if any) of the transformation * * @return The filename of the transformation. */ public String getFilename() { return filename; } /** * Set the filename of the transformation * * @param fname The new filename of the transformation. */ public void setFilename(String fname) { filename = fname; setInternalKettleVariables(); } /** * Determines if a step has been used in a hop or not. * * @param stepMeta The step queried. * @return True if a step is used in a hop (active or not), false if this is not the case. */ public boolean isStepUsedInTransHops(StepMeta stepMeta) { TransHopMeta fr = findTransHopFrom(stepMeta); TransHopMeta to = findTransHopTo(stepMeta); if (fr != null || to != null) return true; return false; } /** * Sets the changed parameter of the transformation. * * @param ch True if you want to mark the transformation as changed, false if not. */ public void setChanged(boolean ch) { if (ch) setChanged(); else clearChanged(); } /** * Clears the different changed flags of the transformation. * */ public void clearChanged() { changed_steps = false; changed_databases = false; changed_hops = false; changed_notes = false; for (int i = 0; i < nrSteps(); i++) { getStep(i).setChanged(false); if (getStep(i).getStepPartitioningMeta() != null) { getStep(i).getStepPartitioningMeta().hasChanged(false); } } for (int i = 0; i < nrDatabases(); i++) { getDatabase(i).setChanged(false); } for (int i = 0; i < nrTransHops(); i++) { getTransHop(i).setChanged(false); } for (int i = 0; i < nrNotes(); i++) { getNote(i).setChanged(false); } for (int i = 0; i < partitionSchemas.size(); i++) { partitionSchemas.get(i).setChanged(false); } for (int i = 0; i < clusterSchemas.size(); i++) { clusterSchemas.get(i).setChanged(false); } super.clearChanged(); } /* (non-Javadoc) * @see org.pentaho.di.trans.HasDatabaseInterface#haveConnectionsChanged() */ public boolean haveConnectionsChanged() { if (changed_databases) return true; for (int i = 0; i < nrDatabases(); i++) { DatabaseMeta ci = getDatabase(i); if (ci.hasChanged()) return true; } return false; } /** * Checks whether or not the steps have changed. * * @return True if the connections have been changed. */ public boolean haveStepsChanged() { if (changed_steps) return true; for (int i = 0; i < nrSteps(); i++) { StepMeta stepMeta = getStep(i); if (stepMeta.hasChanged()) return true; if (stepMeta.getStepPartitioningMeta() != null && stepMeta.getStepPartitioningMeta().hasChanged() ) return true; } return false; } /** * Checks whether or not any of the hops have been changed. * * @return True if a hop has been changed. */ public boolean haveHopsChanged() { if (changed_hops) return true; for (int i = 0; i < nrTransHops(); i++) { TransHopMeta hi = getTransHop(i); if (hi.hasChanged()) return true; } return false; } /** * Checks whether or not any of the notes have been changed. * * @return True if the notes have been changed. */ public boolean haveNotesChanged() { if (changed_notes) return true; for (int i = 0; i < nrNotes(); i++) { NotePadMeta ni = getNote(i); if (ni.hasChanged()) return true; } return false; } /** * Checks whether or not any of the partitioning schemas have been changed. * * @return True if the partitioning schemas have been changed. */ public boolean havePartitionSchemasChanged() { for (int i = 0; i < partitionSchemas.size(); i++) { PartitionSchema ps = partitionSchemas.get(i); if (ps.hasChanged()) return true; } return false; } /** * Checks whether or not any of the clustering schemas have been changed. * * @return True if the clustering schemas have been changed. */ public boolean haveClusterSchemasChanged() { for (int i = 0; i < clusterSchemas.size(); i++) { ClusterSchema cs = clusterSchemas.get(i); if (cs.hasChanged()) return true; } return false; } /** * Checks whether or not the transformation has changed. * * @return True if the transformation has changed. */ public boolean hasChanged() { if (super.hasChanged()) return true; if (haveConnectionsChanged()) return true; if (haveStepsChanged()) return true; if (haveHopsChanged()) return true; if (haveNotesChanged()) return true; if (havePartitionSchemasChanged()) return true; if (haveClusterSchemasChanged()) return true; return false; } /** * See if there are any loops in the transformation, starting at the indicated step. This works by looking at all * the previous steps. If you keep going backward and find the step, there is a loop. Both the informational and the * normal steps need to be checked for loops! * * @param stepMeta The step position to start looking * * @return True if a loop has been found, false if no loop is found. */ public boolean hasLoop(StepMeta stepMeta) { return hasLoop(stepMeta, null, true) || hasLoop(stepMeta, null, false); } /** * See if there are any loops in the transformation, starting at the indicated step. This works by looking at all * the previous steps. If you keep going backward and find the orginal step again, there is a loop. * * @param stepMeta The step position to start looking * @param lookup The original step when wandering around the transformation. * @param info Check the informational steps or not. * * @return True if a loop has been found, false if no loop is found. */ public boolean hasLoop(StepMeta stepMeta, StepMeta lookup, boolean info) { int nr = findNrPrevSteps(stepMeta, info); for (int i = 0; i < nr; i++) { StepMeta prevStepMeta = findPrevStep(stepMeta, i, info); if (prevStepMeta != null) { if (prevStepMeta.equals(stepMeta)) return true; if (prevStepMeta.equals(lookup)) return true; if (hasLoop(prevStepMeta, lookup == null ? stepMeta : lookup, info)) return true; } } return false; } /** * Mark all steps in the transformation as selected. * */ public void selectAll() { int i; for (i = 0; i < nrSteps(); i++) { StepMeta stepMeta = getStep(i); stepMeta.setSelected(true); } for (i = 0; i < nrNotes(); i++) { NotePadMeta ni = getNote(i); ni.setSelected(true); } setChanged(); notifyObservers("refreshGraph"); } /** * Clear the selection of all steps. * */ public void unselectAll() { int i; for (i = 0; i < nrSteps(); i++) { StepMeta stepMeta = getStep(i); stepMeta.setSelected(false); } for (i = 0; i < nrNotes(); i++) { NotePadMeta ni = getNote(i); ni.setSelected(false); } } /** * Count the number of selected steps in this transformation * * @return The number of selected steps. */ public int nrSelectedSteps() { int i, count; count = 0; for (i = 0; i < nrSteps(); i++) { StepMeta stepMeta = getStep(i); if (stepMeta.isSelected() && stepMeta.isDrawn()) count++; } return count; } /** * Get the selected step at a certain location * * @param nr The location * @return The selected step */ public StepMeta getSelectedStep(int nr) { int i, count; count = 0; for (i = 0; i < nrSteps(); i++) { StepMeta stepMeta = getStep(i); if (stepMeta.isSelected() && stepMeta.isDrawn()) { if (nr == count) return stepMeta; count++; } } return null; } /** * Count the number of selected notes in this transformation * * @return The number of selected notes. */ public int nrSelectedNotes() { int i, count; count = 0; for (i = 0; i < nrNotes(); i++) { NotePadMeta ni = getNote(i); if (ni.isSelected()) count++; } return count; } /** * Get the selected note at a certain index * * @param nr The index * @return The selected note */ public NotePadMeta getSelectedNote(int nr) { int i, count; count = 0; for (i = 0; i < nrNotes(); i++) { NotePadMeta ni = getNote(i); if (ni.isSelected()) { if (nr == count) return ni; count++; } } return null; } /** * Get an array of all the selected step and note locations * * @return The selected step and notes locations. */ public Point[] getSelectedStepLocations() { List<Point> points = new ArrayList<Point>(); for (int i = 0; i < nrSelectedSteps(); i++) { StepMeta stepMeta = getSelectedStep(i); Point p = stepMeta.getLocation(); points.add(new Point(p.x, p.y)); // explicit copy of location } return points.toArray(new Point[points.size()]); } /** * Get an array of all the selected step and note locations * * @return The selected step and notes locations. */ public Point[] getSelectedNoteLocations() { List<Point> points = new ArrayList<Point>(); for (int i = 0; i < nrSelectedNotes(); i++) { NotePadMeta ni = getSelectedNote(i); Point p = ni.getLocation(); points.add(new Point(p.x, p.y)); // explicit copy of location } return points.toArray(new Point[points.size()]); } /** * Get an array of all the selected steps * * @return An array of all the selected steps. */ public StepMeta[] getSelectedSteps() { int sels = nrSelectedSteps(); if (sels == 0) return null; StepMeta retval[] = new StepMeta[sels]; for (int i = 0; i < sels; i++) { StepMeta stepMeta = getSelectedStep(i); retval[i] = stepMeta; } return retval; } /** * Get an array of all the selected steps * * @return A list containing all the selected & drawn steps. */ public List<GUIPositionInterface> getSelectedDrawnStepsList() { List<GUIPositionInterface> list = new ArrayList<GUIPositionInterface>(); for (int i = 0; i < nrSteps(); i++) { StepMeta stepMeta = getStep(i); if (stepMeta.isDrawn() && stepMeta.isSelected()) list.add(stepMeta); } return list; } /** * Get an array of all the selected notes * * @return An array of all the selected notes. */ public NotePadMeta[] getSelectedNotes() { int sels = nrSelectedNotes(); if (sels == 0) return null; NotePadMeta retval[] = new NotePadMeta[sels]; for (int i = 0; i < sels; i++) { NotePadMeta si = getSelectedNote(i); retval[i] = si; } return retval; } /** * Get an array of all the selected step names * * @return An array of all the selected step names. */ public String[] getSelectedStepNames() { int sels = nrSelectedSteps(); if (sels == 0) return null; String retval[] = new String[sels]; for (int i = 0; i < sels; i++) { StepMeta stepMeta = getSelectedStep(i); retval[i] = stepMeta.getName(); } return retval; } /** * Get an array of the locations of an array of steps * * @param steps An array of steps * @return an array of the locations of an array of steps */ public int[] getStepIndexes(StepMeta steps[]) { int retval[] = new int[steps.length]; for (int i = 0; i < steps.length; i++) { retval[i] = indexOfStep(steps[i]); } return retval; } /** * Get an array of the locations of an array of notes * * @param notes An array of notes * @return an array of the locations of an array of notes */ public int[] getNoteIndexes(NotePadMeta notes[]) { int retval[] = new int[notes.length]; for (int i = 0; i < notes.length; i++) retval[i] = indexOfNote(notes[i]); return retval; } /** * Get the maximum number of undo operations possible * * @return The maximum number of undo operations that are allowed. */ public int getMaxUndo() { return max_undo; } /** * Sets the maximum number of undo operations that are allowed. * * @param mu The maximum number of undo operations that are allowed. */ public void setMaxUndo(int mu) { max_undo = mu; while (undo.size() > mu && undo.size() > 0) undo.remove(0); } /** * Add an undo operation to the undo list * * @param from array of objects representing the old state * @param to array of objectes representing the new state * @param pos An array of object locations * @param prev An array of points representing the old positions * @param curr An array of points representing the new positions * @param type_of_change The type of change that's being done to the transformation. * @param nextAlso indicates that the next undo operation needs to follow this one. */ public void addUndo(Object from[], Object to[], int pos[], Point prev[], Point curr[], int type_of_change, boolean nextAlso) { // First clean up after the current position. // Example: position at 3, size=5 // 012345 // ^ // remove 34 // Add 4 // 01234 while (undo.size() > undo_position + 1 && undo.size() > 0) { int last = undo.size() - 1; undo.remove(last); } TransAction ta = new TransAction(); switch (type_of_change) { case TYPE_UNDO_CHANGE: ta.setChanged(from, to, pos); break; case TYPE_UNDO_DELETE: ta.setDelete(from, pos); break; case TYPE_UNDO_NEW: ta.setNew(from, pos); break; case TYPE_UNDO_POSITION: ta.setPosition(from, pos, prev, curr); break; } ta.setNextAlso(nextAlso); undo.add(ta); undo_position++; if (undo.size() > max_undo) { undo.remove(0); undo_position--; } } /** * Get the previous undo operation and change the undo pointer * * @return The undo transaction to be performed. */ public TransAction previousUndo() { if (undo.isEmpty() || undo_position < 0) return null; // No undo left! TransAction retval = undo.get(undo_position); undo_position--; return retval; } /** * View current undo, don't change undo position * * @return The current undo transaction */ public TransAction viewThisUndo() { if (undo.isEmpty() || undo_position < 0) return null; // No undo left! TransAction retval = undo.get(undo_position); return retval; } /** * View previous undo, don't change undo position * * @return The previous undo transaction */ public TransAction viewPreviousUndo() { if (undo.isEmpty() || undo_position - 1 < 0) return null; // No undo left! TransAction retval = undo.get(undo_position - 1); return retval; } /** * Get the next undo transaction on the list. Change the undo pointer. * * @return The next undo transaction (for redo) */ public TransAction nextUndo() { int size = undo.size(); if (size == 0 || undo_position >= size - 1) return null; // no redo left... undo_position++; TransAction retval = undo.get(undo_position); return retval; } /** * Get the next undo transaction on the list. * * @return The next undo transaction (for redo) */ public TransAction viewNextUndo() { int size = undo.size(); if (size == 0 || undo_position >= size - 1) return null; // no redo left... TransAction retval = undo.get(undo_position + 1); return retval; } /** * Get the maximum size of the canvas by calculating the maximum location of a step * * @return Maximum coordinate of a step in the transformation + (100,100) for safety. */ public Point getMaximum() { int maxx = 0, maxy = 0; for (int i = 0; i < nrSteps(); i++) { StepMeta stepMeta = getStep(i); Point loc = stepMeta.getLocation(); if (loc.x > maxx) maxx = loc.x; if (loc.y > maxy) maxy = loc.y; } for (int i = 0; i < nrNotes(); i++) { NotePadMeta notePadMeta = getNote(i); Point loc = notePadMeta.getLocation(); if (loc.x + notePadMeta.width > maxx) maxx = loc.x + notePadMeta.width; if (loc.y + notePadMeta.height > maxy) maxy = loc.y + notePadMeta.height; } return new Point(maxx + 100, maxy + 100); } /** * Get the names of all the steps. * * @return An array of step names. */ public String[] getStepNames() { String retval[] = new String[nrSteps()]; for (int i = 0; i < nrSteps(); i++) retval[i] = getStep(i).getName(); return retval; } /** * Get all the steps in an array. * * @return An array of all the steps in the transformation. */ public StepMeta[] getStepsArray() { StepMeta retval[] = new StepMeta[nrSteps()]; for (int i = 0; i < nrSteps(); i++) retval[i] = getStep(i); return retval; } /** * Look in the transformation and see if we can find a step in a previous location starting somewhere. * * @param startStep The starting step * @param stepToFind The step to look for backward in the transformation * @return true if we can find the step in an earlier location in the transformation. */ public boolean findPrevious(StepMeta startStep, StepMeta stepToFind) { // Normal steps int nrPrevious = findNrPrevSteps(startStep, false); for (int i = 0; i < nrPrevious; i++) { StepMeta stepMeta = findPrevStep(startStep, i, false); if (stepMeta.equals(stepToFind)) return true; boolean found = findPrevious(stepMeta, stepToFind); // Look further back in the tree. if (found) return true; } // Info steps nrPrevious = findNrPrevSteps(startStep, true); for (int i = 0; i < nrPrevious; i++) { StepMeta stepMeta = findPrevStep(startStep, i, true); if (stepMeta.equals(stepToFind)) return true; boolean found = findPrevious(stepMeta, stepToFind); // Look further back in the tree. if (found) return true; } return false; } /** * Put the steps in alfabetical order. */ public void sortSteps() { try { Collections.sort(steps); } catch (Exception e) { LogWriter.getInstance().logError(toString(), Messages.getString("TransMeta.Exception.ErrorOfSortingSteps") + e); //$NON-NLS-1$ LogWriter.getInstance().logError(toString(), Const.getStackTracker(e)); } } public void sortHops() { Collections.sort(hops); } /** * Put the steps in a more natural order: from start to finish. For the moment, we ignore splits and joins. Splits * and joins can't be listed sequentially in any case! * */ public void sortStepsNatural() { // Loop over the steps... for (int j = 0; j < nrSteps(); j++) { // Buble sort: we need to do this several times... for (int i = 0; i < nrSteps() - 1; i++) { StepMeta one = getStep(i); StepMeta two = getStep(i + 1); if (!findPrevious(two, one)) { setStep(i + 1, one); setStep(i, two); } } } } /** * Sort the hops in a natural way: from beginning to end */ public void sortHopsNatural() { // Loop over the hops... for (int j = 0; j < nrTransHops(); j++) { // Buble sort: we need to do this several times... for (int i = 0; i < nrTransHops() - 1; i++) { TransHopMeta one = getTransHop(i); TransHopMeta two = getTransHop(i + 1); StepMeta a = two.getFromStep(); StepMeta b = one.getToStep(); if (!findPrevious(a, b) && !a.equals(b)) { setTransHop(i + 1, one); setTransHop(i, two); } } } } /** * This procedure determines the impact of the different steps in a transformation on databases, tables and field. * * @param impact An ArrayList of DatabaseImpact objects. * */ public void analyseImpact(List<DatabaseImpact> impact, ProgressMonitorListener monitor) throws KettleStepException { if (monitor != null) { monitor.beginTask(Messages.getString("TransMeta.Monitor.DeterminingImpactTask.Title"), nrSteps()); //$NON-NLS-1$ } boolean stop = false; for (int i = 0; i < nrSteps() && !stop; i++) { if (monitor != null) monitor.subTask(Messages.getString("TransMeta.Monitor.LookingAtStepTask.Title") + (i + 1) + "/" + nrSteps()); //$NON-NLS-1$ //$NON-NLS-2$ StepMeta stepMeta = getStep(i); RowMetaInterface prev = getPrevStepFields(stepMeta); StepMetaInterface stepint = stepMeta.getStepMetaInterface(); RowMetaInterface inform = null; StepMeta[] lu = getInfoStep(stepMeta); if (lu != null) { inform = getStepFields(lu); } else { inform = stepint.getTableFields(); } stepint.analyseImpact(impact, this, stepMeta, prev, null, null, inform); if (monitor != null) { monitor.worked(1); stop = monitor.isCanceled(); } } if (monitor != null) monitor.done(); } /** * Proposes an alternative stepname when the original already exists... * * @param stepname The stepname to find an alternative for.. * @return The alternative stepname. */ public String getAlternativeStepname(String stepname) { String newname = stepname; StepMeta stepMeta = findStep(newname); int nr = 1; while (stepMeta != null) { nr++; newname = stepname + " " + nr; //$NON-NLS-1$ stepMeta = findStep(newname); } return newname; } /** * Builds a list of all the SQL statements that this transformation needs in order to work properly. * * @return An ArrayList of SQLStatement objects. */ public List<SQLStatement> getSQLStatements() throws KettleStepException { return getSQLStatements(null); } /** * Builds a list of all the SQL statements that this transformation needs in order to work properly. * * @return An ArrayList of SQLStatement objects. */ public List<SQLStatement> getSQLStatements(ProgressMonitorListener monitor) throws KettleStepException { if (monitor != null) monitor.beginTask(Messages.getString("TransMeta.Monitor.GettingTheSQLForTransformationTask.Title"), nrSteps() + 1); //$NON-NLS-1$ List<SQLStatement> stats = new ArrayList<SQLStatement>(); for (int i = 0; i < nrSteps(); i++) { StepMeta stepMeta = getStep(i); if (monitor != null) monitor.subTask(Messages.getString("TransMeta.Monitor.GettingTheSQLForStepTask.Title",""+stepMeta )); //$NON-NLS-1$ //$NON-NLS-2$ RowMetaInterface prev = getPrevStepFields(stepMeta); SQLStatement sql = stepMeta.getStepMetaInterface().getSQLStatements(this, stepMeta, prev); if (sql.getSQL() != null || sql.hasError()) { stats.add(sql); } if (monitor != null) monitor.worked(1); } // Also check the sql for the logtable... if (monitor != null) monitor.subTask(Messages.getString("TransMeta.Monitor.GettingTheSQLForTransformationTask.Title2")); //$NON-NLS-1$ if (logConnection != null && logTable != null && logTable.length() > 0) { Database db = new Database(logConnection); db.shareVariablesWith(this); try { db.connect(); RowMetaInterface fields = Database.getTransLogrecordFields(false, useBatchId, logfieldUsed); String sql = db.getDDL(logTable, fields); if (sql != null && sql.length() > 0) { SQLStatement stat = new SQLStatement("<this transformation>", logConnection, sql); //$NON-NLS-1$ stats.add(stat); } } catch (KettleDatabaseException dbe) { SQLStatement stat = new SQLStatement("<this transformation>", logConnection, null); //$NON-NLS-1$ stat.setError(Messages.getString("TransMeta.SQLStatement.ErrorDesc.ErrorObtainingTransformationLogTableInfo") + dbe.getMessage()); //$NON-NLS-1$ stats.add(stat); } finally { db.disconnect(); } } if (monitor != null) monitor.worked(1); if (monitor != null) monitor.done(); return stats; } /** * Get the SQL statements, needed to run this transformation, as one String. * * @return the SQL statements needed to run this transformation. */ public String getSQLStatementsString() throws KettleStepException { String sql = ""; //$NON-NLS-1$ List<SQLStatement> stats = getSQLStatements(); for (int i = 0; i < stats.size(); i++) { SQLStatement stat = stats.get(i); if (!stat.hasError() && stat.hasSQL()) { sql += stat.getSQL(); } } return sql; } /** * Checks all the steps and fills a List of (CheckResult) remarks. * * @param remarks The remarks list to add to. * @param only_selected Check only the selected steps. * @param monitor The progress monitor to use, null if not used */ public void checkSteps(List<CheckResultInterface> remarks, boolean only_selected, ProgressMonitorListener monitor) { try { remarks.clear(); // Start with a clean slate... Map<ValueMetaInterface,String> values = new Hashtable<ValueMetaInterface,String>(); String stepnames[]; StepMeta steps[]; if (!only_selected || nrSelectedSteps() == 0) { stepnames = getStepNames(); steps = getStepsArray(); } else { stepnames = getSelectedStepNames(); steps = getSelectedSteps(); } boolean stop_checking = false; if (monitor != null) monitor.beginTask(Messages.getString("TransMeta.Monitor.VerifyingThisTransformationTask.Title"), steps.length + 2); //$NON-NLS-1$ for (int i = 0; i < steps.length && !stop_checking; i++) { if (monitor != null) monitor.subTask(Messages.getString("TransMeta.Monitor.VerifyingStepTask.Title",stepnames[i])); //$NON-NLS-1$ //$NON-NLS-2$ StepMeta stepMeta = steps[i]; int nrinfo = findNrInfoSteps(stepMeta); StepMeta[] infostep = null; if (nrinfo > 0) { infostep = getInfoStep(stepMeta); } RowMetaInterface info = null; if (infostep != null) { try { info = getStepFields(infostep); } catch (KettleStepException kse) { info = null; CheckResult cr = new CheckResult(CheckResultInterface.TYPE_RESULT_ERROR, Messages.getString("TransMeta.CheckResult.TypeResultError.ErrorOccurredGettingStepInfoFields.Description",""+stepMeta , Const.CR + kse.getMessage()), stepMeta); //$NON-NLS-1$ remarks.add(cr); } } // The previous fields from non-informative steps: RowMetaInterface prev = null; try { prev = getPrevStepFields(stepMeta); } catch (KettleStepException kse) { CheckResult cr = new CheckResult(CheckResultInterface.TYPE_RESULT_ERROR, Messages.getString("TransMeta.CheckResult.TypeResultError.ErrorOccurredGettingInputFields.Description", ""+stepMeta , Const.CR + kse.getMessage()), stepMeta); //$NON-NLS-1$ remarks.add(cr); // This is a severe error: stop checking... // Otherwise we wind up checking time & time again because nothing gets put in the database // cache, the timeout of certain databases is very long... (Oracle) stop_checking = true; } if (isStepUsedInTransHops(stepMeta)) { // Get the input & output steps! // Copy to arrays: String input[] = getPrevStepNames(stepMeta); String output[] = getNextStepNames(stepMeta); // Check step specific info... stepMeta.check(remarks, this, prev, input, output, info); // See if illegal characters etc. were used in field-names... if (prev != null) { for (int x = 0; x < prev.size(); x++) { ValueMetaInterface v = prev.getValueMeta(x); String name = v.getName(); if (name == null) values.put(v, Messages.getString("TransMeta.Value.CheckingFieldName.FieldNameIsEmpty.Description")); //$NON-NLS-1$ else if (name.indexOf(' ') >= 0) values.put(v, Messages.getString("TransMeta.Value.CheckingFieldName.FieldNameContainsSpaces.Description")); //$NON-NLS-1$ else { char list[] = new char[] { '.', ',', '-', '/', '+', '*', '\'', '\t', '"', '|', '@', '(', ')', '{', '}', '!', '^' }; for (int c = 0; c < list.length; c++) { if (name.indexOf(list[c]) >= 0) values.put(v, Messages.getString("TransMeta.Value.CheckingFieldName.FieldNameContainsUnfriendlyCodes.Description",String.valueOf(list[c]) )); //$NON-NLS-1$ //$NON-NLS-2$ } } } // Check if 2 steps with the same name are entering the step... if (prev.size() > 1) { String fieldNames[] = prev.getFieldNames(); String sortedNames[] = Const.sortStrings(fieldNames); String prevName = sortedNames[0]; for (int x = 1; x < sortedNames.length; x++) { // Checking for doubles if (prevName.equalsIgnoreCase(sortedNames[x])) { // Give a warning!! CheckResult cr = new CheckResult(CheckResultInterface.TYPE_RESULT_ERROR, Messages.getString("TransMeta.CheckResult.TypeResultWarning.HaveTheSameNameField.Description", prevName ), stepMeta); //$NON-NLS-1$ //$NON-NLS-2$ remarks.add(cr); } else { prevName = sortedNames[x]; } } } } else { CheckResult cr = new CheckResult(CheckResultInterface.TYPE_RESULT_ERROR, Messages.getString("TransMeta.CheckResult.TypeResultError.CannotFindPreviousFields.Description") + stepMeta.getName(), //$NON-NLS-1$ stepMeta); remarks.add(cr); } } else { CheckResult cr = new CheckResult(CheckResultInterface.TYPE_RESULT_WARNING, Messages.getString("TransMeta.CheckResult.TypeResultWarning.StepIsNotUsed.Description"), stepMeta); //$NON-NLS-1$ remarks.add(cr); } // Also check for mixing rows... try { checkRowMixingStatically(stepMeta, null); } catch(KettleRowException e) { CheckResult cr = new CheckResult(CheckResultInterface.TYPE_RESULT_ERROR, e.getMessage(), stepMeta); remarks.add(cr); } if (monitor != null) { monitor.worked(1); // progress bar... if (monitor.isCanceled()) stop_checking = true; } } // Also, check the logging table of the transformation... if (monitor == null || !monitor.isCanceled()) { if (monitor != null) monitor.subTask(Messages.getString("TransMeta.Monitor.CheckingTheLoggingTableTask.Title")); //$NON-NLS-1$ if (getLogConnection() != null) { Database logdb = new Database(getLogConnection()); logdb.shareVariablesWith(this); try { logdb.connect(); CheckResult cr = new CheckResult(CheckResultInterface.TYPE_RESULT_OK, Messages.getString("TransMeta.CheckResult.TypeResultOK.ConnectingWorks.Description"), //$NON-NLS-1$ null); remarks.add(cr); if (getLogTable() != null) { if (logdb.checkTableExists(getLogTable())) { cr = new CheckResult(CheckResultInterface.TYPE_RESULT_OK, Messages.getString("TransMeta.CheckResult.TypeResultOK.LoggingTableExists.Description", getLogTable() ), null); //$NON-NLS-1$ //$NON-NLS-2$ remarks.add(cr); RowMetaInterface fields = Database.getTransLogrecordFields(false, isBatchIdUsed(), isLogfieldUsed()); String sql = logdb.getDDL(getLogTable(), fields); if (sql == null || sql.length() == 0) { cr = new CheckResult(CheckResultInterface.TYPE_RESULT_OK, Messages.getString("TransMeta.CheckResult.TypeResultOK.CorrectLayout.Description"), null); //$NON-NLS-1$ remarks.add(cr); } else { cr = new CheckResult(CheckResultInterface.TYPE_RESULT_ERROR, Messages.getString("TransMeta.CheckResult.TypeResultError.LoggingTableNeedsAdjustments.Description") + Const.CR + sql, //$NON-NLS-1$ null); remarks.add(cr); } } else { cr = new CheckResult(CheckResultInterface.TYPE_RESULT_ERROR, Messages.getString("TransMeta.CheckResult.TypeResultError.LoggingTableDoesNotExist.Description"), null); //$NON-NLS-1$ remarks.add(cr); } } else { cr = new CheckResult(CheckResultInterface.TYPE_RESULT_ERROR, Messages.getString("TransMeta.CheckResult.TypeResultError.LogTableNotSpecified.Description"), null); //$NON-NLS-1$ remarks.add(cr); } } catch (KettleDatabaseException dbe) { } finally { logdb.disconnect(); } } if (monitor != null) monitor.worked(1); } if (monitor != null) monitor.subTask(Messages.getString("TransMeta.Monitor.CheckingForDatabaseUnfriendlyCharactersInFieldNamesTask.Title")); //$NON-NLS-1$ if (values.size() > 0) { for(ValueMetaInterface v:values.keySet()) { String message = values.get(v); CheckResult cr = new CheckResult(CheckResultInterface.TYPE_RESULT_WARNING, Messages.getString("TransMeta.CheckResult.TypeResultWarning.Description",v.getName() , message ,v.getOrigin() ), findStep(v.getOrigin())); //$NON-NLS-1$ remarks.add(cr); } } else { CheckResult cr = new CheckResult(CheckResultInterface.TYPE_RESULT_OK, Messages.getString("TransMeta.CheckResult.TypeResultOK.Description"), null); //$NON-NLS-1$ remarks.add(cr); } if (monitor != null) monitor.worked(1); } catch (Exception e) { LogWriter.getInstance().logError(toString(), Const.getStackTracker(e)); throw new RuntimeException(e); } } /** * @return Returns the resultRows. */ public List<RowMetaAndData> getResultRows() { return resultRows; } /** * @param resultRows The resultRows to set. */ public void setResultRows(List<RowMetaAndData> resultRows) { this.resultRows = resultRows; } /** * @return Returns the directory. */ public RepositoryDirectory getDirectory() { return directory; } /** * @param directory The directory to set. */ public void setDirectory(RepositoryDirectory directory) { this.directory = directory; setInternalKettleVariables(); } /** * @return Returns the directoryTree. * @deprecated */ public RepositoryDirectory getDirectoryTree() { return directoryTree; } /** * @param directoryTree The directoryTree to set. * @deprecated */ public void setDirectoryTree(RepositoryDirectory directoryTree) { this.directoryTree = directoryTree; } /** * @return The directory path plus the name of the transformation */ public String getPathAndName() { if (getDirectory().isRoot()) return getDirectory().getPath() + getName(); else return getDirectory().getPath() + RepositoryDirectory.DIRECTORY_SEPARATOR + getName(); } /** * @return Returns the arguments. */ public String[] getArguments() { return arguments; } /** * @param arguments The arguments to set. */ public void setArguments(String[] arguments) { this.arguments = arguments; } /** * @return Returns the counters. */ public Hashtable<String,Counter> getCounters() { return counters; } /** * @param counters The counters to set. */ public void setCounters(Hashtable<String,Counter> counters) { this.counters = counters; } /** * @return Returns the dependencies. */ public List<TransDependency> getDependencies() { return dependencies; } /** * @param dependencies The dependencies to set. */ public void setDependencies(List<TransDependency> dependencies) { this.dependencies = dependencies; } /** * @return Returns the id. */ public long getId() { return id; } /** * @param id The id to set. */ public void setId(long id) { this.id = id; } /** * @return Returns the inputStep. */ public StepMeta getInputStep() { return inputStep; } /** * @param inputStep The inputStep to set. */ public void setInputStep(StepMeta inputStep) { this.inputStep = inputStep; } /** * @return Returns the logConnection. */ public DatabaseMeta getLogConnection() { return logConnection; } /** * @param logConnection The logConnection to set. */ public void setLogConnection(DatabaseMeta logConnection) { this.logConnection = logConnection; } /** * @return Returns the logTable. */ public String getLogTable() { return logTable; } /** * @param logTable The logTable to set. */ public void setLogTable(String logTable) { this.logTable = logTable; } /** * @return Returns the maxDateConnection. */ public DatabaseMeta getMaxDateConnection() { return maxDateConnection; } /** * @param maxDateConnection The maxDateConnection to set. */ public void setMaxDateConnection(DatabaseMeta maxDateConnection) { this.maxDateConnection = maxDateConnection; } /** * @return Returns the maxDateDifference. */ public double getMaxDateDifference() { return maxDateDifference; } /** * @param maxDateDifference The maxDateDifference to set. */ public void setMaxDateDifference(double maxDateDifference) { this.maxDateDifference = maxDateDifference; } /** * @return Returns the maxDateField. */ public String getMaxDateField() { return maxDateField; } /** * @param maxDateField The maxDateField to set. */ public void setMaxDateField(String maxDateField) { this.maxDateField = maxDateField; } /** * @return Returns the maxDateOffset. */ public double getMaxDateOffset() { return maxDateOffset; } /** * @param maxDateOffset The maxDateOffset to set. */ public void setMaxDateOffset(double maxDateOffset) { this.maxDateOffset = maxDateOffset; } /** * @return Returns the maxDateTable. */ public String getMaxDateTable() { return maxDateTable; } /** * @param maxDateTable The maxDateTable to set. */ public void setMaxDateTable(String maxDateTable) { this.maxDateTable = maxDateTable; } /** * @return Returns the outputStep. */ public StepMeta getOutputStep() { return outputStep; } /** * @param outputStep The outputStep to set. */ public void setOutputStep(StepMeta outputStep) { this.outputStep = outputStep; } /** * @return Returns the readStep. */ public StepMeta getReadStep() { return readStep; } /** * @param readStep The readStep to set. */ public void setReadStep(StepMeta readStep) { this.readStep = readStep; } /** * @return Returns the updateStep. */ public StepMeta getUpdateStep() { return updateStep; } /** * @param updateStep The updateStep to set. */ public void setUpdateStep(StepMeta updateStep) { this.updateStep = updateStep; } /** * @return Returns the writeStep. */ public StepMeta getWriteStep() { return writeStep; } /** * @param writeStep The writeStep to set. */ public void setWriteStep(StepMeta writeStep) { this.writeStep = writeStep; } /** * @return Returns the sizeRowset. */ public int getSizeRowset() { return sizeRowset; } /** * @param sizeRowset The sizeRowset to set. */ public void setSizeRowset(int sizeRowset) { this.sizeRowset = sizeRowset; } /** * @return Returns the dbCache. */ public DBCache getDbCache() { return dbCache; } /** * @param dbCache The dbCache to set. */ public void setDbCache(DBCache dbCache) { this.dbCache = dbCache; } /** * @return Returns the useBatchId. */ public boolean isBatchIdUsed() { return useBatchId; } /** * @param useBatchId The useBatchId to set. */ public void setBatchIdUsed(boolean useBatchId) { this.useBatchId = useBatchId; } /** * @return Returns the logfieldUsed. */ public boolean isLogfieldUsed() { return logfieldUsed; } /** * @param logfieldUsed The logfieldUsed to set. */ public void setLogfieldUsed(boolean logfieldUsed) { this.logfieldUsed = logfieldUsed; } /** * @return Returns the createdDate. */ public Date getCreatedDate() { return createdDate; } /** * @param createdDate The createdDate to set. */ public void setCreatedDate(Date createdDate) { this.createdDate = createdDate; } /** * @param createdUser The createdUser to set. */ public void setCreatedUser(String createdUser) { this.createdUser = createdUser; } /** * @return Returns the createdUser. */ public String getCreatedUser() { return createdUser; } /** * @param modifiedDate The modifiedDate to set. */ public void setModifiedDate(Date modifiedDate) { this.modifiedDate = modifiedDate; } /** * @return Returns the modifiedDate. */ public Date getModifiedDate() { return modifiedDate; } /** * @param modifiedUser The modifiedUser to set. */ public void setModifiedUser(String modifiedUser) { this.modifiedUser = modifiedUser; } /** * @return Returns the modifiedUser. */ public String getModifiedUser() { return modifiedUser; } /** * Get the description of the transformation * * @return The description of the transformation */ public String getDescription() { return description; } /** * Set the description of the transformation. * * @param n The new description of the transformation */ public void setDescription(String n) { description = n; } /** * Set the extended description of the transformation. * * @param n The new extended description of the transformation */ public void setExtendedDescription(String n) { extended_description = n; } /** * Get the extended description of the transformation * * @return The extended description of the transformation */ public String getExtendedDescription() { return extended_description; } /** * Get the version of the transformation * * @return The version of the transformation */ public String getTransversion() { return trans_version; } /** * Set the version of the transformation. * * @param n The new version description of the transformation */ public void setTransversion(String n) { trans_version = n; } /** * Set the status of the transformation. * * @param n The new status description of the transformation */ public void setTransstatus(int n) { trans_status = n; } /** * Get the status of the transformation * * @return The status of the transformation */ public int getTransstatus() { return trans_status; } /** * @return the textual representation of the transformation: it's name. If the name has not been set, the classname * is returned. */ public String toString() { if (name != null) return name; if (filename != null) return filename; return TransMeta.class.getName(); } /** * Cancel queries opened for checking & fieldprediction */ public void cancelQueries() throws KettleDatabaseException { for (int i = 0; i < nrSteps(); i++) { getStep(i).getStepMetaInterface().cancelQueries(); } } /** * Get the arguments used by this transformation. * * @param arguments * @return A row with the used arguments in it. */ public Map<String, String> getUsedArguments(String[] arguments) { Map<String, String> transArgs = new HashMap<String, String>(); for (int i = 0; i < nrSteps(); i++) { StepMetaInterface smi = getStep(i).getStepMetaInterface(); Map<String, String> stepArgs = smi.getUsedArguments(); // Get the command line arguments that this step uses. if (stepArgs != null) { transArgs.putAll(stepArgs); } } // OK, so perhaps, we can use the arguments from a previous execution? String[] saved = Props.isInitialized() ? Props.getInstance().getLastArguments() : null; // Set the default values on it... // Also change the name to "Argument 1" .. "Argument 10" // for (String argument : transArgs.keySet()) { String value = ""; int argNr = Const.toInt(argument, -1); if (arguments!=null && argNr > 0 && argNr <= arguments.length) { value = Const.NVL(arguments[argNr-1], ""); } if (value.length()==0) // try the saved option... { if (argNr > 0 && argNr < saved.length && saved[argNr] != null) { value = saved[argNr-1]; } } transArgs.put(argument, value); } return transArgs; } /** * @return Sleep time waiting when buffer is empty, in nano-seconds */ public int getSleepTimeEmpty() { return Const.TIMEOUT_GET_MILLIS; } /** * @return Sleep time waiting when buffer is full, in nano-seconds */ public int getSleepTimeFull() { return Const.TIMEOUT_PUT_MILLIS; } /** * @param sleepTimeEmpty The sleepTimeEmpty to set. */ public void setSleepTimeEmpty(int sleepTimeEmpty) { this.sleepTimeEmpty = sleepTimeEmpty; } /** * @param sleepTimeFull The sleepTimeFull to set. */ public void setSleepTimeFull(int sleepTimeFull) { this.sleepTimeFull = sleepTimeFull; } /** * This method asks all steps in the transformation whether or not the specified database connection is used. * The connection is used in the transformation if any of the steps uses it or if it is being used to log to. * @param databaseMeta The connection to check * @return true if the connection is used in this transformation. */ public boolean isDatabaseConnectionUsed(DatabaseMeta databaseMeta) { for (int i=0;i<nrSteps();i++) { StepMeta stepMeta = getStep(i); DatabaseMeta dbs[] = stepMeta.getStepMetaInterface().getUsedDatabaseConnections(); for (int d=0;d<dbs.length;d++) { if (dbs[d].equals(databaseMeta)) return true; } } if (logConnection!=null && logConnection.equals(databaseMeta)) return true; return false; } /* public List getInputFiles() { return inputFiles; } public void setInputFiles(List inputFiles) { this.inputFiles = inputFiles; } */ /** * Get a list of all the strings used in this transformation. * * @return A list of StringSearchResult with strings used in the */ public List<StringSearchResult> getStringList(boolean searchSteps, boolean searchDatabases, boolean searchNotes, boolean includePasswords) { List<StringSearchResult> stringList = new ArrayList<StringSearchResult>(); if (searchSteps) { // Loop over all steps in the transformation and see what the used vars are... for (int i=0;i<nrSteps();i++) { StepMeta stepMeta = getStep(i); stringList.add(new StringSearchResult(stepMeta.getName(), stepMeta, this, "Step name")); if (stepMeta.getDescription()!=null) stringList.add(new StringSearchResult(stepMeta.getDescription(), stepMeta, this, "Step description")); StepMetaInterface metaInterface = stepMeta.getStepMetaInterface(); StringSearcher.findMetaData(metaInterface, 1, stringList, stepMeta, this); } } // Loop over all steps in the transformation and see what the used vars are... if (searchDatabases) { for (int i=0;i<nrDatabases();i++) { DatabaseMeta meta = getDatabase(i); stringList.add(new StringSearchResult(meta.getName(), meta, this, "Database connection name")); if (meta.getHostname()!=null) stringList.add(new StringSearchResult(meta.getHostname(), meta, this, "Database hostname")); if (meta.getDatabaseName()!=null) stringList.add(new StringSearchResult(meta.getDatabaseName(), meta, this, "Database name")); if (meta.getUsername()!=null) stringList.add(new StringSearchResult(meta.getUsername(), meta, this, "Database Username")); if (meta.getDatabaseTypeDesc()!=null) stringList.add(new StringSearchResult(meta.getDatabaseTypeDesc(), meta, this, "Database type description")); if (meta.getDatabasePortNumberString()!=null) stringList.add(new StringSearchResult(meta.getDatabasePortNumberString(), meta, this, "Database port")); if (meta.getServername()!=null) stringList.add(new StringSearchResult(meta.getServername(), meta, this, "Database server")); if ( includePasswords ) { if (meta.getPassword()!=null) stringList.add(new StringSearchResult(meta.getPassword(), meta, this, "Database password")); } } } // Loop over all steps in the transformation and see what the used vars are... if (searchNotes) { for (int i=0;i<nrNotes();i++) { NotePadMeta meta = getNote(i); if (meta.getNote()!=null) stringList.add(new StringSearchResult(meta.getNote(), meta, this, "Notepad text")); } } return stringList; } public List<StringSearchResult> getStringList(boolean searchSteps, boolean searchDatabases, boolean searchNotes) { return getStringList(searchSteps, searchDatabases, searchNotes, false); } public List<String> getUsedVariables() { // Get the list of Strings. List<StringSearchResult> stringList = getStringList(true, true, false, true); List<String> varList = new ArrayList<String>(); // Look around in the strings, see what we find... for (int i=0;i<stringList.size();i++) { StringSearchResult result = stringList.get(i); StringUtil.getUsedVariables(result.getString(), varList, false); } return varList; } /** * @return Returns the previousResult. */ public Result getPreviousResult() { return previousResult; } /** * @param previousResult The previousResult to set. */ public void setPreviousResult(Result previousResult) { this.previousResult = previousResult; } /** * @return Returns the resultFiles. */ public List<ResultFile> getResultFiles() { return resultFiles; } /** * @param resultFiles The resultFiles to set. */ public void setResultFiles(List<ResultFile> resultFiles) { this.resultFiles = resultFiles; } /** * @return the partitionSchemas */ public List<PartitionSchema> getPartitionSchemas() { return partitionSchemas; } /** * @param partitionSchemas the partitionSchemas to set */ public void setPartitionSchemas(List<PartitionSchema> partitionSchemas) { this.partitionSchemas = partitionSchemas; } /** * Get the available partition schema names. * @return */ public String[] getPartitionSchemasNames() { String names[] = new String[partitionSchemas.size()]; for (int i=0;i<names.length;i++) { names[i] = partitionSchemas.get(i).getName(); } return names; } /** * @return the feedbackShown */ public boolean isFeedbackShown() { return feedbackShown; } /** * @param feedbackShown the feedbackShown to set */ public void setFeedbackShown(boolean feedbackShown) { this.feedbackShown = feedbackShown; } /** * @return the feedbackSize */ public int getFeedbackSize() { return feedbackSize; } /** * @param feedbackSize the feedbackSize to set */ public void setFeedbackSize(int feedbackSize) { this.feedbackSize = feedbackSize; } /** * @return the usingUniqueConnections */ public boolean isUsingUniqueConnections() { return usingUniqueConnections; } /** * @param usingUniqueConnections the usingUniqueConnections to set */ public void setUsingUniqueConnections(boolean usingUniqueConnections) { this.usingUniqueConnections = usingUniqueConnections; } public List<ClusterSchema> getClusterSchemas() { return clusterSchemas; } public void setClusterSchemas(List<ClusterSchema> clusterSchemas) { this.clusterSchemas = clusterSchemas; } /** * @return The slave server strings from this cluster schema */ public String[] getClusterSchemaNames() { String[] names = new String[clusterSchemas.size()]; for (int i=0;i<names.length;i++) { names[i] = clusterSchemas.get(i).getName(); } return names; } /** * Find a partition schema using its name. * @param name The name of the partition schema to look for. * @return the partition with the specified name of null if nothing was found */ public PartitionSchema findPartitionSchema(String name) { for (int i=0;i<partitionSchemas.size();i++) { PartitionSchema schema = partitionSchemas.get(i); if (schema.getName().equalsIgnoreCase(name)) return schema; } return null; } /** * Find a clustering schema using its name * @param name The name of the clustering schema to look for. * @return the cluster schema with the specified name of null if nothing was found */ public ClusterSchema findClusterSchema(String name) { for (int i=0;i<clusterSchemas.size();i++) { ClusterSchema schema = clusterSchemas.get(i); if (schema.getName().equalsIgnoreCase(name)) return schema; } return null; } /** * Add a new partition schema to the transformation if that didn't exist yet. * Otherwise, replace it. * * @param partitionSchema The partition schema to be added. */ public void addOrReplacePartitionSchema(PartitionSchema partitionSchema) { int index = partitionSchemas.indexOf(partitionSchema); if (index<0) { partitionSchemas.add(partitionSchema); } else { PartitionSchema previous = partitionSchemas.get(index); previous.replaceMeta(partitionSchema); } setChanged(); } /** * Add a new slave server to the transformation if that didn't exist yet. * Otherwise, replace it. * * @param slaveServer The slave server to be added. */ public void addOrReplaceSlaveServer(SlaveServer slaveServer) { int index = slaveServers.indexOf(slaveServer); if (index<0) { slaveServers.add(slaveServer); } else { SlaveServer previous = slaveServers.get(index); previous.replaceMeta(slaveServer); } setChanged(); } /** * Add a new cluster schema to the transformation if that didn't exist yet. * Otherwise, replace it. * * @param clusterSchema The cluster schema to be added. */ public void addOrReplaceClusterSchema(ClusterSchema clusterSchema) { int index = clusterSchemas.indexOf(clusterSchema); if (index<0) { clusterSchemas.add(clusterSchema); } else { ClusterSchema previous = clusterSchemas.get(index); previous.replaceMeta(clusterSchema); } setChanged(); } public String getSharedObjectsFile() { return sharedObjectsFile; } public void setSharedObjectsFile(String sharedObjectsFile) { this.sharedObjectsFile = sharedObjectsFile; } public boolean saveSharedObjects() { try { // First load all the shared objects... String soFile = environmentSubstitute(sharedObjectsFile); SharedObjects sharedObjects = new SharedObjects(soFile); // Now overwrite the objects in there List<SharedObjectInterface> shared = new ArrayList<SharedObjectInterface>(); shared.addAll(databases); shared.addAll(steps); shared.addAll(partitionSchemas); shared.addAll(slaveServers); shared.addAll(clusterSchemas); // The databases connections... for (SharedObjectInterface sharedObject : shared ) { if (sharedObject.isShared()) { sharedObjects.storeObject(sharedObject); } } // Save the objects sharedObjects.saveToFile(); return true; } catch(Exception e) { log.logError(toString(), "Unable to save shared ojects: "+e.toString()); return false; } } /** * @return the usingThreadPriorityManagment */ public boolean isUsingThreadPriorityManagment() { return usingThreadPriorityManagment; } /** * @param usingThreadPriorityManagment the usingThreadPriorityManagment to set */ public void setUsingThreadPriorityManagment(boolean usingThreadPriorityManagment) { this.usingThreadPriorityManagment = usingThreadPriorityManagment; } public SlaveServer findSlaveServer(String serverString) { return SlaveServer.findSlaveServer(slaveServers, serverString); } public String[] getSlaveServerNames() { return SlaveServer.getSlaveServerNames(slaveServers); } /** * @return the slaveServers */ public List<SlaveServer> getSlaveServers() { return slaveServers; } /** * @param slaveServers the slaveServers to set */ public void setSlaveServers(List<SlaveServer> slaveServers) { this.slaveServers = slaveServers; } /** * @return the rejectedStep */ public StepMeta getRejectedStep() { return rejectedStep; } /** * @param rejectedStep the rejectedStep to set */ public void setRejectedStep(StepMeta rejectedStep) { this.rejectedStep = rejectedStep; } /** * Check a step to see if there are no multiple steps to read from. * If so, check to see if the receiving rows are all the same in layout. * We only want to ONLY use the DBCache for this to prevent GUI stalls. * * @param stepMeta the step to check * @throws KettleRowException in case we detect a row mixing violation * */ public void checkRowMixingStatically(StepMeta stepMeta, ProgressMonitorListener monitor) throws KettleRowException { int nrPrevious = findNrPrevSteps(stepMeta); if (nrPrevious>1) { RowMetaInterface referenceRow = null; // See if all previous steps send out the same rows... for (int i=0;i<nrPrevious;i++) { StepMeta previousStep = findPrevStep(stepMeta, i); try { RowMetaInterface row = getStepFields(previousStep, monitor); // Throws KettleStepException if (referenceRow==null) { referenceRow = row; } else { if ( ! stepMeta.getStepMetaInterface().excludeFromRowLayoutVerification()) { BaseStep.safeModeChecking(referenceRow, row); } } } catch(KettleStepException e) { // We ignore this one because we are in the process of designing the transformation, anything intermediate can go wrong. } } } } public void setInternalKettleVariables() { setInternalKettleVariables(variables); } public void setInternalKettleVariables(VariableSpace var) { if (!Const.isEmpty(filename)) // we have a finename that's defined. { try { FileObject fileObject = KettleVFS.getFileObject(filename); FileName fileName = fileObject.getName(); // The filename of the transformation var.setVariable(Const.INTERNAL_VARIABLE_TRANSFORMATION_FILENAME_NAME, fileName.getBaseName()); // The directory of the transformation FileName fileDir = fileName.getParent(); var.setVariable(Const.INTERNAL_VARIABLE_TRANSFORMATION_FILENAME_DIRECTORY, fileDir.getURI()); } catch(IOException e) { var.setVariable(Const.INTERNAL_VARIABLE_TRANSFORMATION_FILENAME_DIRECTORY, ""); var.setVariable(Const.INTERNAL_VARIABLE_TRANSFORMATION_FILENAME_NAME, ""); } } else { var.setVariable(Const.INTERNAL_VARIABLE_TRANSFORMATION_FILENAME_DIRECTORY, ""); var.setVariable(Const.INTERNAL_VARIABLE_TRANSFORMATION_FILENAME_NAME, ""); } // The name of the transformation // var.setVariable(Const.INTERNAL_VARIABLE_TRANSFORMATION_NAME, Const.NVL(name, "")); // The name of the directory in the repository // var.setVariable(Const.INTERNAL_VARIABLE_TRANSFORMATION_REPOSITORY_DIRECTORY, directory!=null?directory.getPath():""); // Here we don't remove the job specific parameters, as they may come in handy. // if (var.getVariable(Const.INTERNAL_VARIABLE_JOB_FILENAME_DIRECTORY)==null) { var.setVariable(Const.INTERNAL_VARIABLE_JOB_FILENAME_DIRECTORY, "Parent Job File Directory"); //$NON-NLS-1$ } if (var.getVariable(Const.INTERNAL_VARIABLE_JOB_FILENAME_NAME)==null) { var.setVariable(Const.INTERNAL_VARIABLE_JOB_FILENAME_NAME, "Parent Job Filename"); //$NON-NLS-1$ } if (var.getVariable(Const.INTERNAL_VARIABLE_JOB_NAME)==null) { var.setVariable(Const.INTERNAL_VARIABLE_JOB_NAME, "Parent Job Name"); //$NON-NLS-1$ } if (var.getVariable(Const.INTERNAL_VARIABLE_JOB_REPOSITORY_DIRECTORY)==null) { var.setVariable(Const.INTERNAL_VARIABLE_JOB_REPOSITORY_DIRECTORY, "Parent Job Repository Directory"); //$NON-NLS-1$ } } public void copyVariablesFrom(VariableSpace space) { variables.copyVariablesFrom(space); } public String environmentSubstitute(String aString) { return variables.environmentSubstitute(aString); } public String[] environmentSubstitute(String aString[]) { return variables.environmentSubstitute(aString); } public VariableSpace getParentVariableSpace() { return variables.getParentVariableSpace(); } public void setParentVariableSpace(VariableSpace parent) { variables.setParentVariableSpace(parent); } public String getVariable(String variableName, String defaultValue) { return variables.getVariable(variableName, defaultValue); } public String getVariable(String variableName) { return variables.getVariable(variableName); } public boolean getBooleanValueOfVariable(String variableName, boolean defaultValue) { if (!Const.isEmpty(variableName)) { String value = environmentSubstitute(variableName); if (!Const.isEmpty(value)) { return ValueMeta.convertStringToBoolean(value); } } return defaultValue; } public void initializeVariablesFrom(VariableSpace parent) { variables.initializeVariablesFrom(parent); } public String[] listVariables() { return variables.listVariables(); } public void setVariable(String variableName, String variableValue) { variables.setVariable(variableName, variableValue); } public void shareVariablesWith(VariableSpace space) { variables = space; } public void injectVariables(Map<String,String> prop) { variables.injectVariables(prop); } public StepMeta findMappingInputStep(String stepname) throws KettleStepException { if (!Const.isEmpty(stepname)) { StepMeta stepMeta = findStep(stepname); // TODO verify that it's a mapping input!! if (stepMeta==null) { throw new KettleStepException(Messages.getString("TransMeta.Exception.StepNameNotFound", stepname)); } return stepMeta; } else { // Find the first mapping input step that fits the bill. StepMeta stepMeta = null; for (StepMeta mappingStep : steps) { if (mappingStep.getStepID().equals("MappingInput")) { if (stepMeta==null) { stepMeta = mappingStep; } else if (stepMeta!=null) { throw new KettleStepException(Messages.getString("TransMeta.Exception.OnlyOneMappingInputStepAllowed", "2")); } } } if (stepMeta==null) { throw new KettleStepException(Messages.getString("TransMeta.Exception.OneMappingInputStepRequired")); } return stepMeta; } } public StepMeta findMappingOutputStep(String stepname) throws KettleStepException { if (!Const.isEmpty(stepname)) { StepMeta stepMeta = findStep(stepname); // TODO verify that it's a mapping output step. if (stepMeta==null) { throw new KettleStepException(Messages.getString("TransMeta.Exception.StepNameNotFound", stepname)); } return stepMeta; } else { // Find the first mapping output step that fits the bill. StepMeta stepMeta = null; for (StepMeta mappingStep : steps) { if (mappingStep.getStepID().equals("MappingOutput")) { if (stepMeta==null) { stepMeta = mappingStep; } else if (stepMeta!=null) { throw new KettleStepException(Messages.getString("TransMeta.Exception.OnlyOneMappingOutputStepAllowed", "2")); } } } if (stepMeta==null) { throw new KettleStepException(Messages.getString("TransMeta.Exception.OneMappingOutputStepRequired")); } return stepMeta; } } public List<ResourceReference> getResourceDependencies() { List<ResourceReference> resourceReferences = new ArrayList<ResourceReference>(); for (StepMeta stepMeta : steps) { resourceReferences.addAll( stepMeta.getResourceDependencies(this) ); } return resourceReferences; } public String exportResources(VariableSpace space, Map<String, ResourceDefinition> definitions, ResourceNamingInterface resourceNamingInterface) throws KettleException { try { FileObject fileObject = KettleVFS.getFileObject(getFilename()); String exportFileName = resourceNamingInterface.nameResource(fileObject.getName().getBaseName(), fileObject.getParent().getName().getPath(), "ktr"); //$NON-NLS-1$ ResourceDefinition definition = definitions.get(exportFileName); if (definition==null) { // If we do this once, it will be plenty :-) // TransMeta transMeta = (TransMeta) this.realClone(false); // transMeta.copyVariablesFrom(space); // Add used resources, modify transMeta accordingly // Go through the list of steps, etc. // These critters change the steps in the cloned TransMeta // At the end we make a new XML version of it in "exported" format... // loop over steps, databases will be exported to XML anyway. // for (StepMeta stepMeta : transMeta.getSteps()) { stepMeta.exportResources(space, definitions, resourceNamingInterface); } // Change the filename, calling this sets internal variables inside of the transformation. // transMeta.setFilename(exportFileName); // At the end, add ourselves to the map... // String transMetaContent = transMeta.getXML(); definition = new ResourceDefinition(exportFileName, transMetaContent); definitions.put(fileObject.getName().getPath(), definition); } return exportFileName; } catch (FileSystemException e) { throw new KettleException(Messages.getString("TransMeta.Exception.ErrorOpeningOrValidatingTheXMLFile", getFilename()), e); //$NON-NLS-1$ } catch (IOException e) { throw new KettleException(Messages.getString("TransMeta.Exception.ErrorOpeningOrValidatingTheXMLFile", getFilename()), e); //$NON-NLS-1$ } } /** * @return the slaveStepCopyPartitionDistribution */ public SlaveStepCopyPartitionDistribution getSlaveStepCopyPartitionDistribution() { return slaveStepCopyPartitionDistribution; } /** * @param slaveStepCopyPartitionDistribution the slaveStepCopyPartitionDistribution to set */ public void setSlaveStepCopyPartitionDistribution(SlaveStepCopyPartitionDistribution slaveStepCopyPartitionDistribution) { this.slaveStepCopyPartitionDistribution = slaveStepCopyPartitionDistribution; } public boolean isUsingAtLeastOneClusterSchema() { for (StepMeta stepMeta : steps) { if (stepMeta.getClusterSchema()!=null) return true; } return false; } public boolean isSlaveTransformation() { return slaveTransformation; } public void setSlaveTransformation(boolean slaveTransformation) { this.slaveTransformation = slaveTransformation; } /** * @return the repository */ public Repository getRepository() { return repository; } /** * @param repository the repository to set */ public void setRepository(Repository repository) { this.repository = repository; } /** * @return the capturingStepPerformanceSnapShots */ public boolean isCapturingStepPerformanceSnapShots() { return capturingStepPerformanceSnapShots; } /** * @param capturingStepPerformanceSnapShots the capturingStepPerformanceSnapShots to set */ public void setCapturingStepPerformanceSnapShots(boolean capturingStepPerformanceSnapShots) { this.capturingStepPerformanceSnapShots = capturingStepPerformanceSnapShots; } /** * @return the stepPerformanceCapturingDelay */ public long getStepPerformanceCapturingDelay() { return stepPerformanceCapturingDelay; } /** * @param stepPerformanceCapturingDelay the stepPerformanceCapturingDelay to set */ public void setStepPerformanceCapturingDelay(long stepPerformanceCapturingDelay) { this.stepPerformanceCapturingDelay = stepPerformanceCapturingDelay; } /** * @return the sharedObjects */ public SharedObjects getSharedObjects() { return sharedObjects; } /** * @param sharedObjects the sharedObjects to set */ public void setSharedObjects(SharedObjects sharedObjects) { this.sharedObjects = sharedObjects; } private void clearStepFieldsCachce() { stepsFieldsCache.clear(); } }
src/org/pentaho/di/trans/TransMeta.java
/* Copyright (c) 2007 Pentaho Corporation. All rights reserved. * This software was developed by Pentaho Corporation and is provided under the terms * of the GNU Lesser General Public License, Version 2.1. You may not use * this file except in compliance with the license. If you need a copy of the license, * please go to http://www.gnu.org/licenses/lgpl-2.1.txt. The Original Code is Pentaho * Data Integration. The Initial Developer is Pentaho Corporation. * * Software distributed under the GNU Lesser Public License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. Please refer to * the license for the specific language governing your rights and limitations.*/ package org.pentaho.di.trans; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.Hashtable; import java.util.List; import java.util.Map; import org.apache.commons.vfs.FileName; import org.apache.commons.vfs.FileObject; import org.apache.commons.vfs.FileSystemException; import org.pentaho.di.cluster.ClusterSchema; import org.pentaho.di.cluster.SlaveServer; import org.pentaho.di.core.CheckResult; import org.pentaho.di.core.CheckResultInterface; import org.pentaho.di.core.Const; import org.pentaho.di.core.Counter; import org.pentaho.di.core.DBCache; import org.pentaho.di.core.EngineMetaInterface; import org.pentaho.di.core.LastUsedFile; import org.pentaho.di.core.NotePadMeta; import org.pentaho.di.core.ProgressMonitorListener; import org.pentaho.di.core.Props; import org.pentaho.di.core.Result; import org.pentaho.di.core.ResultFile; import org.pentaho.di.core.RowMetaAndData; import org.pentaho.di.core.SQLStatement; import org.pentaho.di.core.changed.ChangedFlag; import org.pentaho.di.core.database.Database; import org.pentaho.di.core.database.DatabaseMeta; import org.pentaho.di.core.exception.KettleDatabaseException; import org.pentaho.di.core.exception.KettleException; import org.pentaho.di.core.exception.KettleRowException; import org.pentaho.di.core.exception.KettleStepException; import org.pentaho.di.core.exception.KettleXMLException; import org.pentaho.di.core.gui.GUIPositionInterface; import org.pentaho.di.core.gui.Point; import org.pentaho.di.core.gui.SpoonFactory; import org.pentaho.di.core.gui.UndoInterface; import org.pentaho.di.core.logging.LogWriter; import org.pentaho.di.core.reflection.StringSearchResult; import org.pentaho.di.core.reflection.StringSearcher; import org.pentaho.di.core.row.RowMeta; import org.pentaho.di.core.row.RowMetaInterface; import org.pentaho.di.core.row.ValueMeta; import org.pentaho.di.core.row.ValueMetaInterface; import org.pentaho.di.core.undo.TransAction; import org.pentaho.di.core.util.StringUtil; import org.pentaho.di.core.variables.VariableSpace; import org.pentaho.di.core.variables.Variables; import org.pentaho.di.core.vfs.KettleVFS; import org.pentaho.di.core.xml.XMLHandler; import org.pentaho.di.core.xml.XMLInterface; import org.pentaho.di.partition.PartitionSchema; import org.pentaho.di.repository.Repository; import org.pentaho.di.repository.RepositoryDirectory; import org.pentaho.di.resource.ResourceDefinition; import org.pentaho.di.resource.ResourceExportInterface; import org.pentaho.di.resource.ResourceNamingInterface; import org.pentaho.di.resource.ResourceReference; import org.pentaho.di.shared.SharedObjectInterface; import org.pentaho.di.shared.SharedObjects; import org.pentaho.di.trans.step.BaseStep; import org.pentaho.di.trans.step.StepErrorMeta; import org.pentaho.di.trans.step.StepMeta; import org.pentaho.di.trans.step.StepMetaInterface; import org.pentaho.di.trans.step.StepPartitioningMeta; import org.pentaho.di.trans.steps.mapping.MappingMeta; import org.w3c.dom.Document; import org.w3c.dom.Node; /** * This class defines a transformation and offers methods to save and load it * from XML or a PDI database repository. * * @since 20-jun-2003 * @author Matt */ public class TransMeta extends ChangedFlag implements XMLInterface, Comparator<TransMeta>, Comparable<TransMeta>, Cloneable, UndoInterface, HasDatabasesInterface, VariableSpace, EngineMetaInterface, ResourceExportInterface, HasSlaveServersInterface { public static final String XML_TAG = "transformation"; private static LogWriter log = LogWriter.getInstance(); // private List inputFiles; private List<DatabaseMeta> databases; private List<StepMeta> steps; private List<TransHopMeta> hops; private List<NotePadMeta> notes; private List<TransDependency> dependencies; private List<SlaveServer> slaveServers; private List<ClusterSchema> clusterSchemas; private List<PartitionSchema> partitionSchemas; private RepositoryDirectory directory; private RepositoryDirectory directoryTree; private String name; private String description; private String extended_description; private String trans_version; private int trans_status; private String filename; private StepMeta readStep; private StepMeta writeStep; private StepMeta inputStep; private StepMeta outputStep; private StepMeta updateStep; private StepMeta rejectedStep; private String logTable; private DatabaseMeta logConnection; private int sizeRowset; private DatabaseMeta maxDateConnection; private String maxDateTable; private String maxDateField; private double maxDateOffset; private double maxDateDifference; private String arguments[]; private Hashtable<String,Counter> counters; private boolean changed_steps, changed_databases, changed_hops, changed_notes; private List<TransAction> undo; private int max_undo; private int undo_position; private DBCache dbCache; private long id; private boolean useBatchId; private boolean logfieldUsed; private String createdUser, modifiedUser; private Date createdDate, modifiedDate; private int sleepTimeEmpty; private int sleepTimeFull; private Result previousResult; private List<RowMetaAndData> resultRows; private List<ResultFile> resultFiles; private boolean usingUniqueConnections; private boolean feedbackShown; private int feedbackSize; /** flag to indicate thread management usage. Set to default to false from version 2.5.0 on. Before that it was enabled by default. */ private boolean usingThreadPriorityManagment; /** If this is null, we load from the default shared objects file : $KETTLE_HOME/.kettle/shared.xml */ private String sharedObjectsFile; /** The last load of the shared objects file by this TransMet object */ private SharedObjects sharedObjects; private VariableSpace variables = new Variables(); /** The slave-step-copy/partition distribution. Only used for slave transformations in a clustering environment. */ private SlaveStepCopyPartitionDistribution slaveStepCopyPartitionDistribution; /** Just a flag indicating that this is a slave transformation - internal use only, no GUI option */ private boolean slaveTransformation; /** The repository to reference in the one-off case that it is needed */ private Repository repository; private boolean capturingStepPerformanceSnapShots; private long stepPerformanceCapturingDelay; // ////////////////////////////////////////////////////////////////////////// public static final int TYPE_UNDO_CHANGE = 1; public static final int TYPE_UNDO_NEW = 2; public static final int TYPE_UNDO_DELETE = 3; public static final int TYPE_UNDO_POSITION = 4; public static final String desc_type_undo[] = { "", Messages.getString("TransMeta.UndoTypeDesc.UndoChange"), Messages.getString("TransMeta.UndoTypeDesc.UndoNew"), Messages.getString("TransMeta.UndoTypeDesc.UndoDelete"), Messages.getString("TransMeta.UndoTypeDesc.UndoPosition") }; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ private static final String XML_TAG_INFO = "info"; private static final String XML_TAG_ORDER = "order"; private static final String XML_TAG_NOTEPADS = "notepads"; private static final String XML_TAG_DEPENDENCIES = "dependencies"; private static final String XML_TAG_PARTITIONSCHEMAS = "partitionschemas"; private static final String XML_TAG_SLAVESERVERS = "slaveservers"; private static final String XML_TAG_CLUSTERSCHEMAS = "clusterschemas"; private static final String XML_TAG_STEP_ERROR_HANDLING = "step_error_handling"; /** * Builds a new empty transformation. */ public TransMeta() { clear(); initializeVariablesFrom(null); } /** * Builds a new empty transformation with a set of variables to inherit from. * @param parent the variable space to inherit from */ public TransMeta(VariableSpace parent) { clear(); initializeVariablesFrom(parent); } /** * Constructs a new transformation specifying the filename, name and arguments. * * @param filename The filename of the transformation * @param name The name of the transformation * @param arguments The arguments as Strings */ public TransMeta(String filename, String name, String arguments[]) { clear(); this.filename = filename; this.name = name; this.arguments = arguments; initializeVariablesFrom(null); } /** * Compares two transformation on name, filename */ public int compare(TransMeta t1, TransMeta t2) { if (Const.isEmpty(t1.getName()) && !Const.isEmpty(t2.getName())) return -1; if (!Const.isEmpty(t1.getName()) && Const.isEmpty(t2.getName())) return 1; if (Const.isEmpty(t1.getName()) && Const.isEmpty(t2.getName())) { if (Const.isEmpty(t1.getFilename()) && !Const.isEmpty(t2.getFilename())) return -1; if (!Const.isEmpty(t1.getFilename()) && Const.isEmpty(t2.getFilename())) return 1; if (Const.isEmpty(t1.getFilename()) && Const.isEmpty(t2.getFilename())) { return 0; } return t1.getFilename().compareTo(t2.getFilename()); } return t1.getName().compareTo(t2.getName()); } public int compareTo(TransMeta o) { return compare(this, o); } public boolean equals(Object obj) { if (!(obj instanceof TransMeta)) return false; return compare(this, (TransMeta)obj)==0; } @Override public Object clone() { return realClone(true); } public Object realClone(boolean doClear) { try { TransMeta transMeta = (TransMeta) super.clone(); if (doClear) { transMeta.clear(); } else { // Clear out the things we're replacing below transMeta.databases = new ArrayList<DatabaseMeta>(); transMeta.steps = new ArrayList<StepMeta>(); transMeta.hops = new ArrayList<TransHopMeta>(); transMeta.notes = new ArrayList<NotePadMeta>(); transMeta.dependencies = new ArrayList<TransDependency>(); transMeta.partitionSchemas = new ArrayList<PartitionSchema>(); transMeta.slaveServers = new ArrayList<SlaveServer>(); transMeta.clusterSchemas = new ArrayList<ClusterSchema>(); } for (DatabaseMeta db : databases) transMeta.addDatabase((DatabaseMeta)db.clone()); for (StepMeta step : steps) transMeta.addStep((StepMeta) step.clone()); for (TransHopMeta hop : hops) transMeta.addTransHop((TransHopMeta) hop.clone()); for (NotePadMeta note : notes) transMeta.addNote((NotePadMeta)note.clone()); for (TransDependency dep : dependencies) transMeta.addDependency((TransDependency)dep.clone()); for (SlaveServer slave : slaveServers) transMeta.getSlaveServers().add((SlaveServer)slave.clone()); for (ClusterSchema schema : clusterSchemas) transMeta.getClusterSchemas().add((ClusterSchema)schema.clone()); for (PartitionSchema schema : partitionSchemas) transMeta.getPartitionSchemas().add((PartitionSchema)schema.clone()); return transMeta; } catch (CloneNotSupportedException e) { e.printStackTrace(); return null; } } /** * Get the database ID in the repository for this object. * * @return the database ID in the repository for this object. */ public long getID() { return id; } /** * Set the database ID for this object in the repository. * * @param id the database ID for this object in the repository. */ public void setID(long id) { this.id = id; } /** * Clears the transformation. */ public void clear() { setID(-1L); databases = new ArrayList<DatabaseMeta>(); steps = new ArrayList<StepMeta>(); hops = new ArrayList<TransHopMeta>(); notes = new ArrayList<NotePadMeta>(); dependencies = new ArrayList<TransDependency>(); partitionSchemas = new ArrayList<PartitionSchema>(); slaveServers = new ArrayList<SlaveServer>(); clusterSchemas = new ArrayList<ClusterSchema>(); slaveStepCopyPartitionDistribution = new SlaveStepCopyPartitionDistribution(); name = null; description=null; trans_status=-1; trans_version=null; extended_description=null; filename = null; readStep = null; writeStep = null; inputStep = null; outputStep = null; updateStep = null; logTable = null; logConnection = null; sizeRowset = Const.ROWS_IN_ROWSET; sleepTimeEmpty = Const.TIMEOUT_GET_MILLIS; sleepTimeFull = Const.TIMEOUT_PUT_MILLIS; maxDateConnection = null; maxDateTable = null; maxDateField = null; maxDateOffset = 0.0; maxDateDifference = 0.0; undo = new ArrayList<TransAction>(); max_undo = Const.MAX_UNDO; undo_position = -1; counters = new Hashtable<String,Counter>(); resultRows = null; clearUndo(); clearChanged(); useBatchId = true; // Make this one the default from now on... logfieldUsed = false; // Don't use the log-field by default... createdUser = "-"; //$NON-NLS-1$ createdDate = new Date(); //$NON-NLS-1$ modifiedUser = "-"; //$NON-NLS-1$ modifiedDate = new Date(); //$NON-NLS-1$ // LOAD THE DATABASE CACHE! dbCache = DBCache.getInstance(); directoryTree = new RepositoryDirectory(); // Default directory: root directory = directoryTree; resultRows = new ArrayList<RowMetaAndData>(); resultFiles = new ArrayList<ResultFile>(); feedbackShown = true; feedbackSize = Const.ROWS_UPDATE; // Thread priority: // - set to false in version 2.5.0 // - re-enabling in version 3.0.1 to prevent excessive locking (PDI-491) // usingThreadPriorityManagment = true; // TODO FIXME Make these performance monitoring options configurable // capturingStepPerformanceSnapShots = true; stepPerformanceCapturingDelay = 1000; // every 1 seconds } public void clearUndo() { undo = new ArrayList<TransAction>(); undo_position = -1; } /* (non-Javadoc) * @see org.pentaho.di.trans.HasDatabaseInterface#getDatabases() */ public List<DatabaseMeta> getDatabases() { return databases; } /* (non-Javadoc) * @see org.pentaho.di.trans.HasDatabaseInterface#setDatabases(java.util.ArrayList) */ public void setDatabases(List<DatabaseMeta> databases) { this.databases = databases; } /* (non-Javadoc) * @see org.pentaho.di.trans.HasDatabaseInterface#addDatabase(org.pentaho.di.core.database.DatabaseMeta) */ public void addDatabase(DatabaseMeta databaseMeta) { databases.add(databaseMeta); } /* (non-Javadoc) * @see org.pentaho.di.trans.HasDatabaseInterface#addOrReplaceDatabase(org.pentaho.di.core.database.DatabaseMeta) */ public void addOrReplaceDatabase(DatabaseMeta databaseMeta) { int index = databases.indexOf(databaseMeta); if (index<0) { databases.add(databaseMeta); } else { DatabaseMeta previous = getDatabase(index); previous.replaceMeta(databaseMeta); } changed_databases = true; } /** * Add a new step to the transformation * * @param stepMeta The step to be added. */ public void addStep(StepMeta stepMeta) { steps.add(stepMeta); changed_steps = true; } /** * Add a new step to the transformation if that step didn't exist yet. * Otherwise, replace the step. * * @param stepMeta The step to be added. */ public void addOrReplaceStep(StepMeta stepMeta) { int index = steps.indexOf(stepMeta); if (index<0) { steps.add(stepMeta); } else { StepMeta previous = getStep(index); previous.replaceMeta(stepMeta); } changed_steps = true; } /** * Add a new hop to the transformation. * * @param hi The hop to be added. */ public void addTransHop(TransHopMeta hi) { hops.add(hi); changed_hops = true; } /** * Add a new note to the transformation. * * @param ni The note to be added. */ public void addNote(NotePadMeta ni) { notes.add(ni); changed_notes = true; } /** * Add a new dependency to the transformation. * * @param td The transformation dependency to be added. */ public void addDependency(TransDependency td) { dependencies.add(td); } /* (non-Javadoc) * @see org.pentaho.di.trans.HasDatabaseInterface#addDatabase(int, org.pentaho.di.core.database.DatabaseMeta) */ public void addDatabase(int p, DatabaseMeta ci) { databases.add(p, ci); } /** * Add a new step to the transformation * * @param p The location * @param stepMeta The step to be added. */ public void addStep(int p, StepMeta stepMeta) { steps.add(p, stepMeta); changed_steps = true; } /** * Add a new hop to the transformation on a certain location. * * @param p the location * @param hi The hop to be added. */ public void addTransHop(int p, TransHopMeta hi) { hops.add(p, hi); changed_hops = true; } /** * Add a new note to the transformation on a certain location. * * @param p The location * @param ni The note to be added. */ public void addNote(int p, NotePadMeta ni) { notes.add(p, ni); changed_notes = true; } /** * Add a new dependency to the transformation on a certain location * * @param p The location. * @param td The transformation dependency to be added. */ public void addDependency(int p, TransDependency td) { dependencies.add(p, td); } /* (non-Javadoc) * @see org.pentaho.di.trans.HasDatabaseInterface#getDatabase(int) */ public DatabaseMeta getDatabase(int i) { return databases.get(i); } /** * Get an ArrayList of defined steps. * * @return an ArrayList of defined steps. */ public List<StepMeta> getSteps() { return steps; } /** * Retrieves a step on a certain location. * * @param i The location. * @return The step information. */ public StepMeta getStep(int i) { return steps.get(i); } /** * Retrieves a hop on a certain location. * * @param i The location. * @return The hop information. */ public TransHopMeta getTransHop(int i) { return hops.get(i); } /** * Retrieves notepad information on a certain location. * * @param i The location * @return The notepad information. */ public NotePadMeta getNote(int i) { return notes.get(i); } /** * Retrieves a dependency on a certain location. * * @param i The location. * @return The dependency. */ public TransDependency getDependency(int i) { return dependencies.get(i); } /* (non-Javadoc) * @see org.pentaho.di.trans.HasDatabaseInterface#removeDatabase(int) */ public void removeDatabase(int i) { if (i < 0 || i >= databases.size()) return; databases.remove(i); changed_databases = true; } /** * Removes a step from the transformation on a certain location. * * @param i The location */ public void removeStep(int i) { if (i < 0 || i >= steps.size()) return; steps.remove(i); changed_steps = true; } /** * Removes a hop from the transformation on a certain location. * * @param i The location */ public void removeTransHop(int i) { if (i < 0 || i >= hops.size()) return; hops.remove(i); changed_hops = true; } /** * Removes a note from the transformation on a certain location. * * @param i The location */ public void removeNote(int i) { if (i < 0 || i >= notes.size()) return; notes.remove(i); changed_notes = true; } public void raiseNote(int p) { // if valid index and not last index if ((p >=0) && (p < notes.size()-1)) { NotePadMeta note = notes.remove(p); notes.add(note); changed_notes = true; } } public void lowerNote(int p) { // if valid index and not first index if ((p >0) && (p < notes.size())) { NotePadMeta note = notes.remove(p); notes.add(0, note); changed_notes = true; } } /** * Removes a dependency from the transformation on a certain location. * * @param i The location */ public void removeDependency(int i) { if (i < 0 || i >= dependencies.size()) return; dependencies.remove(i); } /** * Clears all the dependencies from the transformation. */ public void removeAllDependencies() { dependencies.clear(); } /* (non-Javadoc) * @see org.pentaho.di.trans.HasDatabaseInterface#nrDatabases() */ public int nrDatabases() { return databases.size(); } /** * Count the nr of steps in the transformation. * * @return The nr of steps */ public int nrSteps() { return steps.size(); } /** * Count the nr of hops in the transformation. * * @return The nr of hops */ public int nrTransHops() { return hops.size(); } /** * Count the nr of notes in the transformation. * * @return The nr of notes */ public int nrNotes() { return notes.size(); } /** * Count the nr of dependencies in the transformation. * * @return The nr of dependencies */ public int nrDependencies() { return dependencies.size(); } /** * Changes the content of a step on a certain position * * @param i The position * @param stepMeta The Step */ public void setStep(int i, StepMeta stepMeta) { steps.set(i, stepMeta); } /** * Changes the content of a hop on a certain position * * @param i The position * @param hi The hop */ public void setTransHop(int i, TransHopMeta hi) { hops.set(i, hi); } /** * Counts the number of steps that are actually used in the transformation. * * @return the number of used steps. */ public int nrUsedSteps() { int nr = 0; for (int i = 0; i < nrSteps(); i++) { StepMeta stepMeta = getStep(i); if (isStepUsedInTransHops(stepMeta)) nr++; } return nr; } /** * Gets a used step on a certain location * * @param lu The location * @return The used step. */ public StepMeta getUsedStep(int lu) { int nr = 0; for (int i = 0; i < nrSteps(); i++) { StepMeta stepMeta = getStep(i); if (isStepUsedInTransHops(stepMeta)) { if (lu == nr) return stepMeta; nr++; } } return null; } /* (non-Javadoc) * @see org.pentaho.di.trans.HasDatabaseInterface#findDatabase(java.lang.String) */ public DatabaseMeta findDatabase(String name) { int i; for (i = 0; i < nrDatabases(); i++) { DatabaseMeta ci = getDatabase(i); if (ci.getName().equalsIgnoreCase(name)) { return ci; } } return null; } /** * Searches the list of steps for a step with a certain name * * @param name The name of the step to look for * @return The step information or null if no nothing was found. */ public StepMeta findStep(String name) { return findStep(name, null); } /** * Searches the list of steps for a step with a certain name while excluding one step. * * @param name The name of the step to look for * @param exclude The step information to exclude. * @return The step information or null if nothing was found. */ public StepMeta findStep(String name, StepMeta exclude) { if (name==null) return null; int excl = -1; if (exclude != null) excl = indexOfStep(exclude); for (int i = 0; i < nrSteps(); i++) { StepMeta stepMeta = getStep(i); if (i != excl && stepMeta.getName().equalsIgnoreCase(name)) { return stepMeta; } } return null; } /** * Searches the list of hops for a hop with a certain name * * @param name The name of the hop to look for * @return The hop information or null if nothing was found. */ public TransHopMeta findTransHop(String name) { int i; for (i = 0; i < nrTransHops(); i++) { TransHopMeta hi = getTransHop(i); if (hi.toString().equalsIgnoreCase(name)) { return hi; } } return null; } /** * Search all hops for a hop where a certain step is at the start. * * @param fromstep The step at the start of the hop. * @return The hop or null if no hop was found. */ public TransHopMeta findTransHopFrom(StepMeta fromstep) { int i; for (i = 0; i < nrTransHops(); i++) { TransHopMeta hi = getTransHop(i); if (hi.getFromStep() != null && hi.getFromStep().equals(fromstep)) // return the first { return hi; } } return null; } /** * Find a certain hop in the transformation.. * * @param hi The hop information to look for. * @return The hop or null if no hop was found. */ public TransHopMeta findTransHop(TransHopMeta hi) { return findTransHop(hi.getFromStep(), hi.getToStep()); } /** * Search all hops for a hop where a certain step is at the start and another is at the end. * * @param from The step at the start of the hop. * @param to The step at the end of the hop. * @return The hop or null if no hop was found. */ public TransHopMeta findTransHop(StepMeta from, StepMeta to) { return findTransHop(from, to, false); } /** * Search all hops for a hop where a certain step is at the start and another is at the end. * * @param from The step at the start of the hop. * @param to The step at the end of the hop. * @return The hop or null if no hop was found. */ public TransHopMeta findTransHop(StepMeta from, StepMeta to, boolean disabledToo) { int i; for (i = 0; i < nrTransHops(); i++) { TransHopMeta hi = getTransHop(i); if (hi.isEnabled() || disabledToo) { if (hi.getFromStep() != null && hi.getToStep() != null && hi.getFromStep().equals(from) && hi.getToStep().equals(to)) { return hi; } } } return null; } /** * Search all hops for a hop where a certain step is at the end. * * @param tostep The step at the end of the hop. * @return The hop or null if no hop was found. */ public TransHopMeta findTransHopTo(StepMeta tostep) { int i; for (i = 0; i < nrTransHops(); i++) { TransHopMeta hi = getTransHop(i); if (hi.getToStep() != null && hi.getToStep().equals(tostep)) // Return the first! { return hi; } } return null; } /** * Determines whether or not a certain step is informative. This means that the previous step is sending information * to this step, but only informative. This means that this step is using the information to process the actual * stream of data. We use this in StreamLookup, TableInput and other types of steps. * * @param this_step The step that is receiving information. * @param prev_step The step that is sending information * @return true if prev_step if informative for this_step. */ public boolean isStepInformative(StepMeta this_step, StepMeta prev_step) { String[] infoSteps = this_step.getStepMetaInterface().getInfoSteps(); if (infoSteps == null) return false; for (int i = 0; i < infoSteps.length; i++) { if (prev_step.getName().equalsIgnoreCase(infoSteps[i])) return true; } return false; } /** * Counts the number of previous steps for a step name. * * @param stepname The name of the step to start from * @return The number of preceding steps. */ public int findNrPrevSteps(String stepname) { return findNrPrevSteps(findStep(stepname), false); } /** * Counts the number of previous steps for a step name taking into account whether or not they are informational. * * @param stepname The name of the step to start from * @return The number of preceding steps. */ public int findNrPrevSteps(String stepname, boolean info) { return findNrPrevSteps(findStep(stepname), info); } /** * Find the number of steps that precede the indicated step. * * @param stepMeta The source step * * @return The number of preceding steps found. */ public int findNrPrevSteps(StepMeta stepMeta) { return findNrPrevSteps(stepMeta, false); } /** * Find the previous step on a certain location. * * @param stepname The source step name * @param nr the location * * @return The preceding step found. */ public StepMeta findPrevStep(String stepname, int nr) { return findPrevStep(findStep(stepname), nr); } /** * Find the previous step on a certain location taking into account the steps being informational or not. * * @param stepname The name of the step * @param nr The location * @param info true if we only want the informational steps. * @return The step information */ public StepMeta findPrevStep(String stepname, int nr, boolean info) { return findPrevStep(findStep(stepname), nr, info); } /** * Find the previous step on a certain location. * * @param stepMeta The source step information * @param nr the location * * @return The preceding step found. */ public StepMeta findPrevStep(StepMeta stepMeta, int nr) { return findPrevStep(stepMeta, nr, false); } /** * Count the number of previous steps on a certain location taking into account the steps being informational or * not. * * @param stepMeta The name of the step * @param info true if we only want the informational steps. * @return The number of preceding steps */ public int findNrPrevSteps(StepMeta stepMeta, boolean info) { int count = 0; int i; for (i = 0; i < nrTransHops(); i++) // Look at all the hops; { TransHopMeta hi = getTransHop(i); if (hi.getToStep() != null && hi.isEnabled() && hi.getToStep().equals(stepMeta)) { // Check if this previous step isn't informative (StreamValueLookup) // We don't want fields from this stream to show up! if (info || !isStepInformative(stepMeta, hi.getFromStep())) { count++; } } } return count; } /** * Find the previous step on a certain location taking into account the steps being informational or not. * * @param stepMeta The step * @param nr The location * @param info true if we only want the informational steps. * @return The preceding step information */ public StepMeta findPrevStep(StepMeta stepMeta, int nr, boolean info) { int count = 0; int i; for (i = 0; i < nrTransHops(); i++) // Look at all the hops; { TransHopMeta hi = getTransHop(i); if (hi.getToStep() != null && hi.isEnabled() && hi.getToStep().equals(stepMeta)) { if (info || !isStepInformative(stepMeta, hi.getFromStep())) { if (count == nr) { return hi.getFromStep(); } count++; } } } return null; } /** * Get the informational steps for a certain step. An informational step is a step that provides information for * lookups etc. * * @param stepMeta The name of the step * @return The informational steps found */ public StepMeta[] getInfoStep(StepMeta stepMeta) { String[] infoStepName = stepMeta.getStepMetaInterface().getInfoSteps(); if (infoStepName == null) return null; StepMeta[] infoStep = new StepMeta[infoStepName.length]; for (int i = 0; i < infoStep.length; i++) { infoStep[i] = findStep(infoStepName[i]); } return infoStep; } /** * Find the the number of informational steps for a certains step. * * @param stepMeta The step * @return The number of informational steps found. */ public int findNrInfoSteps(StepMeta stepMeta) { if (stepMeta == null) return 0; int count = 0; for (int i = 0; i < nrTransHops(); i++) // Look at all the hops; { TransHopMeta hi = getTransHop(i); if (hi == null || hi.getToStep() == null) { log.logError(toString(), Messages.getString("TransMeta.Log.DestinationOfHopCannotBeNull")); //$NON-NLS-1$ } if (hi != null && hi.getToStep() != null && hi.isEnabled() && hi.getToStep().equals(stepMeta)) { // Check if this previous step isn't informative (StreamValueLookup) // We don't want fields from this stream to show up! if (isStepInformative(stepMeta, hi.getFromStep())) { count++; } } } return count; } /** * Find the informational fields coming from an informational step into the step specified. * * @param stepname The name of the step * @return A row containing fields with origin. */ public RowMetaInterface getPrevInfoFields(String stepname) throws KettleStepException { return getPrevInfoFields(findStep(stepname)); } /** * Find the informational fields coming from an informational step into the step specified. * * @param stepMeta The receiving step * @return A row containing fields with origin. */ public RowMetaInterface getPrevInfoFields(StepMeta stepMeta) throws KettleStepException { RowMetaInterface row = new RowMeta(); for (int i = 0; i < nrTransHops(); i++) // Look at all the hops; { TransHopMeta hi = getTransHop(i); if (hi.isEnabled() && hi.getToStep().equals(stepMeta)) { if (isStepInformative(stepMeta, hi.getFromStep())) { getThisStepFields(stepMeta, null, row); return row; } } } return row; } /** * Find the number of succeeding steps for a certain originating step. * * @param stepMeta The originating step * @return The number of succeeding steps. */ public int findNrNextSteps(StepMeta stepMeta) { int count = 0; int i; for (i = 0; i < nrTransHops(); i++) // Look at all the hops; { TransHopMeta hi = getTransHop(i); if (hi.isEnabled() && hi.getFromStep().equals(stepMeta)) count++; } return count; } /** * Find the succeeding step at a location for an originating step. * * @param stepMeta The originating step * @param nr The location * @return The step found. */ public StepMeta findNextStep(StepMeta stepMeta, int nr) { int count = 0; int i; for (i = 0; i < nrTransHops(); i++) // Look at all the hops; { TransHopMeta hi = getTransHop(i); if (hi.isEnabled() && hi.getFromStep().equals(stepMeta)) { if (count == nr) { return hi.getToStep(); } count++; } } return null; } /** * Retrieve an array of preceding steps for a certain destination step. * * @param stepMeta The destination step * @return An array containing the preceding steps. */ public StepMeta[] getPrevSteps(StepMeta stepMeta) { int nr = findNrPrevSteps(stepMeta, true); StepMeta retval[] = new StepMeta[nr]; for (int i = 0; i < nr; i++) { retval[i] = findPrevStep(stepMeta, i, true); } return retval; } /** * Retrieve an array of succeeding step names for a certain originating step name. * * @param stepname The originating step name * @return An array of succeeding step names */ public String[] getPrevStepNames(String stepname) { return getPrevStepNames(findStep(stepname)); } /** * Retrieve an array of preceding steps for a certain destination step. * * @param stepMeta The destination step * @return an array of preceding step names. */ public String[] getPrevStepNames(StepMeta stepMeta) { StepMeta prevStepMetas[] = getPrevSteps(stepMeta); String retval[] = new String[prevStepMetas.length]; for (int x = 0; x < prevStepMetas.length; x++) retval[x] = prevStepMetas[x].getName(); return retval; } /** * Retrieve an array of succeeding steps for a certain originating step. * * @param stepMeta The originating step * @return an array of succeeding steps. */ public StepMeta[] getNextSteps(StepMeta stepMeta) { int nr = findNrNextSteps(stepMeta); StepMeta retval[] = new StepMeta[nr]; for (int i = 0; i < nr; i++) { retval[i] = findNextStep(stepMeta, i); } return retval; } /** * Retrieve an array of succeeding step names for a certain originating step. * * @param stepMeta The originating step * @return an array of succeeding step names. */ public String[] getNextStepNames(StepMeta stepMeta) { StepMeta nextStepMeta[] = getNextSteps(stepMeta); String retval[] = new String[nextStepMeta.length]; for (int x = 0; x < nextStepMeta.length; x++) retval[x] = nextStepMeta[x].getName(); return retval; } /** * Find the step that is located on a certain point on the canvas, taking into account the icon size. * * @param x the x-coordinate of the point queried * @param y the y-coordinate of the point queried * @return The step information if a step is located at the point. Otherwise, if no step was found: null. */ public StepMeta getStep(int x, int y, int iconsize) { int i, s; s = steps.size(); for (i = s - 1; i >= 0; i--) // Back to front because drawing goes from start to end { StepMeta stepMeta = steps.get(i); if (partOfTransHop(stepMeta) || stepMeta.isDrawn()) // Only consider steps from active or inactive hops! { Point p = stepMeta.getLocation(); if (p != null) { if (x >= p.x && x <= p.x + iconsize && y >= p.y && y <= p.y + iconsize + 20) { return stepMeta; } } } } return null; } /** * Find the note that is located on a certain point on the canvas. * * @param x the x-coordinate of the point queried * @param y the y-coordinate of the point queried * @return The note information if a note is located at the point. Otherwise, if nothing was found: null. */ public NotePadMeta getNote(int x, int y) { int i, s; s = notes.size(); for (i = s - 1; i >= 0; i--) // Back to front because drawing goes from start to end { NotePadMeta ni = notes.get(i); Point loc = ni.getLocation(); Point p = new Point(loc.x, loc.y); if (x >= p.x && x <= p.x + ni.width + 2 * Const.NOTE_MARGIN && y >= p.y && y <= p.y + ni.height + 2 * Const.NOTE_MARGIN) { return ni; } } return null; } /** * Determines whether or not a certain step is part of a hop. * * @param stepMeta The step queried * @return true if the step is part of a hop. */ public boolean partOfTransHop(StepMeta stepMeta) { int i; for (i = 0; i < nrTransHops(); i++) { TransHopMeta hi = getTransHop(i); if (hi.getFromStep() == null || hi.getToStep() == null) return false; if (hi.getFromStep().equals(stepMeta) || hi.getToStep().equals(stepMeta)) return true; } return false; } /** * Returns the fields that are emitted by a certain step name * * @param stepname The stepname of the step to be queried. * @return A row containing the fields emitted. */ public RowMetaInterface getStepFields(String stepname) throws KettleStepException { StepMeta stepMeta = findStep(stepname); if (stepMeta != null) return getStepFields(stepMeta); else return null; } /** * Returns the fields that are emitted by a certain step * * @param stepMeta The step to be queried. * @return A row containing the fields emitted. */ public RowMetaInterface getStepFields(StepMeta stepMeta) throws KettleStepException { return getStepFields(stepMeta, null); } public RowMetaInterface getStepFields(StepMeta[] stepMeta) throws KettleStepException { RowMetaInterface fields = new RowMeta(); for (int i = 0; i < stepMeta.length; i++) { RowMetaInterface flds = getStepFields(stepMeta[i]); if (flds != null) fields.mergeRowMeta(flds); } return fields; } /** * Returns the fields that are emitted by a certain step * * @param stepMeta The step to be queried. * @param monitor The progress monitor for progress dialog. (null if not used!) * @return A row containing the fields emitted. */ public RowMetaInterface getStepFields(StepMeta stepMeta, ProgressMonitorListener monitor) throws KettleStepException { return getStepFields(stepMeta, null, monitor); } /** * Returns the fields that are emitted by a certain step * * @param stepMeta The step to be queried. * @param targetStep the target step * @param monitor The progress monitor for progress dialog. (null if not used!) * @return A row containing the fields emitted. */ public RowMetaInterface getStepFields(StepMeta stepMeta, StepMeta targetStep, ProgressMonitorListener monitor) throws KettleStepException { RowMetaInterface row = new RowMeta(); if (stepMeta == null) return row; // See if the step is sending ERROR rows to the specified target step. // if (targetStep!=null && stepMeta.isSendingErrorRowsToStep(targetStep)) { // The error rows are the same as the input rows for // the step but with the selected error fields added // row = getPrevStepFields(stepMeta); // Add to this the error fields... StepErrorMeta stepErrorMeta = stepMeta.getStepErrorMeta(); row.addRowMeta(stepErrorMeta.getErrorFields()); return row; } // Resume the regular program... log.logDebug(toString(), Messages.getString("TransMeta.Log.FromStepALookingAtPreviousStep", stepMeta.getName(), String.valueOf(findNrPrevSteps(stepMeta)) )); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ for (int i = 0; i < findNrPrevSteps(stepMeta); i++) { StepMeta prevStepMeta = findPrevStep(stepMeta, i); if (monitor != null) { monitor.subTask(Messages.getString("TransMeta.Monitor.CheckingStepTask.Title", prevStepMeta.getName() )); //$NON-NLS-1$ //$NON-NLS-2$ } RowMetaInterface add = getStepFields(prevStepMeta, stepMeta, monitor); if (add == null) add = new RowMeta(); log.logDebug(toString(), Messages.getString("TransMeta.Log.FoundFieldsToAdd") + add.toString()); //$NON-NLS-1$ if (i == 0) { row.addRowMeta(add); } else { // See if the add fields are not already in the row for (int x = 0; x < add.size(); x++) { ValueMetaInterface v = add.getValueMeta(x); ValueMetaInterface s = row.searchValueMeta(v.getName()); if (s == null) { row.addValueMeta(v); } } } } // Finally, see if we need to add/modify/delete fields with this step "name" return getThisStepFields(stepMeta, targetStep, row, monitor); } /** * Find the fields that are entering a step with a certain name. * * @param stepname The name of the step queried * @return A row containing the fields (w/ origin) entering the step */ public RowMetaInterface getPrevStepFields(String stepname) throws KettleStepException { return getPrevStepFields(findStep(stepname)); } /** * Find the fields that are entering a certain step. * * @param stepMeta The step queried * @return A row containing the fields (w/ origin) entering the step */ public RowMetaInterface getPrevStepFields(StepMeta stepMeta) throws KettleStepException { return getPrevStepFields(stepMeta, null); } /** * Find the fields that are entering a certain step. * * @param stepMeta The step queried * @param monitor The progress monitor for progress dialog. (null if not used!) * @return A row containing the fields (w/ origin) entering the step */ public RowMetaInterface getPrevStepFields(StepMeta stepMeta, ProgressMonitorListener monitor) throws KettleStepException { RowMetaInterface row = new RowMeta(); if (stepMeta == null) { return null; } log.logDebug(toString(), Messages.getString("TransMeta.Log.FromStepALookingAtPreviousStep", stepMeta.getName(), String.valueOf(findNrPrevSteps(stepMeta)) )); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ for (int i = 0; i < findNrPrevSteps(stepMeta); i++) { StepMeta prevStepMeta = findPrevStep(stepMeta, i); if (monitor != null) { monitor.subTask(Messages.getString("TransMeta.Monitor.CheckingStepTask.Title", prevStepMeta.getName() )); //$NON-NLS-1$ //$NON-NLS-2$ } RowMetaInterface add = getStepFields(prevStepMeta, stepMeta, monitor); log.logDebug(toString(), Messages.getString("TransMeta.Log.FoundFieldsToAdd2") + add.toString()); //$NON-NLS-1$ if (i == 0) // we expect all input streams to be of the same layout! { row.addRowMeta(add); // recursive! } else { // See if the add fields are not already in the row for (int x = 0; x < add.size(); x++) { ValueMetaInterface v = add.getValueMeta(x); ValueMetaInterface s = row.searchValueMeta(v.getName()); if (s == null) { row.addValueMeta(v); } } } } return row; } /** * Return the fields that are emitted by a step with a certain name * * @param stepname The name of the step that's being queried. * @param row A row containing the input fields or an empty row if no input is required. * @return A Row containing the output fields. */ public RowMetaInterface getThisStepFields(String stepname, RowMetaInterface row) throws KettleStepException { return getThisStepFields(findStep(stepname), null, row); } /** * Returns the fields that are emitted by a step * * @param stepMeta : The StepMeta object that's being queried * @param nextStep : if non-null this is the next step that's call back to ask what's being sent * @param row : A row containing the input fields or an empty row if no input is required. * * @return A Row containing the output fields. */ public RowMetaInterface getThisStepFields(StepMeta stepMeta, StepMeta nextStep, RowMetaInterface row) throws KettleStepException { return getThisStepFields(stepMeta, nextStep, row, null); } /** * Returns the fields that are emitted by a step * * @param stepMeta : The StepMeta object that's being queried * @param nextStep : if non-null this is the next step that's call back to ask what's being sent * @param row : A row containing the input fields or an empty row if no input is required. * * @return A Row containing the output fields. */ public RowMetaInterface getThisStepFields(StepMeta stepMeta, StepMeta nextStep, RowMetaInterface row, ProgressMonitorListener monitor) throws KettleStepException { // Then this one. log.logDebug(toString(), Messages.getString("TransMeta.Log.GettingFieldsFromStep",stepMeta.getName(), stepMeta.getStepID())); //$NON-NLS-1$ //$NON-NLS-2$ String name = stepMeta.getName(); if (monitor != null) { monitor.subTask(Messages.getString("TransMeta.Monitor.GettingFieldsFromStepTask.Title", name )); //$NON-NLS-1$ //$NON-NLS-2$ } StepMetaInterface stepint = stepMeta.getStepMetaInterface(); RowMetaInterface inform[] = null; StepMeta[] lu = getInfoStep(stepMeta); if (Const.isEmpty(lu)) { inform = new RowMetaInterface[] { stepint.getTableFields(), }; } else { inform = new RowMetaInterface[lu.length]; for (int i=0;i<lu.length;i++) inform[i] = getStepFields(lu[i]); } // Set the Repository object on the Mapping step // That way the mapping step can determine the output fields for repository hosted mappings... // This is the exception to the rule so we don't pass this through the getFields() method. // for (StepMeta step : steps) { if (step.getStepMetaInterface() instanceof MappingMeta) { ((MappingMeta)step.getStepMetaInterface()).setRepository(repository); } } // Go get the fields... // stepint.getFields(row, name, inform, nextStep, this); return row; } /** * Determine if we should put a replace warning or not for the transformation in a certain repository. * * @param rep The repository. * @return True if we should show a replace warning, false if not. */ public boolean showReplaceWarning(Repository rep) { if (getID() < 0) { try { if (rep.getTransformationID(getName(), directory.getID()) > 0) return true; } catch (KettleException dbe) { log.logError(toString(), Messages.getString("TransMeta.Log.DatabaseError") + dbe.getMessage()); //$NON-NLS-1$ return true; } } return false; } public void saveRep(Repository rep) throws KettleException { saveRep(rep, null); } /** * Saves the transformation to a repository. * * @param rep The repository. * @throws KettleException if an error occurrs. */ public void saveRep(Repository rep, ProgressMonitorListener monitor) throws KettleException { try { if (monitor!=null) monitor.subTask(Messages.getString("TransMeta.Monitor.LockingRepository")); //$NON-NLS-1$ rep.lockRepository(); // make sure we're they only one using the repository at the moment rep.insertLogEntry("save transformation '"+getName()+"'"); // Clear attribute id cache rep.clearNextIDCounters(); // force repository lookup. // Do we have a valid directory? if (directory.getID() < 0) { throw new KettleException(Messages.getString("TransMeta.Exception.PlsSelectAValidDirectoryBeforeSavingTheTransformation")); } //$NON-NLS-1$ int nrWorks = 2 + nrDatabases() + nrNotes() + nrSteps() + nrTransHops(); if (monitor != null) monitor.beginTask(Messages.getString("TransMeta.Monitor.SavingTransformationTask.Title") + getPathAndName(), nrWorks); //$NON-NLS-1$ log.logDebug(toString(), Messages.getString("TransMeta.Log.SavingOfTransformationStarted")); //$NON-NLS-1$ if (monitor!=null && monitor.isCanceled()) throw new KettleDatabaseException(); // Before we start, make sure we have a valid transformation ID! // Two possibilities: // 1) We have a ID: keep it // 2) We don't have an ID: look it up. // If we find a transformation with the same name: ask! // if (monitor != null) monitor.subTask(Messages.getString("TransMeta.Monitor.HandlingOldVersionTransformationTask.Title")); //$NON-NLS-1$ setID(rep.getTransformationID(getName(), directory.getID())); // If no valid id is available in the database, assign one... if (getID() <= 0) { setID(rep.getNextTransformationID()); } else { // If we have a valid ID, we need to make sure everything is cleared out // of the database for this id_transformation, before we put it back in... if (monitor != null) monitor.subTask(Messages.getString("TransMeta.Monitor.DeletingOldVersionTransformationTask.Title")); //$NON-NLS-1$ log.logDebug(toString(), Messages.getString("TransMeta.Log.DeletingOldVersionTransformation")); //$NON-NLS-1$ rep.delAllFromTrans(getID()); log.logDebug(toString(), Messages.getString("TransMeta.Log.OldVersionOfTransformationRemoved")); //$NON-NLS-1$ } if (monitor != null) monitor.worked(1); log.logDebug(toString(), Messages.getString("TransMeta.Log.SavingNotes")); //$NON-NLS-1$ for (int i = 0; i < nrNotes(); i++) { if (monitor!=null && monitor.isCanceled()) throw new KettleDatabaseException(Messages.getString("TransMeta.Log.UserCancelledTransSave")); if (monitor != null) monitor.subTask(Messages.getString("TransMeta.Monitor.SavingNoteTask.Title") + (i + 1) + "/" + nrNotes()); //$NON-NLS-1$ //$NON-NLS-2$ NotePadMeta ni = getNote(i); ni.saveRep(rep, getID()); if (ni.getID() > 0) rep.insertTransNote(getID(), ni.getID()); if (monitor != null) monitor.worked(1); } log.logDebug(toString(), Messages.getString("TransMeta.Log.SavingDatabaseConnections")); //$NON-NLS-1$ for (int i = 0; i < nrDatabases(); i++) { if (monitor!=null && monitor.isCanceled()) throw new KettleDatabaseException(Messages.getString("TransMeta.Log.UserCancelledTransSave")); if (monitor != null) monitor.subTask(Messages.getString("TransMeta.Monitor.SavingDatabaseTask.Title") + (i + 1) + "/" + nrDatabases()); //$NON-NLS-1$ //$NON-NLS-2$ DatabaseMeta databaseMeta = getDatabase(i); // ONLY save the database connection if it has changed and nothing was saved in the repository if(databaseMeta.hasChanged() || databaseMeta.getID()<=0) { databaseMeta.saveRep(rep); } if (monitor != null) monitor.worked(1); } // Before saving the steps, make sure we have all the step-types. // It is possible that we received another step through a plugin. log.logDebug(toString(), Messages.getString("TransMeta.Log.CheckingStepTypes")); //$NON-NLS-1$ rep.updateStepTypes(); log.logDebug(toString(), Messages.getString("TransMeta.Log.SavingSteps")); //$NON-NLS-1$ for (int i = 0; i < nrSteps(); i++) { if (monitor!=null && monitor.isCanceled()) throw new KettleDatabaseException(Messages.getString("TransMeta.Log.UserCancelledTransSave")); if (monitor != null) monitor.subTask(Messages.getString("TransMeta.Monitor.SavingStepTask.Title") + (i + 1) + "/" + nrSteps()); //$NON-NLS-1$ //$NON-NLS-2$ StepMeta stepMeta = getStep(i); stepMeta.saveRep(rep, getID()); if (monitor != null) monitor.worked(1); } rep.closeStepAttributeInsertPreparedStatement(); log.logDebug(toString(), Messages.getString("TransMeta.Log.SavingHops")); //$NON-NLS-1$ for (int i = 0; i < nrTransHops(); i++) { if (monitor!=null && monitor.isCanceled()) throw new KettleDatabaseException(Messages.getString("TransMeta.Log.UserCancelledTransSave")); if (monitor != null) monitor.subTask(Messages.getString("TransMeta.Monitor.SavingHopTask.Title") + (i + 1) + "/" + nrTransHops()); //$NON-NLS-1$ //$NON-NLS-2$ TransHopMeta hi = getTransHop(i); hi.saveRep(rep, getID()); if (monitor != null) monitor.worked(1); } if (monitor != null) monitor.subTask(Messages.getString("TransMeta.Monitor.FinishingTask.Title")); //$NON-NLS-1$ log.logDebug(toString(), Messages.getString("TransMeta.Log.SavingTransformationInfo")); //$NON-NLS-1$ rep.insertTransformation(this); // save the top level information for the transformation rep.closeTransAttributeInsertPreparedStatement(); // Save the partition schemas // for (int i=0;i<partitionSchemas.size();i++) { if (monitor!=null && monitor.isCanceled()) throw new KettleDatabaseException(Messages.getString("TransMeta.Log.UserCancelledTransSave")); PartitionSchema partitionSchema = partitionSchemas.get(i); // See if this transformation really is a consumer of this object // It might be simply loaded as a shared object from the repository // boolean isUsedByTransformation = isUsingPartitionSchema(partitionSchema); partitionSchema.saveRep(rep, getID(), isUsedByTransformation); } // Save the slaves // for (int i=0;i<slaveServers.size();i++) { if (monitor!=null && monitor.isCanceled()) throw new KettleDatabaseException(Messages.getString("TransMeta.Log.UserCancelledTransSave")); SlaveServer slaveServer = slaveServers.get(i); boolean isUsedByTransformation = isUsingSlaveServer(slaveServer); slaveServer.saveRep(rep, getID(), isUsedByTransformation); } // Save the clustering schemas for (int i=0;i<clusterSchemas.size();i++) { if (monitor!=null && monitor.isCanceled()) throw new KettleDatabaseException(Messages.getString("TransMeta.Log.UserCancelledTransSave")); ClusterSchema clusterSchema = clusterSchemas.get(i); boolean isUsedByTransformation = isUsingClusterSchema(clusterSchema); clusterSchema.saveRep(rep, getID(), isUsedByTransformation); } log.logDebug(toString(), Messages.getString("TransMeta.Log.SavingDependencies")); //$NON-NLS-1$ for (int i = 0; i < nrDependencies(); i++) { if (monitor!=null && monitor.isCanceled()) throw new KettleDatabaseException(Messages.getString("TransMeta.Log.UserCancelledTransSave")); TransDependency td = getDependency(i); td.saveRep(rep, getID()); } // Save the step error handling information as well! for (int i=0;i<nrSteps();i++) { StepMeta stepMeta = getStep(i); StepErrorMeta stepErrorMeta = stepMeta.getStepErrorMeta(); if (stepErrorMeta!=null) { stepErrorMeta.saveRep(rep, getId(), stepMeta.getID()); } } rep.closeStepAttributeInsertPreparedStatement(); log.logDebug(toString(), Messages.getString("TransMeta.Log.SavingFinished")); //$NON-NLS-1$ if (monitor!=null) monitor.subTask(Messages.getString("TransMeta.Monitor.UnlockingRepository")); //$NON-NLS-1$ rep.unlockRepository(); // Perform a commit! rep.commit(); clearChanged(); if (monitor != null) monitor.worked(1); if (monitor != null) monitor.done(); } catch (KettleDatabaseException dbe) { // Oops, roll back! rep.rollback(); log.logError(toString(), Messages.getString("TransMeta.Log.ErrorSavingTransformationToRepository") + Const.CR + dbe.getMessage()); //$NON-NLS-1$ throw new KettleException(Messages.getString("TransMeta.Log.ErrorSavingTransformationToRepository"), dbe); //$NON-NLS-1$ } finally { // don't forget to unlock the repository. // Normally this is done by the commit / rollback statement, but hey there are some freaky database out // there... rep.unlockRepository(); } } public boolean isUsingPartitionSchema(PartitionSchema partitionSchema) { // Loop over all steps and see if the partition schema is used. for (int i=0;i<nrSteps();i++) { StepPartitioningMeta stepPartitioningMeta = getStep(i).getStepPartitioningMeta(); if (stepPartitioningMeta!=null) { PartitionSchema check = stepPartitioningMeta.getPartitionSchema(); if (check!=null && check.equals(partitionSchema)) { return true; } } } return false; } public boolean isUsingClusterSchema(ClusterSchema clusterSchema) { // Loop over all steps and see if the partition schema is used. for (int i=0;i<nrSteps();i++) { ClusterSchema check = getStep(i).getClusterSchema(); if (check!=null && check.equals(clusterSchema)) { return true; } } return false; } public boolean isUsingSlaveServer(SlaveServer slaveServer) { // Loop over all steps and see if the slave server is used. for (int i=0;i<nrSteps();i++) { ClusterSchema clusterSchema = getStep(i).getClusterSchema(); if (clusterSchema!=null) { for (SlaveServer check : clusterSchema.getSlaveServers()) { if (check.equals(slaveServer)) { return true; } } return true; } } return false; } /* (non-Javadoc) * @see org.pentaho.di.trans.HasDatabaseInterface#readDatabases(org.pentaho.di.repository.Repository, boolean) */ public void readDatabases(Repository rep, boolean overWriteShared) throws KettleException { try { long dbids[] = rep.getDatabaseIDs(); for (int i = 0; i < dbids.length; i++) { DatabaseMeta databaseMeta = new DatabaseMeta(rep, dbids[i]); databaseMeta.shareVariablesWith(this); DatabaseMeta check = findDatabase(databaseMeta.getName()); // Check if there already is one in the transformation if (check==null || overWriteShared) // We only add, never overwrite database connections. { if (databaseMeta.getName() != null) { addOrReplaceDatabase(databaseMeta); if (!overWriteShared) databaseMeta.setChanged(false); } } } changed_databases = false; } catch (KettleDatabaseException dbe) { throw new KettleException(Messages.getString("TransMeta.Log.UnableToReadDatabaseIDSFromRepository"), dbe); //$NON-NLS-1$ } catch (KettleException ke) { throw new KettleException(Messages.getString("TransMeta.Log.UnableToReadDatabasesFromRepository"), ke); //$NON-NLS-1$ } } /** * Read the partitions in the repository and add them to this transformation if they are not yet present. * @param rep The repository to load from. * @param overWriteShared if an object with the same name exists, overwrite * @throws KettleException */ public void readPartitionSchemas(Repository rep, boolean overWriteShared) throws KettleException { try { long dbids[] = rep.getPartitionSchemaIDs(); for (int i = 0; i < dbids.length; i++) { PartitionSchema partitionSchema = new PartitionSchema(rep, dbids[i]); PartitionSchema check = findPartitionSchema(partitionSchema.getName()); // Check if there already is one in the transformation if (check==null || overWriteShared) { if (!Const.isEmpty(partitionSchema.getName())) { addOrReplacePartitionSchema(partitionSchema); if (!overWriteShared) partitionSchema.setChanged(false); } } } } catch (KettleException dbe) { throw new KettleException(Messages.getString("TransMeta.Log.UnableToReadPartitionSchemaFromRepository"), dbe); //$NON-NLS-1$ } } /** * Read the slave servers in the repository and add them to this transformation if they are not yet present. * @param rep The repository to load from. * @param overWriteShared if an object with the same name exists, overwrite * @throws KettleException */ public void readSlaves(Repository rep, boolean overWriteShared) throws KettleException { try { long dbids[] = rep.getSlaveIDs(); for (int i = 0; i < dbids.length; i++) { SlaveServer slaveServer = new SlaveServer(rep, dbids[i]); SlaveServer check = findSlaveServer(slaveServer.getName()); // Check if there already is one in the transformation if (check==null || overWriteShared) { if (!Const.isEmpty(slaveServer.getName())) { addOrReplaceSlaveServer(slaveServer); if (!overWriteShared) slaveServer.setChanged(false); } } } } catch (KettleDatabaseException dbe) { throw new KettleException(Messages.getString("TransMeta.Log.UnableToReadSlaveServersFromRepository"), dbe); //$NON-NLS-1$ } } /** * Read the clusters in the repository and add them to this transformation if they are not yet present. * @param rep The repository to load from. * @param overWriteShared if an object with the same name exists, overwrite * @throws KettleException */ public void readClusters(Repository rep, boolean overWriteShared) throws KettleException { try { long dbids[] = rep.getClusterIDs(); for (int i = 0; i < dbids.length; i++) { ClusterSchema cluster = new ClusterSchema(rep, dbids[i], slaveServers); ClusterSchema check = findClusterSchema(cluster.getName()); // Check if there already is one in the transformation if (check==null || overWriteShared) { if (!Const.isEmpty(cluster.getName())) { addOrReplaceClusterSchema(cluster); if (!overWriteShared) cluster.setChanged(false); } } } } catch (KettleDatabaseException dbe) { throw new KettleException(Messages.getString("TransMeta.Log.UnableToReadClustersFromRepository"), dbe); //$NON-NLS-1$ } } /** * Load the transformation name & other details from a repository. * * @param rep The repository to load the details from. */ public void loadRepTrans(Repository rep) throws KettleException { try { RowMetaAndData r = rep.getTransformation(getID()); if (r != null) { name = r.getString("NAME", null); //$NON-NLS-1$ // Trans description description = r.getString("DESCRIPTION", null); extended_description = r.getString("EXTENDED_DESCRIPTION", null); trans_version = r.getString("TRANS_VERSION", null); trans_status=(int) r.getInteger("TRANS_STATUS", -1L); readStep = StepMeta.findStep(steps, r.getInteger("ID_STEP_READ", -1L)); //$NON-NLS-1$ writeStep = StepMeta.findStep(steps, r.getInteger("ID_STEP_WRITE", -1L)); //$NON-NLS-1$ inputStep = StepMeta.findStep(steps, r.getInteger("ID_STEP_INPUT", -1L)); //$NON-NLS-1$ outputStep = StepMeta.findStep(steps, r.getInteger("ID_STEP_OUTPUT", -1L)); //$NON-NLS-1$ updateStep = StepMeta.findStep(steps, r.getInteger("ID_STEP_UPDATE", -1L)); //$NON-NLS-1$ long id_rejected = rep.getTransAttributeInteger(getID(), 0, "ID_STEP_REJECTED"); // $NON-NLS-1$ if (id_rejected>0) { rejectedStep = StepMeta.findStep(steps, id_rejected); //$NON-NLS-1$ } logConnection = DatabaseMeta.findDatabase(databases, r.getInteger("ID_DATABASE_LOG", -1L)); //$NON-NLS-1$ logTable = r.getString("TABLE_NAME_LOG", null); //$NON-NLS-1$ useBatchId = r.getBoolean("USE_BATCHID", false); //$NON-NLS-1$ logfieldUsed = r.getBoolean("USE_LOGFIELD", false); //$NON-NLS-1$ maxDateConnection = DatabaseMeta.findDatabase(databases, r.getInteger("ID_DATABASE_MAXDATE", -1L)); //$NON-NLS-1$ maxDateTable = r.getString("TABLE_NAME_MAXDATE", null); //$NON-NLS-1$ maxDateField = r.getString("FIELD_NAME_MAXDATE", null); //$NON-NLS-1$ maxDateOffset = r.getNumber("OFFSET_MAXDATE", 0.0); //$NON-NLS-1$ maxDateDifference = r.getNumber("DIFF_MAXDATE", 0.0); //$NON-NLS-1$ createdUser = r.getString("CREATED_USER", null); //$NON-NLS-1$ createdDate = r.getDate("CREATED_DATE", null); //$NON-NLS-1$ modifiedUser = r.getString("MODIFIED_USER", null); //$NON-NLS-1$ modifiedDate = r.getDate("MODIFIED_DATE", null); //$NON-NLS-1$ // Optional: sizeRowset = Const.ROWS_IN_ROWSET; Long val_size_rowset = r.getInteger("SIZE_ROWSET"); //$NON-NLS-1$ if (val_size_rowset != null ) { sizeRowset = val_size_rowset.intValue(); } long id_directory = r.getInteger("ID_DIRECTORY", -1L); //$NON-NLS-1$ if (id_directory >= 0) { log.logDetailed(toString(), "ID_DIRECTORY=" + id_directory); //$NON-NLS-1$ // Set right directory... directory = directoryTree.findDirectory(id_directory); } usingUniqueConnections = rep.getTransAttributeBoolean(getID(), 0, Repository.TRANS_ATTRIBUTE_UNIQUE_CONNECTIONS); feedbackShown = !"N".equalsIgnoreCase( rep.getTransAttributeString(getID(), 0, Repository.TRANS_ATTRIBUTE_FEEDBACK_SHOWN) ); feedbackSize = (int) rep.getTransAttributeInteger(getID(), 0, Repository.TRANS_ATTRIBUTE_FEEDBACK_SIZE); usingThreadPriorityManagment = !"N".equalsIgnoreCase( rep.getTransAttributeString(getID(), 0, Repository.TRANS_ATTRIBUTE_USING_THREAD_PRIORITIES) ); // Performance monitoring for steps... // capturingStepPerformanceSnapShots = rep.getTransAttributeBoolean(getID(), 0, Repository.TRANS_ATTRIBUTE_CAPTURE_STEP_PERFORMANCE); stepPerformanceCapturingDelay = rep.getTransAttributeInteger(getID(), 0, Repository.TRANS_ATTRIBUTE_STEP_PERFORMANCE_CAPTURING_DELAY); } } catch (KettleDatabaseException dbe) { throw new KettleException(Messages.getString("TransMeta.Exception.UnableToLoadTransformationInfoFromRepository"), dbe); //$NON-NLS-1$ } finally { initializeVariablesFrom(null); setInternalKettleVariables(); } } public boolean isRepReference() { return isRepReference(getFilename(), this.getName()); } public boolean isFileReference() { return !isRepReference(getFilename(), this.getName()); } public static boolean isRepReference(String exactFilename, String exactTransname) { return Const.isEmpty(exactFilename) && !Const.isEmpty(exactTransname); } public static boolean isFileReference(String exactFilename, String exactTransname) { return !isRepReference(exactFilename, exactTransname); } /** Read a transformation with a certain name from a repository * * @param rep The repository to read from. * @param transname The name of the transformation. * @param repdir the path to the repository directory */ public TransMeta(Repository rep, String transname, RepositoryDirectory repdir) throws KettleException { this(rep, transname, repdir, null, true); } /** * Read a transformation with a certain name from a repository * * @param rep The repository to read from. * @param transname The name of the transformation. * @param repdir the path to the repository directory * @param setInternalVariables true if you want to set the internal variables based on this transformation information */ public TransMeta(Repository rep, String transname, RepositoryDirectory repdir, boolean setInternalVariables) throws KettleException { this(rep, transname, repdir, null, setInternalVariables); } /** Read a transformation with a certain name from a repository * * @param rep The repository to read from. * @param transname The name of the transformation. * @param repdir the path to the repository directory * @param monitor The progress monitor to display the progress of the file-open operation in a dialog */ public TransMeta(Repository rep, String transname, RepositoryDirectory repdir, ProgressMonitorListener monitor) throws KettleException { this(rep, transname, repdir, monitor, true); } /** Read a transformation with a certain name from a repository * * @param rep The repository to read from. * @param transname The name of the transformation. * @param repdir the path to the repository directory * @param monitor The progress monitor to display the progress of the file-open operation in a dialog * @param setInternalVariables true if you want to set the internal variables based on this transformation information */ public TransMeta(Repository rep, String transname, RepositoryDirectory repdir, ProgressMonitorListener monitor, boolean setInternalVariables) throws KettleException { this(); try { String pathAndName = repdir.isRoot() ? repdir + transname : repdir + RepositoryDirectory.DIRECTORY_SEPARATOR + transname; setName(transname); directory = repdir; directoryTree = directory.findRoot(); // Get the transformation id log.logDetailed(toString(), Messages.getString("TransMeta.Log.LookingForTransformation", transname ,directory.getPath() )); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ if (monitor != null) monitor.subTask(Messages.getString("TransMeta.Monitor.ReadingTransformationInfoTask.Title")); //$NON-NLS-1$ setID(rep.getTransformationID(transname, directory.getID())); if (monitor != null) monitor.worked(1); // If no valid id is available in the database, then give error... if (getID() > 0) { long noteids[] = rep.getTransNoteIDs(getID()); long stepids[] = rep.getStepIDs(getID()); long hopids[] = rep.getTransHopIDs(getID()); int nrWork = 3 + noteids.length + stepids.length + hopids.length; if (monitor != null) monitor.beginTask(Messages.getString("TransMeta.Monitor.LoadingTransformationTask.Title") + pathAndName, nrWork); //$NON-NLS-1$ log.logDetailed(toString(), Messages.getString("TransMeta.Log.LoadingTransformation", getName() )); //$NON-NLS-1$ //$NON-NLS-2$ // Load the common database connections if (monitor != null) monitor.subTask(Messages.getString("TransMeta.Monitor.ReadingTheAvailableSharedObjectsTask.Title")); //$NON-NLS-1$ try { sharedObjects = readSharedObjects(rep); } catch(Exception e) { LogWriter.getInstance().logError(toString(), Messages.getString("TransMeta.ErrorReadingSharedObjects.Message", e.toString())); LogWriter.getInstance().logError(toString(), Const.getStackTracker(e)); } if (monitor != null) monitor.worked(1); // Load the notes... if (monitor != null) monitor.subTask(Messages.getString("TransMeta.Monitor.ReadingNoteTask.Title")); //$NON-NLS-1$ for (int i = 0; i < noteids.length; i++) { NotePadMeta ni = new NotePadMeta(log, rep, noteids[i]); if (indexOfNote(ni) < 0) addNote(ni); if (monitor != null) monitor.worked(1); } if (monitor != null) monitor.subTask(Messages.getString("TransMeta.Monitor.ReadingStepsTask.Title")); //$NON-NLS-1$ rep.fillStepAttributesBuffer(getID()); // read all the attributes on one go! for (int i = 0; i < stepids.length; i++) { log.logDetailed(toString(), Messages.getString("TransMeta.Log.LoadingStepWithID") + stepids[i]); //$NON-NLS-1$ if (monitor != null) monitor.subTask(Messages.getString("TransMeta.Monitor.ReadingStepTask.Title") + (i + 1) + "/" + (stepids.length)); //$NON-NLS-1$ //$NON-NLS-2$ StepMeta stepMeta = new StepMeta(rep, stepids[i], databases, counters, partitionSchemas); // In this case, we just add or replace the shared steps. // The repository is considered "more central" addOrReplaceStep(stepMeta); if (monitor != null) monitor.worked(1); } if (monitor != null) monitor.worked(1); rep.setStepAttributesBuffer(null); // clear the buffer (should be empty anyway) // Have all StreamValueLookups, etc. reference the correct source steps... for (int i = 0; i < nrSteps(); i++) { StepMetaInterface sii = getStep(i).getStepMetaInterface(); sii.searchInfoAndTargetSteps(steps); } if (monitor != null) monitor.subTask(Messages.getString("TransMeta.Monitor.LoadingTransformationDetailsTask.Title")); //$NON-NLS-1$ loadRepTrans(rep); if (monitor != null) monitor.worked(1); if (monitor != null) monitor.subTask(Messages.getString("TransMeta.Monitor.ReadingHopTask.Title")); //$NON-NLS-1$ for (int i = 0; i < hopids.length; i++) { TransHopMeta hi = new TransHopMeta(rep, hopids[i], steps); addTransHop(hi); if (monitor != null) monitor.worked(1); } // Have all step partitioning meta-data reference the correct schemas that we just loaded // for (int i = 0; i < nrSteps(); i++) { StepPartitioningMeta stepPartitioningMeta = getStep(i).getStepPartitioningMeta(); if (stepPartitioningMeta!=null) { stepPartitioningMeta.setPartitionSchemaAfterLoading(partitionSchemas); } } // Have all step clustering schema meta-data reference the correct cluster schemas that we just loaded // for (int i = 0; i < nrSteps(); i++) { getStep(i).setClusterSchemaAfterLoading(clusterSchemas); } if (monitor != null) monitor.subTask(Messages.getString("TransMeta.Monitor.ReadingTheDependenciesTask.Title")); //$NON-NLS-1$ long depids[] = rep.getTransDependencyIDs(getID()); for (int i = 0; i < depids.length; i++) { TransDependency td = new TransDependency(rep, depids[i], databases); addDependency(td); } if (monitor != null) monitor.worked(1); // Also load the step error handling metadata // for (int i=0;i<nrSteps();i++) { StepMeta stepMeta = getStep(i); String sourceStep = rep.getStepAttributeString(stepMeta.getID(), "step_error_handling_source_step"); if (sourceStep!=null) { StepErrorMeta stepErrorMeta = new StepErrorMeta(this, rep, stepMeta, steps); stepErrorMeta.getSourceStep().setStepErrorMeta(stepErrorMeta); // a bit of a trick, I know. } } if (monitor != null) monitor.subTask(Messages.getString("TransMeta.Monitor.SortingStepsTask.Title")); //$NON-NLS-1$ sortSteps(); if (monitor != null) monitor.worked(1); if (monitor != null) monitor.done(); } else { throw new KettleException(Messages.getString("TransMeta.Exception.TransformationDoesNotExist") + name); //$NON-NLS-1$ } log.logDetailed(toString(), Messages.getString("TransMeta.Log.LoadedTransformation2", transname , String.valueOf(directory == null))); //$NON-NLS-1$ //$NON-NLS-2$ log.logDetailed(toString(), Messages.getString("TransMeta.Log.LoadedTransformation", transname , directory.getPath() )); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } catch (KettleDatabaseException e) { log.logError(toString(), Messages.getString("TransMeta.Log.DatabaseErrorOccuredReadingTransformation") + Const.CR + e); //$NON-NLS-1$ throw new KettleException(Messages.getString("TransMeta.Exception.DatabaseErrorOccuredReadingTransformation"), e); //$NON-NLS-1$ } catch (Exception e) { log.logError(toString(), Messages.getString("TransMeta.Log.DatabaseErrorOccuredReadingTransformation") + Const.CR + e); //$NON-NLS-1$ throw new KettleException(Messages.getString("TransMeta.Exception.DatabaseErrorOccuredReadingTransformation2"), e); //$NON-NLS-1$ } finally { initializeVariablesFrom(null); if (setInternalVariables) setInternalKettleVariables(); } } /** * Find the location of hop * * @param hi The hop queried * @return The location of the hop, -1 if nothing was found. */ public int indexOfTransHop(TransHopMeta hi) { return hops.indexOf(hi); } /** * Find the location of step * * @param stepMeta The step queried * @return The location of the step, -1 if nothing was found. */ public int indexOfStep(StepMeta stepMeta) { return steps.indexOf(stepMeta); } /* (non-Javadoc) * @see org.pentaho.di.trans.HasDatabaseInterface#indexOfDatabase(org.pentaho.di.core.database.DatabaseMeta) */ public int indexOfDatabase(DatabaseMeta ci) { return databases.indexOf(ci); } /** * Find the location of a note * * @param ni The note queried * @return The location of the note, -1 if nothing was found. */ public int indexOfNote(NotePadMeta ni) { return notes.indexOf(ni); } public String getFileType() { return LastUsedFile.FILE_TYPE_TRANSFORMATION; } public String[] getFilterNames() { return Const.getTransformationFilterNames(); } public String[] getFilterExtensions() { return Const.STRING_TRANS_FILTER_EXT; } public String getDefaultExtension() { return Const.STRING_TRANS_DEFAULT_EXT; } public String getXML() { Props props = null; if (Props.isInitialized()) props=Props.getInstance(); StringBuffer retval = new StringBuffer(800); retval.append(XMLHandler.openTag(XML_TAG)).append(Const.CR); //$NON-NLS-1$ retval.append(" ").append(XMLHandler.openTag(XML_TAG_INFO)).append(Const.CR); //$NON-NLS-1$ retval.append(" ").append(XMLHandler.addTagValue("name", name)); //$NON-NLS-1$ //$NON-NLS-2$ retval.append(" ").append(XMLHandler.addTagValue("description", description)); //$NON-NLS-1$ //$NON-NLS-2$ retval.append(" ").append(XMLHandler.addTagValue("extended_description", extended_description)); retval.append(" ").append(XMLHandler.addTagValue("trans_version", trans_version)); if ( trans_status >= 0 ) { retval.append(" ").append(XMLHandler.addTagValue("trans_status", trans_status)); } retval.append(" ").append(XMLHandler.addTagValue("directory", directory != null ? directory.getPath() : RepositoryDirectory.DIRECTORY_SEPARATOR)); //$NON-NLS-1$ //$NON-NLS-2$ retval.append(" <log>").append(Const.CR); //$NON-NLS-1$ retval.append(" ").append(XMLHandler.addTagValue("read", readStep == null ? "" : readStep.getName())); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ retval.append(" ").append(XMLHandler.addTagValue("write", writeStep == null ? "" : writeStep.getName())); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ retval.append(" ").append(XMLHandler.addTagValue("input", inputStep == null ? "" : inputStep.getName())); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ retval.append(" ").append(XMLHandler.addTagValue("output", outputStep == null ? "" : outputStep.getName())); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ retval.append(" ").append(XMLHandler.addTagValue("update", updateStep == null ? "" : updateStep.getName())); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ retval.append(" ").append(XMLHandler.addTagValue("rejected", rejectedStep == null ? "" : rejectedStep.getName())); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ retval.append(" ").append(XMLHandler.addTagValue("connection", logConnection == null ? "" : logConnection.getName())); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ retval.append(" ").append(XMLHandler.addTagValue("table", logTable)); //$NON-NLS-1$ //$NON-NLS-2$ retval.append(" ").append(XMLHandler.addTagValue("use_batchid", useBatchId)); //$NON-NLS-1$ //$NON-NLS-2$ retval.append(" ").append(XMLHandler.addTagValue("use_logfield", logfieldUsed)); //$NON-NLS-1$ //$NON-NLS-2$ retval.append(" </log>").append(Const.CR); //$NON-NLS-1$ retval.append(" <maxdate>").append(Const.CR); //$NON-NLS-1$ retval.append(" ").append(XMLHandler.addTagValue("connection", maxDateConnection == null ? "" : maxDateConnection.getName())); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ retval.append(" ").append(XMLHandler.addTagValue("table", maxDateTable)); //$NON-NLS-1$ //$NON-NLS-2$ retval.append(" ").append(XMLHandler.addTagValue("field", maxDateField)); //$NON-NLS-1$ //$NON-NLS-2$ retval.append(" ").append(XMLHandler.addTagValue("offset", maxDateOffset)); //$NON-NLS-1$ //$NON-NLS-2$ retval.append(" ").append(XMLHandler.addTagValue("maxdiff", maxDateDifference)); //$NON-NLS-1$ //$NON-NLS-2$ retval.append(" </maxdate>").append(Const.CR); //$NON-NLS-1$ retval.append(" ").append(XMLHandler.addTagValue("size_rowset", sizeRowset)); //$NON-NLS-1$ //$NON-NLS-2$ retval.append(" ").append(XMLHandler.addTagValue("sleep_time_empty", sleepTimeEmpty)); //$NON-NLS-1$ //$NON-NLS-2$ retval.append(" ").append(XMLHandler.addTagValue("sleep_time_full", sleepTimeFull)); //$NON-NLS-1$ //$NON-NLS-2$ retval.append(" ").append(XMLHandler.addTagValue("unique_connections", usingUniqueConnections)); //$NON-NLS-1$ //$NON-NLS-2$ retval.append(" ").append(XMLHandler.addTagValue("feedback_shown", feedbackShown)); //$NON-NLS-1$ //$NON-NLS-2$ retval.append(" ").append(XMLHandler.addTagValue("feedback_size", feedbackSize)); //$NON-NLS-1$ //$NON-NLS-2$ retval.append(" ").append(XMLHandler.addTagValue("using_thread_priorities", usingThreadPriorityManagment)); // $NON-NLS-1$ retval.append(" ").append(XMLHandler.addTagValue("shared_objects_file", sharedObjectsFile)); // $NON-NLS-1$ // Performance monitoring // retval.append(" ").append(XMLHandler.addTagValue("capture_step_performance", capturingStepPerformanceSnapShots)); // $NON-NLS-1$ retval.append(" ").append(XMLHandler.addTagValue("step_performance_capturing_delay", stepPerformanceCapturingDelay)); // $NON-NLS-1$ retval.append(" ").append(XMLHandler.openTag(XML_TAG_DEPENDENCIES)).append(Const.CR); //$NON-NLS-1$ for (int i = 0; i < nrDependencies(); i++) { TransDependency td = getDependency(i); retval.append(td.getXML()); } retval.append(" ").append(XMLHandler.closeTag(XML_TAG_DEPENDENCIES)).append(Const.CR); //$NON-NLS-1$ // The partitioning schemas... // retval.append(" ").append(XMLHandler.openTag(XML_TAG_PARTITIONSCHEMAS)).append(Const.CR); //$NON-NLS-1$ for (int i = 0; i < partitionSchemas.size(); i++) { PartitionSchema partitionSchema = partitionSchemas.get(i); retval.append(partitionSchema.getXML()); } retval.append(" ").append(XMLHandler.closeTag(XML_TAG_PARTITIONSCHEMAS)).append(Const.CR); //$NON-NLS-1$ // The slave servers... // retval.append(" ").append(XMLHandler.openTag(XML_TAG_SLAVESERVERS)).append(Const.CR); //$NON-NLS-1$ for (int i = 0; i < slaveServers.size(); i++) { SlaveServer slaveServer = slaveServers.get(i); retval.append(" ").append(slaveServer.getXML()).append(Const.CR); } retval.append(" ").append(XMLHandler.closeTag(XML_TAG_SLAVESERVERS)).append(Const.CR); //$NON-NLS-1$ // The cluster schemas... // retval.append(" ").append(XMLHandler.openTag(XML_TAG_CLUSTERSCHEMAS)).append(Const.CR); //$NON-NLS-1$ for (int i = 0; i < clusterSchemas.size(); i++) { ClusterSchema clusterSchema = clusterSchemas.get(i); retval.append(clusterSchema.getXML()); } retval.append(" ").append(XMLHandler.closeTag(XML_TAG_CLUSTERSCHEMAS)).append(Const.CR); //$NON-NLS-1$ retval.append(" ").append(XMLHandler.addTagValue("modified_user", modifiedUser)); retval.append(" ").append(XMLHandler.addTagValue("modified_date", modifiedDate)); retval.append(" ").append(XMLHandler.closeTag(XML_TAG_INFO)).append(Const.CR); //$NON-NLS-1$ retval.append(" ").append(XMLHandler.openTag(XML_TAG_NOTEPADS)).append(Const.CR); //$NON-NLS-1$ if (notes != null) for (int i = 0; i < nrNotes(); i++) { NotePadMeta ni = getNote(i); retval.append(ni.getXML()); } retval.append(" ").append(XMLHandler.closeTag(XML_TAG_NOTEPADS)).append(Const.CR); //$NON-NLS-1$ // The database connections... for (int i = 0; i < nrDatabases(); i++) { DatabaseMeta dbMeta = getDatabase(i); if (props!=null && props.areOnlyUsedConnectionsSavedToXML()) { if (isDatabaseConnectionUsed(dbMeta)) retval.append(dbMeta.getXML()); } else { retval.append(dbMeta.getXML()); } } retval.append(" ").append(XMLHandler.openTag(XML_TAG_ORDER)).append(Const.CR); //$NON-NLS-1$ for (int i = 0; i < nrTransHops(); i++) { TransHopMeta transHopMeta = getTransHop(i); retval.append(transHopMeta.getXML()); } retval.append(" ").append(XMLHandler.closeTag(XML_TAG_ORDER)).append(Const.CR); //$NON-NLS-1$ /* The steps... */ for (int i = 0; i < nrSteps(); i++) { StepMeta stepMeta = getStep(i); retval.append(stepMeta.getXML()); } /* The error handling metadata on the steps */ retval.append(" ").append(XMLHandler.openTag(XML_TAG_STEP_ERROR_HANDLING)).append(Const.CR); for (int i = 0; i < nrSteps(); i++) { StepMeta stepMeta = getStep(i); if (stepMeta.getStepErrorMeta()!=null) { retval.append(stepMeta.getStepErrorMeta().getXML()); } } retval.append(" ").append(XMLHandler.closeTag(XML_TAG_STEP_ERROR_HANDLING)).append(Const.CR); // The slave-step-copy/partition distribution. Only used for slave transformations in a clustering environment. retval.append(" ").append(slaveStepCopyPartitionDistribution.getXML()); // Is this a slave transformation or not? retval.append(" ").append(XMLHandler.addTagValue("slave_transformation", slaveTransformation)); retval.append("</").append(XML_TAG+">").append(Const.CR); //$NON-NLS-1$ return retval.toString(); } /** * Parse a file containing the XML that describes the transformation. * No default connections are loaded since no repository is available at this time. * Since the filename is set, internal variables are being set that relate to this. * * @param fname The filename */ public TransMeta(String fname) throws KettleXMLException { this(fname, true); } /** * Parse a file containing the XML that describes the transformation. * No default connections are loaded since no repository is available at this time. * * @param fname The filename * @param setInternalVariables true if you want to set the internal variables based on this transformation information */ public TransMeta(String fname, boolean setInternalVariables) throws KettleXMLException { this(fname, null, setInternalVariables); } /** * Parse a file containing the XML that describes the transformation. * * @param fname The filename * @param rep The repository to load the default set of connections from, null if no repository is avaailable */ public TransMeta(String fname, Repository rep) throws KettleXMLException { this(fname, rep, true); } /** * Parse a file containing the XML that describes the transformation. * * @param fname The filename * @param rep The repository to load the default set of connections from, null if no repository is avaailable * @param setInternalVariables true if you want to set the internal variables based on this transformation information */ public TransMeta(String fname, Repository rep, boolean setInternalVariables ) throws KettleXMLException { // OK, try to load using the VFS stuff... Document doc=null; try { doc = XMLHandler.loadXMLFile(KettleVFS.getFileObject(fname)); } catch (IOException e) { throw new KettleXMLException(Messages.getString("TransMeta.Exception.ErrorOpeningOrValidatingTheXMLFile", fname)+" : "+e.toString(), e); } if (doc != null) { // Clear the transformation clearUndo(); clear(); // Root node: Node transnode = XMLHandler.getSubNode(doc, XML_TAG); //$NON-NLS-1$ // Load from this node... loadXML(transnode, rep, setInternalVariables); setFilename(fname); } else { throw new KettleXMLException(Messages.getString("TransMeta.Exception.ErrorOpeningOrValidatingTheXMLFile", fname)); //$NON-NLS-1$ } } /* * Load the transformation from an XML node * * @param transnode The XML node to parse * @throws KettleXMLException * public TransMeta(Node transnode) throws KettleXMLException { loadXML(transnode); } */ /* * Parse a file containing the XML that describes the transformation. * (no repository is available to load default list of database connections from) * * @param transnode The XML node to load from * @throws KettleXMLException * private void loadXML(Node transnode) throws KettleXMLException { loadXML(transnode, null, false); } */ /** * Parse a file containing the XML that describes the transformation. * Specify a repository to load default list of database connections from and to reference in mappings etc. * * @param transnode The XML node to load from * @param rep the repository to reference. * @throws KettleXMLException */ public TransMeta(Node transnode, Repository rep) throws KettleXMLException { loadXML(transnode, rep, false); } /** * Parse a file containing the XML that describes the transformation. * * @param transnode The XML node to load from * @param rep The repository to load the default list of database connections from (null if no repository is available) * @param setInternalVariables true if you want to set the internal variables based on this transformation information * @throws KettleXMLException */ public void loadXML(Node transnode, Repository rep, boolean setInternalVariables ) throws KettleXMLException { Props props = null; if (Props.isInitialized()) { props=Props.getInstance(); } try { // Clear the transformation clearUndo(); clear(); // Read all the database connections from the repository to make sure that we don't overwrite any there by loading from XML. try { sharedObjectsFile = XMLHandler.getTagValue(transnode, "info", "shared_objects_file"); //$NON-NLS-1$ //$NON-NLS-2$ sharedObjects = readSharedObjects(rep); } catch(Exception e) { LogWriter.getInstance().logError(toString(), Messages.getString("TransMeta.ErrorReadingSharedObjects.Message", e.toString())); LogWriter.getInstance().logError(toString(), Const.getStackTracker(e)); } // Handle connections int n = XMLHandler.countNodes(transnode, DatabaseMeta.XML_TAG); //$NON-NLS-1$ log.logDebug(toString(), Messages.getString("TransMeta.Log.WeHaveConnections", String.valueOf(n) )); //$NON-NLS-1$ //$NON-NLS-2$ for (int i = 0; i < n; i++) { log.logDebug(toString(), Messages.getString("TransMeta.Log.LookingAtConnection") + i); //$NON-NLS-1$ Node nodecon = XMLHandler.getSubNodeByNr(transnode, DatabaseMeta.XML_TAG, i); //$NON-NLS-1$ DatabaseMeta dbcon = new DatabaseMeta(nodecon); dbcon.shareVariablesWith(this); DatabaseMeta exist = findDatabase(dbcon.getName()); if (exist == null) { addDatabase(dbcon); } else { if (!exist.isShared()) // otherwise, we just keep the shared connection. { boolean askOverwrite = Props.isInitialized() ? props.askAboutReplacingDatabaseConnections() : false; boolean overwrite = Props.isInitialized() ? props.replaceExistingDatabaseConnections() : true; if (askOverwrite) { if( SpoonFactory.getInstance() != null ) { Object res[] = SpoonFactory.getInstance().messageDialogWithToggle("Warning", null, "Connection ["+dbcon.getName()+"] already exists, do you want to overwrite this database connection?", Const.WARNING, new String[] { Messages.getString("System.Button.Yes"), //$NON-NLS-1$ Messages.getString("System.Button.No") },//$NON-NLS-1$ 1, "Please, don't show this warning anymore.", !props.askAboutReplacingDatabaseConnections() ); int idx = ((Integer)res[0]).intValue(); boolean toggleState = ((Boolean)res[1]).booleanValue(); props.setAskAboutReplacingDatabaseConnections(!toggleState); overwrite = ((idx&0xFF)==0); // Yes means: overwrite } } if (overwrite) { int idx = indexOfDatabase(exist); removeDatabase(idx); addDatabase(idx, dbcon); } } } } // Read the notes... Node notepadsnode = XMLHandler.getSubNode(transnode, XML_TAG_NOTEPADS); //$NON-NLS-1$ int nrnotes = XMLHandler.countNodes(notepadsnode, NotePadMeta.XML_TAG); //$NON-NLS-1$ for (int i = 0; i < nrnotes; i++) { Node notepadnode = XMLHandler.getSubNodeByNr(notepadsnode, NotePadMeta.XML_TAG, i); //$NON-NLS-1$ NotePadMeta ni = new NotePadMeta(notepadnode); notes.add(ni); } // Handle Steps int s = XMLHandler.countNodes(transnode, StepMeta.XML_TAG); //$NON-NLS-1$ log.logDebug(toString(), Messages.getString("TransMeta.Log.ReadingSteps") + s + " steps..."); //$NON-NLS-1$ //$NON-NLS-2$ for (int i = 0; i < s; i++) { Node stepnode = XMLHandler.getSubNodeByNr(transnode, StepMeta.XML_TAG, i); //$NON-NLS-1$ log.logDebug(toString(), Messages.getString("TransMeta.Log.LookingAtStep") + i); //$NON-NLS-1$ StepMeta stepMeta = new StepMeta(stepnode, databases, counters); // Check if the step exists and if it's a shared step. // If so, then we will keep the shared version, not this one. // The stored XML is only for backup purposes. // StepMeta check = findStep(stepMeta.getName()); if (check!=null) { if (!check.isShared()) // Don't overwrite shared objects { addOrReplaceStep(stepMeta); } else { check.setDraw(stepMeta.isDrawn()); // Just keep the drawn flag and location check.setLocation(stepMeta.getLocation()); } } else { addStep(stepMeta); // simply add it. } } // Read the error handling code of the steps... // Node errorHandlingNode = XMLHandler.getSubNode(transnode, XML_TAG_STEP_ERROR_HANDLING); int nrErrorHandlers = XMLHandler.countNodes(errorHandlingNode, StepErrorMeta.XML_TAG); for (int i=0;i<nrErrorHandlers;i++) { Node stepErrorMetaNode = XMLHandler.getSubNodeByNr(errorHandlingNode, StepErrorMeta.XML_TAG, i); StepErrorMeta stepErrorMeta = new StepErrorMeta(this, stepErrorMetaNode, steps); stepErrorMeta.getSourceStep().setStepErrorMeta(stepErrorMeta); // a bit of a trick, I know. } // Have all StreamValueLookups, etc. reference the correct source steps... // for (int i = 0; i < nrSteps(); i++) { StepMeta stepMeta = getStep(i); StepMetaInterface sii = stepMeta.getStepMetaInterface(); if (sii != null) sii.searchInfoAndTargetSteps(steps); } // Handle Hops // Node ordernode = XMLHandler.getSubNode(transnode, XML_TAG_ORDER); //$NON-NLS-1$ n = XMLHandler.countNodes(ordernode, TransHopMeta.XML_TAG); //$NON-NLS-1$ log.logDebug(toString(), Messages.getString("TransMeta.Log.WeHaveHops") + n + " hops..."); //$NON-NLS-1$ //$NON-NLS-2$ for (int i = 0; i < n; i++) { log.logDebug(toString(), Messages.getString("TransMeta.Log.LookingAtHop") + i); //$NON-NLS-1$ Node hopnode = XMLHandler.getSubNodeByNr(ordernode, TransHopMeta.XML_TAG, i); //$NON-NLS-1$ TransHopMeta hopinf = new TransHopMeta(hopnode, steps); addTransHop(hopinf); } // // get transformation info: // Node infonode = XMLHandler.getSubNode(transnode, XML_TAG_INFO); //$NON-NLS-1$ // Name // name = XMLHandler.getTagValue(infonode, "name"); //$NON-NLS-1$ // description // description = XMLHandler.getTagValue(infonode, "description"); // extended description // extended_description = XMLHandler.getTagValue(infonode, "extended_description"); // trans version // trans_version = XMLHandler.getTagValue(infonode, "trans_version"); // trans status // trans_status = Const.toInt(XMLHandler.getTagValue(infonode, "trans_status"),-1); // Optionally load the repository directory... // if (rep!=null) { String directoryPath = XMLHandler.getTagValue(infonode, "directory"); if (directoryPath!=null) { directory = rep.getDirectoryTree().findDirectory(directoryPath); } } // Logging method... readStep = findStep(XMLHandler.getTagValue(infonode, "log", "read")); //$NON-NLS-1$ //$NON-NLS-2$ writeStep = findStep(XMLHandler.getTagValue(infonode, "log", "write")); //$NON-NLS-1$ //$NON-NLS-2$ inputStep = findStep(XMLHandler.getTagValue(infonode, "log", "input")); //$NON-NLS-1$ //$NON-NLS-2$ outputStep = findStep(XMLHandler.getTagValue(infonode, "log", "output")); //$NON-NLS-1$ //$NON-NLS-2$ updateStep = findStep(XMLHandler.getTagValue(infonode, "log", "update")); //$NON-NLS-1$ //$NON-NLS-2$ rejectedStep = findStep(XMLHandler.getTagValue(infonode, "log", "rejected")); //$NON-NLS-1$ //$NON-NLS-2$ String logcon = XMLHandler.getTagValue(infonode, "log", "connection"); //$NON-NLS-1$ //$NON-NLS-2$ logConnection = findDatabase(logcon); logTable = XMLHandler.getTagValue(infonode, "log", "table"); //$NON-NLS-1$ //$NON-NLS-2$ useBatchId = "Y".equalsIgnoreCase(XMLHandler.getTagValue(infonode, "log", "use_batchid")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ logfieldUsed= "Y".equalsIgnoreCase(XMLHandler.getTagValue(infonode, "log", "USE_LOGFIELD")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ // Maxdate range options... String maxdatcon = XMLHandler.getTagValue(infonode, "maxdate", "connection"); //$NON-NLS-1$ //$NON-NLS-2$ maxDateConnection = findDatabase(maxdatcon); maxDateTable = XMLHandler.getTagValue(infonode, "maxdate", "table"); //$NON-NLS-1$ //$NON-NLS-2$ maxDateField = XMLHandler.getTagValue(infonode, "maxdate", "field"); //$NON-NLS-1$ //$NON-NLS-2$ String offset = XMLHandler.getTagValue(infonode, "maxdate", "offset"); //$NON-NLS-1$ //$NON-NLS-2$ maxDateOffset = Const.toDouble(offset, 0.0); String mdiff = XMLHandler.getTagValue(infonode, "maxdate", "maxdiff"); //$NON-NLS-1$ //$NON-NLS-2$ maxDateDifference = Const.toDouble(mdiff, 0.0); // Check the dependencies as far as dates are concerned... // We calculate BEFORE we run the MAX of these dates // If the date is larger then enddate, startdate is set to MIN_DATE // Node depsNode = XMLHandler.getSubNode(infonode, XML_TAG_DEPENDENCIES); //$NON-NLS-1$ int nrDeps = XMLHandler.countNodes(depsNode, TransDependency.XML_TAG); //$NON-NLS-1$ for (int i = 0; i < nrDeps; i++) { Node depNode = XMLHandler.getSubNodeByNr(depsNode, TransDependency.XML_TAG, i); //$NON-NLS-1$ TransDependency transDependency = new TransDependency(depNode, databases); if (transDependency.getDatabase() != null && transDependency.getFieldname() != null) { addDependency(transDependency); } } // Read the partitioning schemas // Node partSchemasNode = XMLHandler.getSubNode(infonode, XML_TAG_PARTITIONSCHEMAS); //$NON-NLS-1$ int nrPartSchemas = XMLHandler.countNodes(partSchemasNode, PartitionSchema.XML_TAG); //$NON-NLS-1$ for (int i = 0 ; i < nrPartSchemas ; i++) { Node partSchemaNode = XMLHandler.getSubNodeByNr(partSchemasNode, PartitionSchema.XML_TAG, i); PartitionSchema partitionSchema = new PartitionSchema(partSchemaNode); // Check if the step exists and if it's a shared step. // If so, then we will keep the shared version, not this one. // The stored XML is only for backup purposes. // PartitionSchema check = findPartitionSchema(partitionSchema.getName()); if (check!=null) { if (!check.isShared()) // we don't overwrite shared objects. { addOrReplacePartitionSchema(partitionSchema); } } else { partitionSchemas.add(partitionSchema); } } // Have all step partitioning meta-data reference the correct schemas that we just loaded // for (int i = 0; i < nrSteps(); i++) { StepPartitioningMeta stepPartitioningMeta = getStep(i).getStepPartitioningMeta(); if (stepPartitioningMeta!=null) { stepPartitioningMeta.setPartitionSchemaAfterLoading(partitionSchemas); } StepPartitioningMeta targetStepPartitioningMeta = getStep(i).getTargetStepPartitioningMeta(); if (targetStepPartitioningMeta!=null) { targetStepPartitioningMeta.setPartitionSchemaAfterLoading(partitionSchemas); } } // Read the slave servers... // Node slaveServersNode = XMLHandler.getSubNode(infonode, XML_TAG_SLAVESERVERS); //$NON-NLS-1$ int nrSlaveServers = XMLHandler.countNodes(slaveServersNode, SlaveServer.XML_TAG); //$NON-NLS-1$ for (int i = 0 ; i < nrSlaveServers ; i++) { Node slaveServerNode = XMLHandler.getSubNodeByNr(slaveServersNode, SlaveServer.XML_TAG, i); SlaveServer slaveServer = new SlaveServer(slaveServerNode); // Check if the object exists and if it's a shared object. // If so, then we will keep the shared version, not this one. // The stored XML is only for backup purposes. SlaveServer check = findSlaveServer(slaveServer.getName()); if (check!=null) { if (!check.isShared()) // we don't overwrite shared objects. { addOrReplaceSlaveServer(slaveServer); } } else { slaveServers.add(slaveServer); } } // Read the cluster schemas // Node clusterSchemasNode = XMLHandler.getSubNode(infonode, XML_TAG_CLUSTERSCHEMAS); //$NON-NLS-1$ int nrClusterSchemas = XMLHandler.countNodes(clusterSchemasNode, ClusterSchema.XML_TAG); //$NON-NLS-1$ for (int i = 0 ; i < nrClusterSchemas ; i++) { Node clusterSchemaNode = XMLHandler.getSubNodeByNr(clusterSchemasNode, ClusterSchema.XML_TAG, i); ClusterSchema clusterSchema = new ClusterSchema(clusterSchemaNode, slaveServers); // Check if the object exists and if it's a shared object. // If so, then we will keep the shared version, not this one. // The stored XML is only for backup purposes. ClusterSchema check = findClusterSchema(clusterSchema.getName()); if (check!=null) { if (!check.isShared()) // we don't overwrite shared objects. { addOrReplaceClusterSchema(clusterSchema); } } else { clusterSchemas.add(clusterSchema); } } // Have all step clustering schema meta-data reference the correct cluster schemas that we just loaded // for (int i = 0; i < nrSteps(); i++) { getStep(i).setClusterSchemaAfterLoading(clusterSchemas); } String srowset = XMLHandler.getTagValue(infonode, "size_rowset"); //$NON-NLS-1$ sizeRowset = Const.toInt(srowset, Const.ROWS_IN_ROWSET); sleepTimeEmpty = Const.toInt(XMLHandler.getTagValue(infonode, "sleep_time_empty"), Const.TIMEOUT_GET_MILLIS); //$NON-NLS-1$ sleepTimeFull = Const.toInt(XMLHandler.getTagValue(infonode, "sleep_time_full"), Const.TIMEOUT_PUT_MILLIS); //$NON-NLS-1$ usingUniqueConnections = "Y".equalsIgnoreCase( XMLHandler.getTagValue(infonode, "unique_connections") ); //$NON-NLS-1$ feedbackShown = !"N".equalsIgnoreCase( XMLHandler.getTagValue(infonode, "feedback_shown") ); //$NON-NLS-1$ feedbackSize = Const.toInt(XMLHandler.getTagValue(infonode, "feedback_size"), Const.ROWS_UPDATE); //$NON-NLS-1$ usingThreadPriorityManagment = !"N".equalsIgnoreCase( XMLHandler.getTagValue(infonode, "using_thread_priorities") ); //$NON-NLS-1$ // Performance monitoring for steps... // capturingStepPerformanceSnapShots = "Y".equalsIgnoreCase(XMLHandler.getTagValue(infonode, "capture_step_performance")); // $NON-NLS-1$ $NON-NLS-2$ stepPerformanceCapturingDelay = Const.toLong(XMLHandler.getTagValue(infonode, "step_performance_capturing_delay"), 1000); // $NON-NLS-1$ // Created user/date createdUser = XMLHandler.getTagValue(infonode, "created_user"); String createDate = XMLHandler.getTagValue(infonode, "created_date"); if (createDate!=null) { createdDate = XMLHandler.stringToDate(createDate); } // Changed user/date modifiedUser = XMLHandler.getTagValue(infonode, "modified_user"); String modDate = XMLHandler.getTagValue(infonode, "modified_date"); if (modDate!=null) { modifiedDate = XMLHandler.stringToDate(modDate); } Node partitionDistNode = XMLHandler.getSubNode(transnode, SlaveStepCopyPartitionDistribution.XML_TAG); if (partitionDistNode!=null) { slaveStepCopyPartitionDistribution = new SlaveStepCopyPartitionDistribution(partitionDistNode); } else { slaveStepCopyPartitionDistribution = new SlaveStepCopyPartitionDistribution(); // leave empty } // Is this a slave transformation? // slaveTransformation = "Y".equalsIgnoreCase(XMLHandler.getTagValue(transnode, "slave_transformation")); log.logDebug(toString(), Messages.getString("TransMeta.Log.NumberOfStepsReaded") + nrSteps()); //$NON-NLS-1$ log.logDebug(toString(), Messages.getString("TransMeta.Log.NumberOfHopsReaded") + nrTransHops()); //$NON-NLS-1$ sortSteps(); } catch (KettleXMLException xe) { throw new KettleXMLException(Messages.getString("TransMeta.Exception.ErrorReadingTransformation"), xe); //$NON-NLS-1$ } catch (KettleException e) { throw new KettleXMLException(e); } finally { initializeVariablesFrom(null); if (setInternalVariables) setInternalKettleVariables(); } } public SharedObjects readSharedObjects(Repository rep) throws KettleException { if ( rep != null ) { sharedObjectsFile = rep.getTransAttributeString(getId(), 0, "SHARED_FILE"); } // Extract the shared steps, connections, etc. using the SharedObjects class // String soFile = environmentSubstitute(sharedObjectsFile); SharedObjects sharedObjects = new SharedObjects(soFile); // First read the databases... // We read databases & slaves first because there might be dependencies that need to be resolved. // for (SharedObjectInterface object : sharedObjects.getObjectsMap().values()) { if (object instanceof DatabaseMeta) { DatabaseMeta databaseMeta = (DatabaseMeta) object; databaseMeta.shareVariablesWith(this); addOrReplaceDatabase(databaseMeta); } else if (object instanceof SlaveServer) { SlaveServer slaveServer = (SlaveServer) object; addOrReplaceSlaveServer(slaveServer); } else if (object instanceof StepMeta) { StepMeta stepMeta = (StepMeta) object; addOrReplaceStep(stepMeta); } else if (object instanceof PartitionSchema) { PartitionSchema partitionSchema = (PartitionSchema) object; addOrReplacePartitionSchema(partitionSchema); } else if (object instanceof ClusterSchema) { ClusterSchema clusterSchema = (ClusterSchema) object; addOrReplaceClusterSchema(clusterSchema); } } if (rep!=null) { readDatabases(rep, true); readPartitionSchemas(rep, true); readSlaves(rep, true); readClusters(rep, true); } return sharedObjects; } /** * Gives you an List of all the steps that are at least used in one active hop. These steps will be used to * execute the transformation. The others will not be executed. * Update 3.0 : we also add those steps that are not linked to another hop, but have at least one remote input or output step defined. * * @param all Set to true if you want to get ALL the steps from the transformation. * @return A ArrayList of steps */ public List<StepMeta> getTransHopSteps(boolean all) { List<StepMeta> st = new ArrayList<StepMeta>(); int idx; for (int x = 0; x < nrTransHops(); x++) { TransHopMeta hi = getTransHop(x); if (hi.isEnabled() || all) { idx = st.indexOf(hi.getFromStep()); // FROM if (idx < 0) st.add(hi.getFromStep()); idx = st.indexOf(hi.getToStep()); // TO if (idx < 0) st.add(hi.getToStep()); } } // Also, add the steps that need to be painted, but are not part of a hop for (int x = 0; x < nrSteps(); x++) { StepMeta stepMeta = getStep(x); if (stepMeta.isDrawn() && !isStepUsedInTransHops(stepMeta)) { st.add(stepMeta); } if (!stepMeta.getRemoteInputSteps().isEmpty() || !stepMeta.getRemoteOutputSteps().isEmpty()) { if (!st.contains(stepMeta)) st.add(stepMeta); } } return st; } /** * Get the name of the transformation * * @return The name of the transformation */ public String getName() { return name; } /** * Set the name of the transformation. * * @param n The new name of the transformation */ public void setName(String n) { name = n; setInternalKettleVariables(); } /** * Builds a name - if no name is set, yet - from the filename */ public void nameFromFilename() { if (!Const.isEmpty(filename)) { name = Const.createName(filename); } } /** * Get the filename (if any) of the transformation * * @return The filename of the transformation. */ public String getFilename() { return filename; } /** * Set the filename of the transformation * * @param fname The new filename of the transformation. */ public void setFilename(String fname) { filename = fname; setInternalKettleVariables(); } /** * Determines if a step has been used in a hop or not. * * @param stepMeta The step queried. * @return True if a step is used in a hop (active or not), false if this is not the case. */ public boolean isStepUsedInTransHops(StepMeta stepMeta) { TransHopMeta fr = findTransHopFrom(stepMeta); TransHopMeta to = findTransHopTo(stepMeta); if (fr != null || to != null) return true; return false; } /** * Sets the changed parameter of the transformation. * * @param ch True if you want to mark the transformation as changed, false if not. */ public void setChanged(boolean ch) { if (ch) setChanged(); else clearChanged(); } /** * Clears the different changed flags of the transformation. * */ public void clearChanged() { changed_steps = false; changed_databases = false; changed_hops = false; changed_notes = false; for (int i = 0; i < nrSteps(); i++) { getStep(i).setChanged(false); if (getStep(i).getStepPartitioningMeta() != null) { getStep(i).getStepPartitioningMeta().hasChanged(false); } } for (int i = 0; i < nrDatabases(); i++) { getDatabase(i).setChanged(false); } for (int i = 0; i < nrTransHops(); i++) { getTransHop(i).setChanged(false); } for (int i = 0; i < nrNotes(); i++) { getNote(i).setChanged(false); } for (int i = 0; i < partitionSchemas.size(); i++) { partitionSchemas.get(i).setChanged(false); } for (int i = 0; i < clusterSchemas.size(); i++) { clusterSchemas.get(i).setChanged(false); } super.clearChanged(); } /* (non-Javadoc) * @see org.pentaho.di.trans.HasDatabaseInterface#haveConnectionsChanged() */ public boolean haveConnectionsChanged() { if (changed_databases) return true; for (int i = 0; i < nrDatabases(); i++) { DatabaseMeta ci = getDatabase(i); if (ci.hasChanged()) return true; } return false; } /** * Checks whether or not the steps have changed. * * @return True if the connections have been changed. */ public boolean haveStepsChanged() { if (changed_steps) return true; for (int i = 0; i < nrSteps(); i++) { StepMeta stepMeta = getStep(i); if (stepMeta.hasChanged()) return true; if (stepMeta.getStepPartitioningMeta() != null && stepMeta.getStepPartitioningMeta().hasChanged() ) return true; } return false; } /** * Checks whether or not any of the hops have been changed. * * @return True if a hop has been changed. */ public boolean haveHopsChanged() { if (changed_hops) return true; for (int i = 0; i < nrTransHops(); i++) { TransHopMeta hi = getTransHop(i); if (hi.hasChanged()) return true; } return false; } /** * Checks whether or not any of the notes have been changed. * * @return True if the notes have been changed. */ public boolean haveNotesChanged() { if (changed_notes) return true; for (int i = 0; i < nrNotes(); i++) { NotePadMeta ni = getNote(i); if (ni.hasChanged()) return true; } return false; } /** * Checks whether or not any of the partitioning schemas have been changed. * * @return True if the partitioning schemas have been changed. */ public boolean havePartitionSchemasChanged() { for (int i = 0; i < partitionSchemas.size(); i++) { PartitionSchema ps = partitionSchemas.get(i); if (ps.hasChanged()) return true; } return false; } /** * Checks whether or not any of the clustering schemas have been changed. * * @return True if the clustering schemas have been changed. */ public boolean haveClusterSchemasChanged() { for (int i = 0; i < clusterSchemas.size(); i++) { ClusterSchema cs = clusterSchemas.get(i); if (cs.hasChanged()) return true; } return false; } /** * Checks whether or not the transformation has changed. * * @return True if the transformation has changed. */ public boolean hasChanged() { if (super.hasChanged()) return true; if (haveConnectionsChanged()) return true; if (haveStepsChanged()) return true; if (haveHopsChanged()) return true; if (haveNotesChanged()) return true; if (havePartitionSchemasChanged()) return true; if (haveClusterSchemasChanged()) return true; return false; } /** * See if there are any loops in the transformation, starting at the indicated step. This works by looking at all * the previous steps. If you keep going backward and find the step, there is a loop. Both the informational and the * normal steps need to be checked for loops! * * @param stepMeta The step position to start looking * * @return True if a loop has been found, false if no loop is found. */ public boolean hasLoop(StepMeta stepMeta) { return hasLoop(stepMeta, null, true) || hasLoop(stepMeta, null, false); } /** * See if there are any loops in the transformation, starting at the indicated step. This works by looking at all * the previous steps. If you keep going backward and find the orginal step again, there is a loop. * * @param stepMeta The step position to start looking * @param lookup The original step when wandering around the transformation. * @param info Check the informational steps or not. * * @return True if a loop has been found, false if no loop is found. */ public boolean hasLoop(StepMeta stepMeta, StepMeta lookup, boolean info) { int nr = findNrPrevSteps(stepMeta, info); for (int i = 0; i < nr; i++) { StepMeta prevStepMeta = findPrevStep(stepMeta, i, info); if (prevStepMeta != null) { if (prevStepMeta.equals(stepMeta)) return true; if (prevStepMeta.equals(lookup)) return true; if (hasLoop(prevStepMeta, lookup == null ? stepMeta : lookup, info)) return true; } } return false; } /** * Mark all steps in the transformation as selected. * */ public void selectAll() { int i; for (i = 0; i < nrSteps(); i++) { StepMeta stepMeta = getStep(i); stepMeta.setSelected(true); } for (i = 0; i < nrNotes(); i++) { NotePadMeta ni = getNote(i); ni.setSelected(true); } setChanged(); notifyObservers("refreshGraph"); } /** * Clear the selection of all steps. * */ public void unselectAll() { int i; for (i = 0; i < nrSteps(); i++) { StepMeta stepMeta = getStep(i); stepMeta.setSelected(false); } for (i = 0; i < nrNotes(); i++) { NotePadMeta ni = getNote(i); ni.setSelected(false); } } /** * Count the number of selected steps in this transformation * * @return The number of selected steps. */ public int nrSelectedSteps() { int i, count; count = 0; for (i = 0; i < nrSteps(); i++) { StepMeta stepMeta = getStep(i); if (stepMeta.isSelected() && stepMeta.isDrawn()) count++; } return count; } /** * Get the selected step at a certain location * * @param nr The location * @return The selected step */ public StepMeta getSelectedStep(int nr) { int i, count; count = 0; for (i = 0; i < nrSteps(); i++) { StepMeta stepMeta = getStep(i); if (stepMeta.isSelected() && stepMeta.isDrawn()) { if (nr == count) return stepMeta; count++; } } return null; } /** * Count the number of selected notes in this transformation * * @return The number of selected notes. */ public int nrSelectedNotes() { int i, count; count = 0; for (i = 0; i < nrNotes(); i++) { NotePadMeta ni = getNote(i); if (ni.isSelected()) count++; } return count; } /** * Get the selected note at a certain index * * @param nr The index * @return The selected note */ public NotePadMeta getSelectedNote(int nr) { int i, count; count = 0; for (i = 0; i < nrNotes(); i++) { NotePadMeta ni = getNote(i); if (ni.isSelected()) { if (nr == count) return ni; count++; } } return null; } /** * Get an array of all the selected step and note locations * * @return The selected step and notes locations. */ public Point[] getSelectedStepLocations() { List<Point> points = new ArrayList<Point>(); for (int i = 0; i < nrSelectedSteps(); i++) { StepMeta stepMeta = getSelectedStep(i); Point p = stepMeta.getLocation(); points.add(new Point(p.x, p.y)); // explicit copy of location } return points.toArray(new Point[points.size()]); } /** * Get an array of all the selected step and note locations * * @return The selected step and notes locations. */ public Point[] getSelectedNoteLocations() { List<Point> points = new ArrayList<Point>(); for (int i = 0; i < nrSelectedNotes(); i++) { NotePadMeta ni = getSelectedNote(i); Point p = ni.getLocation(); points.add(new Point(p.x, p.y)); // explicit copy of location } return points.toArray(new Point[points.size()]); } /** * Get an array of all the selected steps * * @return An array of all the selected steps. */ public StepMeta[] getSelectedSteps() { int sels = nrSelectedSteps(); if (sels == 0) return null; StepMeta retval[] = new StepMeta[sels]; for (int i = 0; i < sels; i++) { StepMeta stepMeta = getSelectedStep(i); retval[i] = stepMeta; } return retval; } /** * Get an array of all the selected steps * * @return A list containing all the selected & drawn steps. */ public List<GUIPositionInterface> getSelectedDrawnStepsList() { List<GUIPositionInterface> list = new ArrayList<GUIPositionInterface>(); for (int i = 0; i < nrSteps(); i++) { StepMeta stepMeta = getStep(i); if (stepMeta.isDrawn() && stepMeta.isSelected()) list.add(stepMeta); } return list; } /** * Get an array of all the selected notes * * @return An array of all the selected notes. */ public NotePadMeta[] getSelectedNotes() { int sels = nrSelectedNotes(); if (sels == 0) return null; NotePadMeta retval[] = new NotePadMeta[sels]; for (int i = 0; i < sels; i++) { NotePadMeta si = getSelectedNote(i); retval[i] = si; } return retval; } /** * Get an array of all the selected step names * * @return An array of all the selected step names. */ public String[] getSelectedStepNames() { int sels = nrSelectedSteps(); if (sels == 0) return null; String retval[] = new String[sels]; for (int i = 0; i < sels; i++) { StepMeta stepMeta = getSelectedStep(i); retval[i] = stepMeta.getName(); } return retval; } /** * Get an array of the locations of an array of steps * * @param steps An array of steps * @return an array of the locations of an array of steps */ public int[] getStepIndexes(StepMeta steps[]) { int retval[] = new int[steps.length]; for (int i = 0; i < steps.length; i++) { retval[i] = indexOfStep(steps[i]); } return retval; } /** * Get an array of the locations of an array of notes * * @param notes An array of notes * @return an array of the locations of an array of notes */ public int[] getNoteIndexes(NotePadMeta notes[]) { int retval[] = new int[notes.length]; for (int i = 0; i < notes.length; i++) retval[i] = indexOfNote(notes[i]); return retval; } /** * Get the maximum number of undo operations possible * * @return The maximum number of undo operations that are allowed. */ public int getMaxUndo() { return max_undo; } /** * Sets the maximum number of undo operations that are allowed. * * @param mu The maximum number of undo operations that are allowed. */ public void setMaxUndo(int mu) { max_undo = mu; while (undo.size() > mu && undo.size() > 0) undo.remove(0); } /** * Add an undo operation to the undo list * * @param from array of objects representing the old state * @param to array of objectes representing the new state * @param pos An array of object locations * @param prev An array of points representing the old positions * @param curr An array of points representing the new positions * @param type_of_change The type of change that's being done to the transformation. * @param nextAlso indicates that the next undo operation needs to follow this one. */ public void addUndo(Object from[], Object to[], int pos[], Point prev[], Point curr[], int type_of_change, boolean nextAlso) { // First clean up after the current position. // Example: position at 3, size=5 // 012345 // ^ // remove 34 // Add 4 // 01234 while (undo.size() > undo_position + 1 && undo.size() > 0) { int last = undo.size() - 1; undo.remove(last); } TransAction ta = new TransAction(); switch (type_of_change) { case TYPE_UNDO_CHANGE: ta.setChanged(from, to, pos); break; case TYPE_UNDO_DELETE: ta.setDelete(from, pos); break; case TYPE_UNDO_NEW: ta.setNew(from, pos); break; case TYPE_UNDO_POSITION: ta.setPosition(from, pos, prev, curr); break; } ta.setNextAlso(nextAlso); undo.add(ta); undo_position++; if (undo.size() > max_undo) { undo.remove(0); undo_position--; } } /** * Get the previous undo operation and change the undo pointer * * @return The undo transaction to be performed. */ public TransAction previousUndo() { if (undo.isEmpty() || undo_position < 0) return null; // No undo left! TransAction retval = undo.get(undo_position); undo_position--; return retval; } /** * View current undo, don't change undo position * * @return The current undo transaction */ public TransAction viewThisUndo() { if (undo.isEmpty() || undo_position < 0) return null; // No undo left! TransAction retval = undo.get(undo_position); return retval; } /** * View previous undo, don't change undo position * * @return The previous undo transaction */ public TransAction viewPreviousUndo() { if (undo.isEmpty() || undo_position - 1 < 0) return null; // No undo left! TransAction retval = undo.get(undo_position - 1); return retval; } /** * Get the next undo transaction on the list. Change the undo pointer. * * @return The next undo transaction (for redo) */ public TransAction nextUndo() { int size = undo.size(); if (size == 0 || undo_position >= size - 1) return null; // no redo left... undo_position++; TransAction retval = undo.get(undo_position); return retval; } /** * Get the next undo transaction on the list. * * @return The next undo transaction (for redo) */ public TransAction viewNextUndo() { int size = undo.size(); if (size == 0 || undo_position >= size - 1) return null; // no redo left... TransAction retval = undo.get(undo_position + 1); return retval; } /** * Get the maximum size of the canvas by calculating the maximum location of a step * * @return Maximum coordinate of a step in the transformation + (100,100) for safety. */ public Point getMaximum() { int maxx = 0, maxy = 0; for (int i = 0; i < nrSteps(); i++) { StepMeta stepMeta = getStep(i); Point loc = stepMeta.getLocation(); if (loc.x > maxx) maxx = loc.x; if (loc.y > maxy) maxy = loc.y; } for (int i = 0; i < nrNotes(); i++) { NotePadMeta notePadMeta = getNote(i); Point loc = notePadMeta.getLocation(); if (loc.x + notePadMeta.width > maxx) maxx = loc.x + notePadMeta.width; if (loc.y + notePadMeta.height > maxy) maxy = loc.y + notePadMeta.height; } return new Point(maxx + 100, maxy + 100); } /** * Get the names of all the steps. * * @return An array of step names. */ public String[] getStepNames() { String retval[] = new String[nrSteps()]; for (int i = 0; i < nrSteps(); i++) retval[i] = getStep(i).getName(); return retval; } /** * Get all the steps in an array. * * @return An array of all the steps in the transformation. */ public StepMeta[] getStepsArray() { StepMeta retval[] = new StepMeta[nrSteps()]; for (int i = 0; i < nrSteps(); i++) retval[i] = getStep(i); return retval; } /** * Look in the transformation and see if we can find a step in a previous location starting somewhere. * * @param startStep The starting step * @param stepToFind The step to look for backward in the transformation * @return true if we can find the step in an earlier location in the transformation. */ public boolean findPrevious(StepMeta startStep, StepMeta stepToFind) { // Normal steps int nrPrevious = findNrPrevSteps(startStep, false); for (int i = 0; i < nrPrevious; i++) { StepMeta stepMeta = findPrevStep(startStep, i, false); if (stepMeta.equals(stepToFind)) return true; boolean found = findPrevious(stepMeta, stepToFind); // Look further back in the tree. if (found) return true; } // Info steps nrPrevious = findNrPrevSteps(startStep, true); for (int i = 0; i < nrPrevious; i++) { StepMeta stepMeta = findPrevStep(startStep, i, true); if (stepMeta.equals(stepToFind)) return true; boolean found = findPrevious(stepMeta, stepToFind); // Look further back in the tree. if (found) return true; } return false; } /** * Put the steps in alfabetical order. */ public void sortSteps() { try { Collections.sort(steps); } catch (Exception e) { LogWriter.getInstance().logError(toString(), Messages.getString("TransMeta.Exception.ErrorOfSortingSteps") + e); //$NON-NLS-1$ LogWriter.getInstance().logError(toString(), Const.getStackTracker(e)); } } public void sortHops() { Collections.sort(hops); } /** * Put the steps in a more natural order: from start to finish. For the moment, we ignore splits and joins. Splits * and joins can't be listed sequentially in any case! * */ public void sortStepsNatural() { // Loop over the steps... for (int j = 0; j < nrSteps(); j++) { // Buble sort: we need to do this several times... for (int i = 0; i < nrSteps() - 1; i++) { StepMeta one = getStep(i); StepMeta two = getStep(i + 1); if (!findPrevious(two, one)) { setStep(i + 1, one); setStep(i, two); } } } } /** * Sort the hops in a natural way: from beginning to end */ public void sortHopsNatural() { // Loop over the hops... for (int j = 0; j < nrTransHops(); j++) { // Buble sort: we need to do this several times... for (int i = 0; i < nrTransHops() - 1; i++) { TransHopMeta one = getTransHop(i); TransHopMeta two = getTransHop(i + 1); StepMeta a = two.getFromStep(); StepMeta b = one.getToStep(); if (!findPrevious(a, b) && !a.equals(b)) { setTransHop(i + 1, one); setTransHop(i, two); } } } } /** * This procedure determines the impact of the different steps in a transformation on databases, tables and field. * * @param impact An ArrayList of DatabaseImpact objects. * */ public void analyseImpact(List<DatabaseImpact> impact, ProgressMonitorListener monitor) throws KettleStepException { if (monitor != null) { monitor.beginTask(Messages.getString("TransMeta.Monitor.DeterminingImpactTask.Title"), nrSteps()); //$NON-NLS-1$ } boolean stop = false; for (int i = 0; i < nrSteps() && !stop; i++) { if (monitor != null) monitor.subTask(Messages.getString("TransMeta.Monitor.LookingAtStepTask.Title") + (i + 1) + "/" + nrSteps()); //$NON-NLS-1$ //$NON-NLS-2$ StepMeta stepMeta = getStep(i); RowMetaInterface prev = getPrevStepFields(stepMeta); StepMetaInterface stepint = stepMeta.getStepMetaInterface(); RowMetaInterface inform = null; StepMeta[] lu = getInfoStep(stepMeta); if (lu != null) { inform = getStepFields(lu); } else { inform = stepint.getTableFields(); } stepint.analyseImpact(impact, this, stepMeta, prev, null, null, inform); if (monitor != null) { monitor.worked(1); stop = monitor.isCanceled(); } } if (monitor != null) monitor.done(); } /** * Proposes an alternative stepname when the original already exists... * * @param stepname The stepname to find an alternative for.. * @return The alternative stepname. */ public String getAlternativeStepname(String stepname) { String newname = stepname; StepMeta stepMeta = findStep(newname); int nr = 1; while (stepMeta != null) { nr++; newname = stepname + " " + nr; //$NON-NLS-1$ stepMeta = findStep(newname); } return newname; } /** * Builds a list of all the SQL statements that this transformation needs in order to work properly. * * @return An ArrayList of SQLStatement objects. */ public List<SQLStatement> getSQLStatements() throws KettleStepException { return getSQLStatements(null); } /** * Builds a list of all the SQL statements that this transformation needs in order to work properly. * * @return An ArrayList of SQLStatement objects. */ public List<SQLStatement> getSQLStatements(ProgressMonitorListener monitor) throws KettleStepException { if (monitor != null) monitor.beginTask(Messages.getString("TransMeta.Monitor.GettingTheSQLForTransformationTask.Title"), nrSteps() + 1); //$NON-NLS-1$ List<SQLStatement> stats = new ArrayList<SQLStatement>(); for (int i = 0; i < nrSteps(); i++) { StepMeta stepMeta = getStep(i); if (monitor != null) monitor.subTask(Messages.getString("TransMeta.Monitor.GettingTheSQLForStepTask.Title",""+stepMeta )); //$NON-NLS-1$ //$NON-NLS-2$ RowMetaInterface prev = getPrevStepFields(stepMeta); SQLStatement sql = stepMeta.getStepMetaInterface().getSQLStatements(this, stepMeta, prev); if (sql.getSQL() != null || sql.hasError()) { stats.add(sql); } if (monitor != null) monitor.worked(1); } // Also check the sql for the logtable... if (monitor != null) monitor.subTask(Messages.getString("TransMeta.Monitor.GettingTheSQLForTransformationTask.Title2")); //$NON-NLS-1$ if (logConnection != null && logTable != null && logTable.length() > 0) { Database db = new Database(logConnection); db.shareVariablesWith(this); try { db.connect(); RowMetaInterface fields = Database.getTransLogrecordFields(false, useBatchId, logfieldUsed); String sql = db.getDDL(logTable, fields); if (sql != null && sql.length() > 0) { SQLStatement stat = new SQLStatement("<this transformation>", logConnection, sql); //$NON-NLS-1$ stats.add(stat); } } catch (KettleDatabaseException dbe) { SQLStatement stat = new SQLStatement("<this transformation>", logConnection, null); //$NON-NLS-1$ stat.setError(Messages.getString("TransMeta.SQLStatement.ErrorDesc.ErrorObtainingTransformationLogTableInfo") + dbe.getMessage()); //$NON-NLS-1$ stats.add(stat); } finally { db.disconnect(); } } if (monitor != null) monitor.worked(1); if (monitor != null) monitor.done(); return stats; } /** * Get the SQL statements, needed to run this transformation, as one String. * * @return the SQL statements needed to run this transformation. */ public String getSQLStatementsString() throws KettleStepException { String sql = ""; //$NON-NLS-1$ List<SQLStatement> stats = getSQLStatements(); for (int i = 0; i < stats.size(); i++) { SQLStatement stat = stats.get(i); if (!stat.hasError() && stat.hasSQL()) { sql += stat.getSQL(); } } return sql; } /** * Checks all the steps and fills a List of (CheckResult) remarks. * * @param remarks The remarks list to add to. * @param only_selected Check only the selected steps. * @param monitor The progress monitor to use, null if not used */ public void checkSteps(List<CheckResultInterface> remarks, boolean only_selected, ProgressMonitorListener monitor) { try { remarks.clear(); // Start with a clean slate... Map<ValueMetaInterface,String> values = new Hashtable<ValueMetaInterface,String>(); String stepnames[]; StepMeta steps[]; if (!only_selected || nrSelectedSteps() == 0) { stepnames = getStepNames(); steps = getStepsArray(); } else { stepnames = getSelectedStepNames(); steps = getSelectedSteps(); } boolean stop_checking = false; if (monitor != null) monitor.beginTask(Messages.getString("TransMeta.Monitor.VerifyingThisTransformationTask.Title"), steps.length + 2); //$NON-NLS-1$ for (int i = 0; i < steps.length && !stop_checking; i++) { if (monitor != null) monitor.subTask(Messages.getString("TransMeta.Monitor.VerifyingStepTask.Title",stepnames[i])); //$NON-NLS-1$ //$NON-NLS-2$ StepMeta stepMeta = steps[i]; int nrinfo = findNrInfoSteps(stepMeta); StepMeta[] infostep = null; if (nrinfo > 0) { infostep = getInfoStep(stepMeta); } RowMetaInterface info = null; if (infostep != null) { try { info = getStepFields(infostep); } catch (KettleStepException kse) { info = null; CheckResult cr = new CheckResult(CheckResultInterface.TYPE_RESULT_ERROR, Messages.getString("TransMeta.CheckResult.TypeResultError.ErrorOccurredGettingStepInfoFields.Description",""+stepMeta , Const.CR + kse.getMessage()), stepMeta); //$NON-NLS-1$ remarks.add(cr); } } // The previous fields from non-informative steps: RowMetaInterface prev = null; try { prev = getPrevStepFields(stepMeta); } catch (KettleStepException kse) { CheckResult cr = new CheckResult(CheckResultInterface.TYPE_RESULT_ERROR, Messages.getString("TransMeta.CheckResult.TypeResultError.ErrorOccurredGettingInputFields.Description", ""+stepMeta , Const.CR + kse.getMessage()), stepMeta); //$NON-NLS-1$ remarks.add(cr); // This is a severe error: stop checking... // Otherwise we wind up checking time & time again because nothing gets put in the database // cache, the timeout of certain databases is very long... (Oracle) stop_checking = true; } if (isStepUsedInTransHops(stepMeta)) { // Get the input & output steps! // Copy to arrays: String input[] = getPrevStepNames(stepMeta); String output[] = getNextStepNames(stepMeta); // Check step specific info... stepMeta.check(remarks, this, prev, input, output, info); // See if illegal characters etc. were used in field-names... if (prev != null) { for (int x = 0; x < prev.size(); x++) { ValueMetaInterface v = prev.getValueMeta(x); String name = v.getName(); if (name == null) values.put(v, Messages.getString("TransMeta.Value.CheckingFieldName.FieldNameIsEmpty.Description")); //$NON-NLS-1$ else if (name.indexOf(' ') >= 0) values.put(v, Messages.getString("TransMeta.Value.CheckingFieldName.FieldNameContainsSpaces.Description")); //$NON-NLS-1$ else { char list[] = new char[] { '.', ',', '-', '/', '+', '*', '\'', '\t', '"', '|', '@', '(', ')', '{', '}', '!', '^' }; for (int c = 0; c < list.length; c++) { if (name.indexOf(list[c]) >= 0) values.put(v, Messages.getString("TransMeta.Value.CheckingFieldName.FieldNameContainsUnfriendlyCodes.Description",String.valueOf(list[c]) )); //$NON-NLS-1$ //$NON-NLS-2$ } } } // Check if 2 steps with the same name are entering the step... if (prev.size() > 1) { String fieldNames[] = prev.getFieldNames(); String sortedNames[] = Const.sortStrings(fieldNames); String prevName = sortedNames[0]; for (int x = 1; x < sortedNames.length; x++) { // Checking for doubles if (prevName.equalsIgnoreCase(sortedNames[x])) { // Give a warning!! CheckResult cr = new CheckResult(CheckResultInterface.TYPE_RESULT_ERROR, Messages.getString("TransMeta.CheckResult.TypeResultWarning.HaveTheSameNameField.Description", prevName ), stepMeta); //$NON-NLS-1$ //$NON-NLS-2$ remarks.add(cr); } else { prevName = sortedNames[x]; } } } } else { CheckResult cr = new CheckResult(CheckResultInterface.TYPE_RESULT_ERROR, Messages.getString("TransMeta.CheckResult.TypeResultError.CannotFindPreviousFields.Description") + stepMeta.getName(), //$NON-NLS-1$ stepMeta); remarks.add(cr); } } else { CheckResult cr = new CheckResult(CheckResultInterface.TYPE_RESULT_WARNING, Messages.getString("TransMeta.CheckResult.TypeResultWarning.StepIsNotUsed.Description"), stepMeta); //$NON-NLS-1$ remarks.add(cr); } // Also check for mixing rows... try { checkRowMixingStatically(stepMeta, null); } catch(KettleRowException e) { CheckResult cr = new CheckResult(CheckResultInterface.TYPE_RESULT_ERROR, e.getMessage(), stepMeta); remarks.add(cr); } if (monitor != null) { monitor.worked(1); // progress bar... if (monitor.isCanceled()) stop_checking = true; } } // Also, check the logging table of the transformation... if (monitor == null || !monitor.isCanceled()) { if (monitor != null) monitor.subTask(Messages.getString("TransMeta.Monitor.CheckingTheLoggingTableTask.Title")); //$NON-NLS-1$ if (getLogConnection() != null) { Database logdb = new Database(getLogConnection()); logdb.shareVariablesWith(this); try { logdb.connect(); CheckResult cr = new CheckResult(CheckResultInterface.TYPE_RESULT_OK, Messages.getString("TransMeta.CheckResult.TypeResultOK.ConnectingWorks.Description"), //$NON-NLS-1$ null); remarks.add(cr); if (getLogTable() != null) { if (logdb.checkTableExists(getLogTable())) { cr = new CheckResult(CheckResultInterface.TYPE_RESULT_OK, Messages.getString("TransMeta.CheckResult.TypeResultOK.LoggingTableExists.Description", getLogTable() ), null); //$NON-NLS-1$ //$NON-NLS-2$ remarks.add(cr); RowMetaInterface fields = Database.getTransLogrecordFields(false, isBatchIdUsed(), isLogfieldUsed()); String sql = logdb.getDDL(getLogTable(), fields); if (sql == null || sql.length() == 0) { cr = new CheckResult(CheckResultInterface.TYPE_RESULT_OK, Messages.getString("TransMeta.CheckResult.TypeResultOK.CorrectLayout.Description"), null); //$NON-NLS-1$ remarks.add(cr); } else { cr = new CheckResult(CheckResultInterface.TYPE_RESULT_ERROR, Messages.getString("TransMeta.CheckResult.TypeResultError.LoggingTableNeedsAdjustments.Description") + Const.CR + sql, //$NON-NLS-1$ null); remarks.add(cr); } } else { cr = new CheckResult(CheckResultInterface.TYPE_RESULT_ERROR, Messages.getString("TransMeta.CheckResult.TypeResultError.LoggingTableDoesNotExist.Description"), null); //$NON-NLS-1$ remarks.add(cr); } } else { cr = new CheckResult(CheckResultInterface.TYPE_RESULT_ERROR, Messages.getString("TransMeta.CheckResult.TypeResultError.LogTableNotSpecified.Description"), null); //$NON-NLS-1$ remarks.add(cr); } } catch (KettleDatabaseException dbe) { } finally { logdb.disconnect(); } } if (monitor != null) monitor.worked(1); } if (monitor != null) monitor.subTask(Messages.getString("TransMeta.Monitor.CheckingForDatabaseUnfriendlyCharactersInFieldNamesTask.Title")); //$NON-NLS-1$ if (values.size() > 0) { for(ValueMetaInterface v:values.keySet()) { String message = values.get(v); CheckResult cr = new CheckResult(CheckResultInterface.TYPE_RESULT_WARNING, Messages.getString("TransMeta.CheckResult.TypeResultWarning.Description",v.getName() , message ,v.getOrigin() ), findStep(v.getOrigin())); //$NON-NLS-1$ remarks.add(cr); } } else { CheckResult cr = new CheckResult(CheckResultInterface.TYPE_RESULT_OK, Messages.getString("TransMeta.CheckResult.TypeResultOK.Description"), null); //$NON-NLS-1$ remarks.add(cr); } if (monitor != null) monitor.worked(1); } catch (Exception e) { LogWriter.getInstance().logError(toString(), Const.getStackTracker(e)); throw new RuntimeException(e); } } /** * @return Returns the resultRows. */ public List<RowMetaAndData> getResultRows() { return resultRows; } /** * @param resultRows The resultRows to set. */ public void setResultRows(List<RowMetaAndData> resultRows) { this.resultRows = resultRows; } /** * @return Returns the directory. */ public RepositoryDirectory getDirectory() { return directory; } /** * @param directory The directory to set. */ public void setDirectory(RepositoryDirectory directory) { this.directory = directory; setInternalKettleVariables(); } /** * @return Returns the directoryTree. * @deprecated */ public RepositoryDirectory getDirectoryTree() { return directoryTree; } /** * @param directoryTree The directoryTree to set. * @deprecated */ public void setDirectoryTree(RepositoryDirectory directoryTree) { this.directoryTree = directoryTree; } /** * @return The directory path plus the name of the transformation */ public String getPathAndName() { if (getDirectory().isRoot()) return getDirectory().getPath() + getName(); else return getDirectory().getPath() + RepositoryDirectory.DIRECTORY_SEPARATOR + getName(); } /** * @return Returns the arguments. */ public String[] getArguments() { return arguments; } /** * @param arguments The arguments to set. */ public void setArguments(String[] arguments) { this.arguments = arguments; } /** * @return Returns the counters. */ public Hashtable<String,Counter> getCounters() { return counters; } /** * @param counters The counters to set. */ public void setCounters(Hashtable<String,Counter> counters) { this.counters = counters; } /** * @return Returns the dependencies. */ public List<TransDependency> getDependencies() { return dependencies; } /** * @param dependencies The dependencies to set. */ public void setDependencies(List<TransDependency> dependencies) { this.dependencies = dependencies; } /** * @return Returns the id. */ public long getId() { return id; } /** * @param id The id to set. */ public void setId(long id) { this.id = id; } /** * @return Returns the inputStep. */ public StepMeta getInputStep() { return inputStep; } /** * @param inputStep The inputStep to set. */ public void setInputStep(StepMeta inputStep) { this.inputStep = inputStep; } /** * @return Returns the logConnection. */ public DatabaseMeta getLogConnection() { return logConnection; } /** * @param logConnection The logConnection to set. */ public void setLogConnection(DatabaseMeta logConnection) { this.logConnection = logConnection; } /** * @return Returns the logTable. */ public String getLogTable() { return logTable; } /** * @param logTable The logTable to set. */ public void setLogTable(String logTable) { this.logTable = logTable; } /** * @return Returns the maxDateConnection. */ public DatabaseMeta getMaxDateConnection() { return maxDateConnection; } /** * @param maxDateConnection The maxDateConnection to set. */ public void setMaxDateConnection(DatabaseMeta maxDateConnection) { this.maxDateConnection = maxDateConnection; } /** * @return Returns the maxDateDifference. */ public double getMaxDateDifference() { return maxDateDifference; } /** * @param maxDateDifference The maxDateDifference to set. */ public void setMaxDateDifference(double maxDateDifference) { this.maxDateDifference = maxDateDifference; } /** * @return Returns the maxDateField. */ public String getMaxDateField() { return maxDateField; } /** * @param maxDateField The maxDateField to set. */ public void setMaxDateField(String maxDateField) { this.maxDateField = maxDateField; } /** * @return Returns the maxDateOffset. */ public double getMaxDateOffset() { return maxDateOffset; } /** * @param maxDateOffset The maxDateOffset to set. */ public void setMaxDateOffset(double maxDateOffset) { this.maxDateOffset = maxDateOffset; } /** * @return Returns the maxDateTable. */ public String getMaxDateTable() { return maxDateTable; } /** * @param maxDateTable The maxDateTable to set. */ public void setMaxDateTable(String maxDateTable) { this.maxDateTable = maxDateTable; } /** * @return Returns the outputStep. */ public StepMeta getOutputStep() { return outputStep; } /** * @param outputStep The outputStep to set. */ public void setOutputStep(StepMeta outputStep) { this.outputStep = outputStep; } /** * @return Returns the readStep. */ public StepMeta getReadStep() { return readStep; } /** * @param readStep The readStep to set. */ public void setReadStep(StepMeta readStep) { this.readStep = readStep; } /** * @return Returns the updateStep. */ public StepMeta getUpdateStep() { return updateStep; } /** * @param updateStep The updateStep to set. */ public void setUpdateStep(StepMeta updateStep) { this.updateStep = updateStep; } /** * @return Returns the writeStep. */ public StepMeta getWriteStep() { return writeStep; } /** * @param writeStep The writeStep to set. */ public void setWriteStep(StepMeta writeStep) { this.writeStep = writeStep; } /** * @return Returns the sizeRowset. */ public int getSizeRowset() { return sizeRowset; } /** * @param sizeRowset The sizeRowset to set. */ public void setSizeRowset(int sizeRowset) { this.sizeRowset = sizeRowset; } /** * @return Returns the dbCache. */ public DBCache getDbCache() { return dbCache; } /** * @param dbCache The dbCache to set. */ public void setDbCache(DBCache dbCache) { this.dbCache = dbCache; } /** * @return Returns the useBatchId. */ public boolean isBatchIdUsed() { return useBatchId; } /** * @param useBatchId The useBatchId to set. */ public void setBatchIdUsed(boolean useBatchId) { this.useBatchId = useBatchId; } /** * @return Returns the logfieldUsed. */ public boolean isLogfieldUsed() { return logfieldUsed; } /** * @param logfieldUsed The logfieldUsed to set. */ public void setLogfieldUsed(boolean logfieldUsed) { this.logfieldUsed = logfieldUsed; } /** * @return Returns the createdDate. */ public Date getCreatedDate() { return createdDate; } /** * @param createdDate The createdDate to set. */ public void setCreatedDate(Date createdDate) { this.createdDate = createdDate; } /** * @param createdUser The createdUser to set. */ public void setCreatedUser(String createdUser) { this.createdUser = createdUser; } /** * @return Returns the createdUser. */ public String getCreatedUser() { return createdUser; } /** * @param modifiedDate The modifiedDate to set. */ public void setModifiedDate(Date modifiedDate) { this.modifiedDate = modifiedDate; } /** * @return Returns the modifiedDate. */ public Date getModifiedDate() { return modifiedDate; } /** * @param modifiedUser The modifiedUser to set. */ public void setModifiedUser(String modifiedUser) { this.modifiedUser = modifiedUser; } /** * @return Returns the modifiedUser. */ public String getModifiedUser() { return modifiedUser; } /** * Get the description of the transformation * * @return The description of the transformation */ public String getDescription() { return description; } /** * Set the description of the transformation. * * @param n The new description of the transformation */ public void setDescription(String n) { description = n; } /** * Set the extended description of the transformation. * * @param n The new extended description of the transformation */ public void setExtendedDescription(String n) { extended_description = n; } /** * Get the extended description of the transformation * * @return The extended description of the transformation */ public String getExtendedDescription() { return extended_description; } /** * Get the version of the transformation * * @return The version of the transformation */ public String getTransversion() { return trans_version; } /** * Set the version of the transformation. * * @param n The new version description of the transformation */ public void setTransversion(String n) { trans_version = n; } /** * Set the status of the transformation. * * @param n The new status description of the transformation */ public void setTransstatus(int n) { trans_status = n; } /** * Get the status of the transformation * * @return The status of the transformation */ public int getTransstatus() { return trans_status; } /** * @return the textual representation of the transformation: it's name. If the name has not been set, the classname * is returned. */ public String toString() { if (name != null) return name; if (filename != null) return filename; return TransMeta.class.getName(); } /** * Cancel queries opened for checking & fieldprediction */ public void cancelQueries() throws KettleDatabaseException { for (int i = 0; i < nrSteps(); i++) { getStep(i).getStepMetaInterface().cancelQueries(); } } /** * Get the arguments used by this transformation. * * @param arguments * @return A row with the used arguments in it. */ public Map<String, String> getUsedArguments(String[] arguments) { Map<String, String> transArgs = new HashMap<String, String>(); for (int i = 0; i < nrSteps(); i++) { StepMetaInterface smi = getStep(i).getStepMetaInterface(); Map<String, String> stepArgs = smi.getUsedArguments(); // Get the command line arguments that this step uses. if (stepArgs != null) { transArgs.putAll(stepArgs); } } // OK, so perhaps, we can use the arguments from a previous execution? String[] saved = Props.isInitialized() ? Props.getInstance().getLastArguments() : null; // Set the default values on it... // Also change the name to "Argument 1" .. "Argument 10" // for (String argument : transArgs.keySet()) { String value = ""; int argNr = Const.toInt(argument, -1); if (arguments!=null && argNr > 0 && argNr <= arguments.length) { value = Const.NVL(arguments[argNr-1], ""); } if (value.length()==0) // try the saved option... { if (argNr > 0 && argNr < saved.length && saved[argNr] != null) { value = saved[argNr-1]; } } transArgs.put(argument, value); } return transArgs; } /** * @return Sleep time waiting when buffer is empty, in nano-seconds */ public int getSleepTimeEmpty() { return Const.TIMEOUT_GET_MILLIS; } /** * @return Sleep time waiting when buffer is full, in nano-seconds */ public int getSleepTimeFull() { return Const.TIMEOUT_PUT_MILLIS; } /** * @param sleepTimeEmpty The sleepTimeEmpty to set. */ public void setSleepTimeEmpty(int sleepTimeEmpty) { this.sleepTimeEmpty = sleepTimeEmpty; } /** * @param sleepTimeFull The sleepTimeFull to set. */ public void setSleepTimeFull(int sleepTimeFull) { this.sleepTimeFull = sleepTimeFull; } /** * This method asks all steps in the transformation whether or not the specified database connection is used. * The connection is used in the transformation if any of the steps uses it or if it is being used to log to. * @param databaseMeta The connection to check * @return true if the connection is used in this transformation. */ public boolean isDatabaseConnectionUsed(DatabaseMeta databaseMeta) { for (int i=0;i<nrSteps();i++) { StepMeta stepMeta = getStep(i); DatabaseMeta dbs[] = stepMeta.getStepMetaInterface().getUsedDatabaseConnections(); for (int d=0;d<dbs.length;d++) { if (dbs[d].equals(databaseMeta)) return true; } } if (logConnection!=null && logConnection.equals(databaseMeta)) return true; return false; } /* public List getInputFiles() { return inputFiles; } public void setInputFiles(List inputFiles) { this.inputFiles = inputFiles; } */ /** * Get a list of all the strings used in this transformation. * * @return A list of StringSearchResult with strings used in the */ public List<StringSearchResult> getStringList(boolean searchSteps, boolean searchDatabases, boolean searchNotes, boolean includePasswords) { List<StringSearchResult> stringList = new ArrayList<StringSearchResult>(); if (searchSteps) { // Loop over all steps in the transformation and see what the used vars are... for (int i=0;i<nrSteps();i++) { StepMeta stepMeta = getStep(i); stringList.add(new StringSearchResult(stepMeta.getName(), stepMeta, this, "Step name")); if (stepMeta.getDescription()!=null) stringList.add(new StringSearchResult(stepMeta.getDescription(), stepMeta, this, "Step description")); StepMetaInterface metaInterface = stepMeta.getStepMetaInterface(); StringSearcher.findMetaData(metaInterface, 1, stringList, stepMeta, this); } } // Loop over all steps in the transformation and see what the used vars are... if (searchDatabases) { for (int i=0;i<nrDatabases();i++) { DatabaseMeta meta = getDatabase(i); stringList.add(new StringSearchResult(meta.getName(), meta, this, "Database connection name")); if (meta.getHostname()!=null) stringList.add(new StringSearchResult(meta.getHostname(), meta, this, "Database hostname")); if (meta.getDatabaseName()!=null) stringList.add(new StringSearchResult(meta.getDatabaseName(), meta, this, "Database name")); if (meta.getUsername()!=null) stringList.add(new StringSearchResult(meta.getUsername(), meta, this, "Database Username")); if (meta.getDatabaseTypeDesc()!=null) stringList.add(new StringSearchResult(meta.getDatabaseTypeDesc(), meta, this, "Database type description")); if (meta.getDatabasePortNumberString()!=null) stringList.add(new StringSearchResult(meta.getDatabasePortNumberString(), meta, this, "Database port")); if (meta.getServername()!=null) stringList.add(new StringSearchResult(meta.getServername(), meta, this, "Database server")); if ( includePasswords ) { if (meta.getPassword()!=null) stringList.add(new StringSearchResult(meta.getPassword(), meta, this, "Database password")); } } } // Loop over all steps in the transformation and see what the used vars are... if (searchNotes) { for (int i=0;i<nrNotes();i++) { NotePadMeta meta = getNote(i); if (meta.getNote()!=null) stringList.add(new StringSearchResult(meta.getNote(), meta, this, "Notepad text")); } } return stringList; } public List<StringSearchResult> getStringList(boolean searchSteps, boolean searchDatabases, boolean searchNotes) { return getStringList(searchSteps, searchDatabases, searchNotes, false); } public List<String> getUsedVariables() { // Get the list of Strings. List<StringSearchResult> stringList = getStringList(true, true, false, true); List<String> varList = new ArrayList<String>(); // Look around in the strings, see what we find... for (int i=0;i<stringList.size();i++) { StringSearchResult result = stringList.get(i); StringUtil.getUsedVariables(result.getString(), varList, false); } return varList; } /** * @return Returns the previousResult. */ public Result getPreviousResult() { return previousResult; } /** * @param previousResult The previousResult to set. */ public void setPreviousResult(Result previousResult) { this.previousResult = previousResult; } /** * @return Returns the resultFiles. */ public List<ResultFile> getResultFiles() { return resultFiles; } /** * @param resultFiles The resultFiles to set. */ public void setResultFiles(List<ResultFile> resultFiles) { this.resultFiles = resultFiles; } /** * @return the partitionSchemas */ public List<PartitionSchema> getPartitionSchemas() { return partitionSchemas; } /** * @param partitionSchemas the partitionSchemas to set */ public void setPartitionSchemas(List<PartitionSchema> partitionSchemas) { this.partitionSchemas = partitionSchemas; } /** * Get the available partition schema names. * @return */ public String[] getPartitionSchemasNames() { String names[] = new String[partitionSchemas.size()]; for (int i=0;i<names.length;i++) { names[i] = partitionSchemas.get(i).getName(); } return names; } /** * @return the feedbackShown */ public boolean isFeedbackShown() { return feedbackShown; } /** * @param feedbackShown the feedbackShown to set */ public void setFeedbackShown(boolean feedbackShown) { this.feedbackShown = feedbackShown; } /** * @return the feedbackSize */ public int getFeedbackSize() { return feedbackSize; } /** * @param feedbackSize the feedbackSize to set */ public void setFeedbackSize(int feedbackSize) { this.feedbackSize = feedbackSize; } /** * @return the usingUniqueConnections */ public boolean isUsingUniqueConnections() { return usingUniqueConnections; } /** * @param usingUniqueConnections the usingUniqueConnections to set */ public void setUsingUniqueConnections(boolean usingUniqueConnections) { this.usingUniqueConnections = usingUniqueConnections; } public List<ClusterSchema> getClusterSchemas() { return clusterSchemas; } public void setClusterSchemas(List<ClusterSchema> clusterSchemas) { this.clusterSchemas = clusterSchemas; } /** * @return The slave server strings from this cluster schema */ public String[] getClusterSchemaNames() { String[] names = new String[clusterSchemas.size()]; for (int i=0;i<names.length;i++) { names[i] = clusterSchemas.get(i).getName(); } return names; } /** * Find a partition schema using its name. * @param name The name of the partition schema to look for. * @return the partition with the specified name of null if nothing was found */ public PartitionSchema findPartitionSchema(String name) { for (int i=0;i<partitionSchemas.size();i++) { PartitionSchema schema = partitionSchemas.get(i); if (schema.getName().equalsIgnoreCase(name)) return schema; } return null; } /** * Find a clustering schema using its name * @param name The name of the clustering schema to look for. * @return the cluster schema with the specified name of null if nothing was found */ public ClusterSchema findClusterSchema(String name) { for (int i=0;i<clusterSchemas.size();i++) { ClusterSchema schema = clusterSchemas.get(i); if (schema.getName().equalsIgnoreCase(name)) return schema; } return null; } /** * Add a new partition schema to the transformation if that didn't exist yet. * Otherwise, replace it. * * @param partitionSchema The partition schema to be added. */ public void addOrReplacePartitionSchema(PartitionSchema partitionSchema) { int index = partitionSchemas.indexOf(partitionSchema); if (index<0) { partitionSchemas.add(partitionSchema); } else { PartitionSchema previous = partitionSchemas.get(index); previous.replaceMeta(partitionSchema); } setChanged(); } /** * Add a new slave server to the transformation if that didn't exist yet. * Otherwise, replace it. * * @param slaveServer The slave server to be added. */ public void addOrReplaceSlaveServer(SlaveServer slaveServer) { int index = slaveServers.indexOf(slaveServer); if (index<0) { slaveServers.add(slaveServer); } else { SlaveServer previous = slaveServers.get(index); previous.replaceMeta(slaveServer); } setChanged(); } /** * Add a new cluster schema to the transformation if that didn't exist yet. * Otherwise, replace it. * * @param clusterSchema The cluster schema to be added. */ public void addOrReplaceClusterSchema(ClusterSchema clusterSchema) { int index = clusterSchemas.indexOf(clusterSchema); if (index<0) { clusterSchemas.add(clusterSchema); } else { ClusterSchema previous = clusterSchemas.get(index); previous.replaceMeta(clusterSchema); } setChanged(); } public String getSharedObjectsFile() { return sharedObjectsFile; } public void setSharedObjectsFile(String sharedObjectsFile) { this.sharedObjectsFile = sharedObjectsFile; } public boolean saveSharedObjects() { try { // First load all the shared objects... String soFile = environmentSubstitute(sharedObjectsFile); SharedObjects sharedObjects = new SharedObjects(soFile); // Now overwrite the objects in there List<SharedObjectInterface> shared = new ArrayList<SharedObjectInterface>(); shared.addAll(databases); shared.addAll(steps); shared.addAll(partitionSchemas); shared.addAll(slaveServers); shared.addAll(clusterSchemas); // The databases connections... for (SharedObjectInterface sharedObject : shared ) { if (sharedObject.isShared()) { sharedObjects.storeObject(sharedObject); } } // Save the objects sharedObjects.saveToFile(); return true; } catch(Exception e) { log.logError(toString(), "Unable to save shared ojects: "+e.toString()); return false; } } /** * @return the usingThreadPriorityManagment */ public boolean isUsingThreadPriorityManagment() { return usingThreadPriorityManagment; } /** * @param usingThreadPriorityManagment the usingThreadPriorityManagment to set */ public void setUsingThreadPriorityManagment(boolean usingThreadPriorityManagment) { this.usingThreadPriorityManagment = usingThreadPriorityManagment; } public SlaveServer findSlaveServer(String serverString) { return SlaveServer.findSlaveServer(slaveServers, serverString); } public String[] getSlaveServerNames() { return SlaveServer.getSlaveServerNames(slaveServers); } /** * @return the slaveServers */ public List<SlaveServer> getSlaveServers() { return slaveServers; } /** * @param slaveServers the slaveServers to set */ public void setSlaveServers(List<SlaveServer> slaveServers) { this.slaveServers = slaveServers; } /** * @return the rejectedStep */ public StepMeta getRejectedStep() { return rejectedStep; } /** * @param rejectedStep the rejectedStep to set */ public void setRejectedStep(StepMeta rejectedStep) { this.rejectedStep = rejectedStep; } /** * Check a step to see if there are no multiple steps to read from. * If so, check to see if the receiving rows are all the same in layout. * We only want to ONLY use the DBCache for this to prevent GUI stalls. * * @param stepMeta the step to check * @throws KettleRowException in case we detect a row mixing violation * */ public void checkRowMixingStatically(StepMeta stepMeta, ProgressMonitorListener monitor) throws KettleRowException { int nrPrevious = findNrPrevSteps(stepMeta); if (nrPrevious>1) { RowMetaInterface referenceRow = null; // See if all previous steps send out the same rows... for (int i=0;i<nrPrevious;i++) { StepMeta previousStep = findPrevStep(stepMeta, i); try { RowMetaInterface row = getStepFields(previousStep, monitor); // Throws KettleStepException if (referenceRow==null) { referenceRow = row; } else { if ( ! stepMeta.getStepMetaInterface().excludeFromRowLayoutVerification()) { BaseStep.safeModeChecking(referenceRow, row); } } } catch(KettleStepException e) { // We ignore this one because we are in the process of designing the transformation, anything intermediate can go wrong. } } } } public void setInternalKettleVariables() { setInternalKettleVariables(variables); } public void setInternalKettleVariables(VariableSpace var) { if (!Const.isEmpty(filename)) // we have a finename that's defined. { try { FileObject fileObject = KettleVFS.getFileObject(filename); FileName fileName = fileObject.getName(); // The filename of the transformation var.setVariable(Const.INTERNAL_VARIABLE_TRANSFORMATION_FILENAME_NAME, fileName.getBaseName()); // The directory of the transformation FileName fileDir = fileName.getParent(); var.setVariable(Const.INTERNAL_VARIABLE_TRANSFORMATION_FILENAME_DIRECTORY, fileDir.getURI()); } catch(IOException e) { var.setVariable(Const.INTERNAL_VARIABLE_TRANSFORMATION_FILENAME_DIRECTORY, ""); var.setVariable(Const.INTERNAL_VARIABLE_TRANSFORMATION_FILENAME_NAME, ""); } } else { var.setVariable(Const.INTERNAL_VARIABLE_TRANSFORMATION_FILENAME_DIRECTORY, ""); var.setVariable(Const.INTERNAL_VARIABLE_TRANSFORMATION_FILENAME_NAME, ""); } // The name of the transformation // var.setVariable(Const.INTERNAL_VARIABLE_TRANSFORMATION_NAME, Const.NVL(name, "")); // The name of the directory in the repository // var.setVariable(Const.INTERNAL_VARIABLE_TRANSFORMATION_REPOSITORY_DIRECTORY, directory!=null?directory.getPath():""); // Here we don't remove the job specific parameters, as they may come in handy. // if (var.getVariable(Const.INTERNAL_VARIABLE_JOB_FILENAME_DIRECTORY)==null) { var.setVariable(Const.INTERNAL_VARIABLE_JOB_FILENAME_DIRECTORY, "Parent Job File Directory"); //$NON-NLS-1$ } if (var.getVariable(Const.INTERNAL_VARIABLE_JOB_FILENAME_NAME)==null) { var.setVariable(Const.INTERNAL_VARIABLE_JOB_FILENAME_NAME, "Parent Job Filename"); //$NON-NLS-1$ } if (var.getVariable(Const.INTERNAL_VARIABLE_JOB_NAME)==null) { var.setVariable(Const.INTERNAL_VARIABLE_JOB_NAME, "Parent Job Name"); //$NON-NLS-1$ } if (var.getVariable(Const.INTERNAL_VARIABLE_JOB_REPOSITORY_DIRECTORY)==null) { var.setVariable(Const.INTERNAL_VARIABLE_JOB_REPOSITORY_DIRECTORY, "Parent Job Repository Directory"); //$NON-NLS-1$ } } public void copyVariablesFrom(VariableSpace space) { variables.copyVariablesFrom(space); } public String environmentSubstitute(String aString) { return variables.environmentSubstitute(aString); } public String[] environmentSubstitute(String aString[]) { return variables.environmentSubstitute(aString); } public VariableSpace getParentVariableSpace() { return variables.getParentVariableSpace(); } public void setParentVariableSpace(VariableSpace parent) { variables.setParentVariableSpace(parent); } public String getVariable(String variableName, String defaultValue) { return variables.getVariable(variableName, defaultValue); } public String getVariable(String variableName) { return variables.getVariable(variableName); } public boolean getBooleanValueOfVariable(String variableName, boolean defaultValue) { if (!Const.isEmpty(variableName)) { String value = environmentSubstitute(variableName); if (!Const.isEmpty(value)) { return ValueMeta.convertStringToBoolean(value); } } return defaultValue; } public void initializeVariablesFrom(VariableSpace parent) { variables.initializeVariablesFrom(parent); } public String[] listVariables() { return variables.listVariables(); } public void setVariable(String variableName, String variableValue) { variables.setVariable(variableName, variableValue); } public void shareVariablesWith(VariableSpace space) { variables = space; } public void injectVariables(Map<String,String> prop) { variables.injectVariables(prop); } public StepMeta findMappingInputStep(String stepname) throws KettleStepException { if (!Const.isEmpty(stepname)) { StepMeta stepMeta = findStep(stepname); // TODO verify that it's a mapping input!! if (stepMeta==null) { throw new KettleStepException(Messages.getString("TransMeta.Exception.StepNameNotFound", stepname)); } return stepMeta; } else { // Find the first mapping input step that fits the bill. StepMeta stepMeta = null; for (StepMeta mappingStep : steps) { if (mappingStep.getStepID().equals("MappingInput")) { if (stepMeta==null) { stepMeta = mappingStep; } else if (stepMeta!=null) { throw new KettleStepException(Messages.getString("TransMeta.Exception.OnlyOneMappingInputStepAllowed", "2")); } } } if (stepMeta==null) { throw new KettleStepException(Messages.getString("TransMeta.Exception.OneMappingInputStepRequired")); } return stepMeta; } } public StepMeta findMappingOutputStep(String stepname) throws KettleStepException { if (!Const.isEmpty(stepname)) { StepMeta stepMeta = findStep(stepname); // TODO verify that it's a mapping output step. if (stepMeta==null) { throw new KettleStepException(Messages.getString("TransMeta.Exception.StepNameNotFound", stepname)); } return stepMeta; } else { // Find the first mapping output step that fits the bill. StepMeta stepMeta = null; for (StepMeta mappingStep : steps) { if (mappingStep.getStepID().equals("MappingOutput")) { if (stepMeta==null) { stepMeta = mappingStep; } else if (stepMeta!=null) { throw new KettleStepException(Messages.getString("TransMeta.Exception.OnlyOneMappingOutputStepAllowed", "2")); } } } if (stepMeta==null) { throw new KettleStepException(Messages.getString("TransMeta.Exception.OneMappingOutputStepRequired")); } return stepMeta; } } public List<ResourceReference> getResourceDependencies() { List<ResourceReference> resourceReferences = new ArrayList<ResourceReference>(); for (StepMeta stepMeta : steps) { resourceReferences.addAll( stepMeta.getResourceDependencies(this) ); } return resourceReferences; } public String exportResources(VariableSpace space, Map<String, ResourceDefinition> definitions, ResourceNamingInterface resourceNamingInterface) throws KettleException { try { FileObject fileObject = KettleVFS.getFileObject(getFilename()); String exportFileName = resourceNamingInterface.nameResource(fileObject.getName().getBaseName(), fileObject.getParent().getName().getPath(), "ktr"); //$NON-NLS-1$ ResourceDefinition definition = definitions.get(exportFileName); if (definition==null) { // If we do this once, it will be plenty :-) // TransMeta transMeta = (TransMeta) this.realClone(false); // transMeta.copyVariablesFrom(space); // Add used resources, modify transMeta accordingly // Go through the list of steps, etc. // These critters change the steps in the cloned TransMeta // At the end we make a new XML version of it in "exported" format... // loop over steps, databases will be exported to XML anyway. // for (StepMeta stepMeta : transMeta.getSteps()) { stepMeta.exportResources(space, definitions, resourceNamingInterface); } // Change the filename, calling this sets internal variables inside of the transformation. // transMeta.setFilename(exportFileName); // At the end, add ourselves to the map... // String transMetaContent = transMeta.getXML(); definition = new ResourceDefinition(exportFileName, transMetaContent); definitions.put(fileObject.getName().getPath(), definition); } return exportFileName; } catch (FileSystemException e) { throw new KettleException(Messages.getString("TransMeta.Exception.ErrorOpeningOrValidatingTheXMLFile", getFilename()), e); //$NON-NLS-1$ } catch (IOException e) { throw new KettleException(Messages.getString("TransMeta.Exception.ErrorOpeningOrValidatingTheXMLFile", getFilename()), e); //$NON-NLS-1$ } } /** * @return the slaveStepCopyPartitionDistribution */ public SlaveStepCopyPartitionDistribution getSlaveStepCopyPartitionDistribution() { return slaveStepCopyPartitionDistribution; } /** * @param slaveStepCopyPartitionDistribution the slaveStepCopyPartitionDistribution to set */ public void setSlaveStepCopyPartitionDistribution(SlaveStepCopyPartitionDistribution slaveStepCopyPartitionDistribution) { this.slaveStepCopyPartitionDistribution = slaveStepCopyPartitionDistribution; } public boolean isUsingAtLeastOneClusterSchema() { for (StepMeta stepMeta : steps) { if (stepMeta.getClusterSchema()!=null) return true; } return false; } public boolean isSlaveTransformation() { return slaveTransformation; } public void setSlaveTransformation(boolean slaveTransformation) { this.slaveTransformation = slaveTransformation; } /** * @return the repository */ public Repository getRepository() { return repository; } /** * @param repository the repository to set */ public void setRepository(Repository repository) { this.repository = repository; } /** * @return the capturingStepPerformanceSnapShots */ public boolean isCapturingStepPerformanceSnapShots() { return capturingStepPerformanceSnapShots; } /** * @param capturingStepPerformanceSnapShots the capturingStepPerformanceSnapShots to set */ public void setCapturingStepPerformanceSnapShots(boolean capturingStepPerformanceSnapShots) { this.capturingStepPerformanceSnapShots = capturingStepPerformanceSnapShots; } /** * @return the stepPerformanceCapturingDelay */ public long getStepPerformanceCapturingDelay() { return stepPerformanceCapturingDelay; } /** * @param stepPerformanceCapturingDelay the stepPerformanceCapturingDelay to set */ public void setStepPerformanceCapturingDelay(long stepPerformanceCapturingDelay) { this.stepPerformanceCapturingDelay = stepPerformanceCapturingDelay; } /** * @return the sharedObjects */ public SharedObjects getSharedObjects() { return sharedObjects; } /** * @param sharedObjects the sharedObjects to set */ public void setSharedObjects(SharedObjects sharedObjects) { this.sharedObjects = sharedObjects; } }
PDI-832 : caching of metadata when traversing the workflow git-svn-id: 51b39fcfd0d3a6ea7caa15377cad4af13b9d2664@6757 5fb7f6ec-07c1-534a-b4ca-9155e429e800
src/org/pentaho/di/trans/TransMeta.java
PDI-832 : caching of metadata when traversing the workflow
Java
lgpl-2.1
9bfc5fe615dd7bb8f9d5c4d6e80e63746c66be2b
0
jbosstm/jboss-transaction-spi
/* * JBoss, Home of Professional Open Source. * Copyright 2006, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * 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.jboss.tm; import javax.transaction.Status; import javax.transaction.SystemException; import javax.transaction.Transaction; import javax.transaction.TransactionManager; import javax.transaction.UserTransaction; import javax.transaction.xa.XAException; import javax.transaction.xa.XAResource; /** * TxUtils.java has utility methods for determining transaction status * in various useful ways. * * @author <a href="mailto:[email protected]">David Jencks</a> * @author <a href="mailto:[email protected]">Bill Burke</a> * @author <a href="mailto:[email protected]">Dimitris Andreadis</a> * @author [email protected] * @version $Revision: 63569 $ */ public class TxUtils { private static final String ARJUNA_REAPER_THREAD_NAME = "Transaction Reaper Worker"; /** Transaction Status Strings */ private static final String[] TxStatusStrings = { "STATUS_ACTIVE", "STATUS_MARKED_ROLLBACK", "STATUS_PREPARED", "STATUS_COMMITTED", "STATUS_ROLLEDBACK", "STATUS_UNKNOWN", "STATUS_NO_TRANSACTION", "STATUS_PREPARING", "STATUS_COMMITTING", "STATUS_ROLLING_BACK" }; /** * Do now allow instances of this class */ private TxUtils() { } public static boolean isActive(Transaction tx) { if (tx == null) return false; try { int status = tx.getStatus(); return isActive(status); } catch (SystemException error) { throw new RuntimeException(error); } } public static boolean isActive(TransactionManager tm) { try { return isActive(tm.getTransaction()); } catch (SystemException error) { throw new RuntimeException(error); } } public static boolean isActive() { return isActive(TransactionManagerLocator.locateTransactionManager()); } public static boolean isActive(UserTransaction ut) { try { int status = ut.getStatus(); return isActive(status); } catch (SystemException error) { throw new RuntimeException(error); } } public static boolean isActive(int status) { return status == Status.STATUS_ACTIVE; } public static boolean isUncommitted(Transaction tx) { if (tx == null) return false; try { int status = tx.getStatus(); return isUncommitted(status); } catch (SystemException error) { throw new RuntimeException(error); } } public static boolean isUncommitted(TransactionManager tm) { try { return isUncommitted(tm.getTransaction()); } catch (SystemException error) { throw new RuntimeException(error); } } public static boolean isUncommitted() { return isUncommitted(TransactionManagerLocator.locateTransactionManager()); } public static boolean isUncommitted(UserTransaction ut) { try { int status = ut.getStatus(); return isUncommitted(status); } catch (SystemException error) { throw new RuntimeException(error); } } public static boolean isUncommitted(int status) { return status == Status.STATUS_ACTIVE || status == Status.STATUS_MARKED_ROLLBACK; } public static boolean isCompleted(Transaction tx) { if (tx == null) return true; try { int status = tx.getStatus(); return isCompleted(status); } catch (SystemException error) { throw new RuntimeException(error); } } public static boolean isCompleted(TransactionManager tm) { try { return isCompleted(tm.getTransaction()); } catch (SystemException error) { throw new RuntimeException(error); } } public static boolean isCompleted() { return isCompleted(TransactionManagerLocator.locateTransactionManager()); } public static boolean isCompleted(UserTransaction ut) { try { int status = ut.getStatus(); return isCompleted(status); } catch (SystemException error) { throw new RuntimeException(error); } } public static boolean isCompleted(int status) { return status == Status.STATUS_COMMITTED || status == Status.STATUS_ROLLEDBACK || status == Status.STATUS_NO_TRANSACTION; } public static boolean isRollback(Transaction tx) { if (tx == null) return false; try { int status = tx.getStatus(); return isRollback(status); } catch (SystemException error) { throw new RuntimeException(error); } } public static boolean isRollback(TransactionManager tm) { try { return isRollback(tm.getTransaction()); } catch (SystemException error) { throw new RuntimeException(error); } } public static boolean isRollback() { return isRollback(TransactionManagerLocator.locateTransactionManager()); } public static boolean isRollback(UserTransaction ut) { try { int status = ut.getStatus(); return isRollback(status); } catch (SystemException error) { throw new RuntimeException(error); } } public static boolean isRollback(int status) { return status == Status.STATUS_MARKED_ROLLBACK || status == Status.STATUS_ROLLING_BACK || status == Status.STATUS_ROLLEDBACK; } /** * Converts a tx Status index to a String * * @see javax.transaction.Status * * @param status the Status index * @return status as String or "STATUS_INVALID(value)" */ public static String getStatusAsString(int status) { if (status >= Status.STATUS_ACTIVE && status <= Status.STATUS_ROLLING_BACK) { return TxStatusStrings[status]; } else { return "STATUS_INVALID(" + status + ")"; } } /** * Converts a XAResource flag to a String * * @see javax.transaction.xa.XAResource * * @param flags the flags passed in to start(), end(), recover() * @return the flags in String form */ public static String getXAResourceFlagsAsString(int flags) { if (flags == XAResource.TMNOFLAGS) { return "|TMNOFLAGS"; } else { StringBuffer sbuf = new StringBuffer(64); if ((flags & XAResource.TMONEPHASE) != 0) { sbuf.append("|TMONEPHASE"); } if ((flags & XAResource.TMJOIN) != 0) { sbuf.append("|TMJOIN"); } if ((flags & XAResource.TMRESUME) != 0) { sbuf.append("|TMRESUME"); } if ((flags & XAResource.TMSUCCESS) != 0) { sbuf.append("|TMSUCCESS"); } if ((flags & XAResource.TMFAIL) != 0) { sbuf.append("|TMFAIL"); } if ((flags & XAResource.TMSUSPEND) != 0) { sbuf.append("|TMSUSPEND"); } if ((flags & XAResource.TMSTARTRSCAN) != 0) { sbuf.append("|TMSTARTRSCAN"); } if ((flags & XAResource.TMENDRSCAN) != 0) { sbuf.append("|TMENDRSCAN"); } return sbuf.toString(); } } /** * Converts a XAException error code to a string. * * @see javax.transaction.xa.XAException * * @param errorCode an XAException error code * @return the error code in String form. * */ public static String getXAErrorCodeAsString(int errorCode) { switch (errorCode) { case XAException.XA_HEURCOM: return "XA_HEURCOM"; case XAException.XA_HEURHAZ: return "XA_HEURHAZ"; case XAException.XA_HEURMIX: return "XA_HEURMIX"; case XAException.XA_HEURRB: return "XA_HEURRB"; case XAException.XA_NOMIGRATE: return "XA_NOMIGRATE"; case XAException.XA_RBCOMMFAIL: return "XA_RBCOMMFAIL"; case XAException.XA_RBDEADLOCK: return "XA_RBDEADLOCK"; case XAException.XA_RBINTEGRITY: return "XA_RBINTEGRITY"; case XAException.XA_RBOTHER: return "XA_RBOTHER"; case XAException.XA_RBPROTO: return "XA_RBPROTO"; case XAException.XA_RBROLLBACK: return "XA_RBROLLBACK"; case XAException.XA_RBTIMEOUT: return "XA_RBTIMEOUT"; case XAException.XA_RBTRANSIENT: return "XA_RBTRANSIENT"; case XAException.XA_RDONLY: return "XA_RDONLY"; case XAException.XA_RETRY: return "XA_RETRY"; case XAException.XAER_ASYNC: return "XAER_ASYNC"; case XAException.XAER_DUPID: return "XAER_DUPID"; case XAException.XAER_INVAL: return "XAER_INVAL"; case XAException.XAER_NOTA: return "XAER_NOTA"; case XAException.XAER_OUTSIDE: return "XAER_OUTSIDE"; case XAException.XAER_PROTO: return "XAER_PROTO"; case XAException.XAER_RMERR: return "XAER_RMERR"; case XAException.XAER_RMFAIL: return "XAER_RMFAIL"; default: return "XA_UNKNOWN(" + errorCode + ")"; } } /** * Determine whether the calling thread is the transaction manager * and is processing a transaction timeout: * * @return true if the current thread was created by the TM and is handling * a transaction timeout, otherwise return false */ public static boolean isTransactionManagerTimeoutThread() { String currentThreadName = Thread.currentThread().getName(); return currentThreadName != null && currentThreadName.startsWith(ARJUNA_REAPER_THREAD_NAME); } }
src/main/java/org/jboss/tm/TxUtils.java
/* * JBoss, Home of Professional Open Source. * Copyright 2006, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * 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.jboss.tm; import javax.transaction.Status; import javax.transaction.SystemException; import javax.transaction.Transaction; import javax.transaction.TransactionManager; import javax.transaction.UserTransaction; import javax.transaction.xa.XAException; import javax.transaction.xa.XAResource; /** * TxUtils.java has utility methods for determining transaction status * in various useful ways. * * @author <a href="mailto:[email protected]">David Jencks</a> * @author <a href="mailto:[email protected]">Bill Burke</a> * @author <a href="mailto:[email protected]">Dimitris Andreadis</a> * @author [email protected] * @version $Revision: 63569 $ */ public class TxUtils { /** Transaction Status Strings */ private static final String[] TxStatusStrings = { "STATUS_ACTIVE", "STATUS_MARKED_ROLLBACK", "STATUS_PREPARED", "STATUS_COMMITTED", "STATUS_ROLLEDBACK", "STATUS_UNKNOWN", "STATUS_NO_TRANSACTION", "STATUS_PREPARING", "STATUS_COMMITTING", "STATUS_ROLLING_BACK" }; /** * Do now allow instances of this class */ private TxUtils() { } public static boolean isActive(Transaction tx) { if (tx == null) return false; try { int status = tx.getStatus(); return isActive(status); } catch (SystemException error) { throw new RuntimeException(error); } } public static boolean isActive(TransactionManager tm) { try { return isActive(tm.getTransaction()); } catch (SystemException error) { throw new RuntimeException(error); } } public static boolean isActive() { return isActive(TransactionManagerLocator.locateTransactionManager()); } public static boolean isActive(UserTransaction ut) { try { int status = ut.getStatus(); return isActive(status); } catch (SystemException error) { throw new RuntimeException(error); } } public static boolean isActive(int status) { return status == Status.STATUS_ACTIVE; } public static boolean isUncommitted(Transaction tx) { if (tx == null) return false; try { int status = tx.getStatus(); return isUncommitted(status); } catch (SystemException error) { throw new RuntimeException(error); } } public static boolean isUncommitted(TransactionManager tm) { try { return isUncommitted(tm.getTransaction()); } catch (SystemException error) { throw new RuntimeException(error); } } public static boolean isUncommitted() { return isUncommitted(TransactionManagerLocator.locateTransactionManager()); } public static boolean isUncommitted(UserTransaction ut) { try { int status = ut.getStatus(); return isUncommitted(status); } catch (SystemException error) { throw new RuntimeException(error); } } public static boolean isUncommitted(int status) { return status == Status.STATUS_ACTIVE || status == Status.STATUS_MARKED_ROLLBACK; } public static boolean isCompleted(Transaction tx) { if (tx == null) return true; try { int status = tx.getStatus(); return isCompleted(status); } catch (SystemException error) { throw new RuntimeException(error); } } public static boolean isCompleted(TransactionManager tm) { try { return isCompleted(tm.getTransaction()); } catch (SystemException error) { throw new RuntimeException(error); } } public static boolean isCompleted() { return isCompleted(TransactionManagerLocator.locateTransactionManager()); } public static boolean isCompleted(UserTransaction ut) { try { int status = ut.getStatus(); return isCompleted(status); } catch (SystemException error) { throw new RuntimeException(error); } } public static boolean isCompleted(int status) { return status == Status.STATUS_COMMITTED || status == Status.STATUS_ROLLEDBACK || status == Status.STATUS_NO_TRANSACTION; } public static boolean isRollback(Transaction tx) { if (tx == null) return false; try { int status = tx.getStatus(); return isRollback(status); } catch (SystemException error) { throw new RuntimeException(error); } } public static boolean isRollback(TransactionManager tm) { try { return isRollback(tm.getTransaction()); } catch (SystemException error) { throw new RuntimeException(error); } } public static boolean isRollback() { return isRollback(TransactionManagerLocator.locateTransactionManager()); } public static boolean isRollback(UserTransaction ut) { try { int status = ut.getStatus(); return isRollback(status); } catch (SystemException error) { throw new RuntimeException(error); } } public static boolean isRollback(int status) { return status == Status.STATUS_MARKED_ROLLBACK || status == Status.STATUS_ROLLING_BACK || status == Status.STATUS_ROLLEDBACK; } /** * Converts a tx Status index to a String * * @see javax.transaction.Status * * @param status the Status index * @return status as String or "STATUS_INVALID(value)" */ public static String getStatusAsString(int status) { if (status >= Status.STATUS_ACTIVE && status <= Status.STATUS_ROLLING_BACK) { return TxStatusStrings[status]; } else { return "STATUS_INVALID(" + status + ")"; } } /** * Converts a XAResource flag to a String * * @see javax.transaction.xa.XAResource * * @param flags the flags passed in to start(), end(), recover() * @return the flags in String form */ public static String getXAResourceFlagsAsString(int flags) { if (flags == XAResource.TMNOFLAGS) { return "|TMNOFLAGS"; } else { StringBuffer sbuf = new StringBuffer(64); if ((flags & XAResource.TMONEPHASE) != 0) { sbuf.append("|TMONEPHASE"); } if ((flags & XAResource.TMJOIN) != 0) { sbuf.append("|TMJOIN"); } if ((flags & XAResource.TMRESUME) != 0) { sbuf.append("|TMRESUME"); } if ((flags & XAResource.TMSUCCESS) != 0) { sbuf.append("|TMSUCCESS"); } if ((flags & XAResource.TMFAIL) != 0) { sbuf.append("|TMFAIL"); } if ((flags & XAResource.TMSUSPEND) != 0) { sbuf.append("|TMSUSPEND"); } if ((flags & XAResource.TMSTARTRSCAN) != 0) { sbuf.append("|TMSTARTRSCAN"); } if ((flags & XAResource.TMENDRSCAN) != 0) { sbuf.append("|TMENDRSCAN"); } return sbuf.toString(); } } /** * Converts a XAException error code to a string. * * @see javax.transaction.xa.XAException * * @param errorCode an XAException error code * @return the error code in String form. * */ public static String getXAErrorCodeAsString(int errorCode) { switch (errorCode) { case XAException.XA_HEURCOM: return "XA_HEURCOM"; case XAException.XA_HEURHAZ: return "XA_HEURHAZ"; case XAException.XA_HEURMIX: return "XA_HEURMIX"; case XAException.XA_HEURRB: return "XA_HEURRB"; case XAException.XA_NOMIGRATE: return "XA_NOMIGRATE"; case XAException.XA_RBCOMMFAIL: return "XA_RBCOMMFAIL"; case XAException.XA_RBDEADLOCK: return "XA_RBDEADLOCK"; case XAException.XA_RBINTEGRITY: return "XA_RBINTEGRITY"; case XAException.XA_RBOTHER: return "XA_RBOTHER"; case XAException.XA_RBPROTO: return "XA_RBPROTO"; case XAException.XA_RBROLLBACK: return "XA_RBROLLBACK"; case XAException.XA_RBTIMEOUT: return "XA_RBTIMEOUT"; case XAException.XA_RBTRANSIENT: return "XA_RBTRANSIENT"; case XAException.XA_RDONLY: return "XA_RDONLY"; case XAException.XA_RETRY: return "XA_RETRY"; case XAException.XAER_ASYNC: return "XAER_ASYNC"; case XAException.XAER_DUPID: return "XAER_DUPID"; case XAException.XAER_INVAL: return "XAER_INVAL"; case XAException.XAER_NOTA: return "XAER_NOTA"; case XAException.XAER_OUTSIDE: return "XAER_OUTSIDE"; case XAException.XAER_PROTO: return "XAER_PROTO"; case XAException.XAER_RMERR: return "XAER_RMERR"; case XAException.XAER_RMFAIL: return "XAER_RMFAIL"; default: return "XA_UNKNOWN(" + errorCode + ")"; } } }
[JBTM-1556] new method to determine TM reaper timeout threads
src/main/java/org/jboss/tm/TxUtils.java
[JBTM-1556] new method to determine TM reaper timeout threads
Java
apache-2.0
cc367ffcf1ae3fa143b67d691f9760788f01708d
0
Genymobile/gnirehtet,JonnyShuali/gnirehtet,Genymobile/gnirehtet,WPO-Foundation/gnirehtet,WPO-Foundation/gnirehtet,WPO-Foundation/gnirehtet,WPO-Foundation/gnirehtet,Genymobile/gnirehtet,JonnyShuali/gnirehtet
package com.genymobile.gnirehtet; import android.net.VpnService; import android.util.Log; import java.io.FileDescriptor; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InterruptedIOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; public class Forwarder { private static final ExecutorService EXECUTOR_SERVICE = Executors.newFixedThreadPool(3); private static final String TAG = Forwarder.class.getSimpleName(); private static final int BUFSIZE = 4096; private final FileDescriptor vpnFileDescriptor; private final Tunnel tunnel; private Future<?> deviceToTunnelFuture; private Future<?> tunnelToDeviceFuture; public Forwarder(VpnService vpnService, FileDescriptor vpnFileDescriptor) { this.vpnFileDescriptor = vpnFileDescriptor; tunnel = new PersistentRelayTunnel(vpnService); } public void forward() { deviceToTunnelFuture = EXECUTOR_SERVICE.submit(new Runnable() { @Override public void run() { try { forwardDeviceToTunnel(tunnel); } catch (InterruptedIOException e) { Log.d(TAG, "Device to tunnel interrupted"); } catch (IOException e) { Log.e(TAG, "Device to tunnel exception", e); } } }); tunnelToDeviceFuture = EXECUTOR_SERVICE.submit(new Runnable() { @Override public void run() { try { forwardTunnelToDevice(tunnel); } catch (InterruptedIOException e) { Log.d(TAG, "Device to tunnel interrupted"); } catch (IOException e) { Log.e(TAG, "Tunnel to device exception", e); } } }); } public void stop() { tunnel.close(); tunnelToDeviceFuture.cancel(true); deviceToTunnelFuture.cancel(true); wakeUpReadWorkaround(); } private void forwardDeviceToTunnel(Tunnel tunnel) throws IOException { Log.d(TAG, "Device to tunnel forwarding started"); FileInputStream vpnInput = new FileInputStream(vpnFileDescriptor); byte[] buffer = new byte[BUFSIZE]; while (true) { // blocking read int r = vpnInput.read(buffer); if (r == -1) { Log.d(TAG, "VPN closed"); break; } if (r > 0) { // blocking send tunnel.send(buffer, r); } } Log.d(TAG, "Device to tunnel forwarding stopped"); } private void forwardTunnelToDevice(Tunnel tunnel) throws IOException { Log.d(TAG, "Tunnel to device forwarding started"); FileOutputStream vpnOutput = new FileOutputStream(vpnFileDescriptor); IPPacketOutputStream packetOutputStream = new IPPacketOutputStream(vpnOutput); byte[] buffer = new byte[BUFSIZE]; while (true) { // blocking receive int w = tunnel.receive(buffer); if (w == -1) { Log.d(TAG, "Tunnel closed"); break; } if (w > 0) { if (GnirehtetService.VERBOSE) { Log.d(TAG, "WRITING " + w + "..." + Binary.toString(buffer, w)); } // blocking write packetOutputStream.write(buffer, 0, w); } } Log.d(TAG, "Tunnel to device forwarding stopped"); } /** * Neither vpnInterface.close() nor vpnInputStream.close() wake up a blocking * vpnInputStream.read(). * <p> * Therefore, we need to make Android send a packet to the VPN interface (here by sending a UDP * packet), so that any blocking read will be woken up. * <p> * Since the tunnel is closed at this point, it will never reach the network. */ private void wakeUpReadWorkaround() { // network actions may not be called from the main thread EXECUTOR_SERVICE.execute(new Runnable() { @Override public void run() { try { DatagramSocket socket = new DatagramSocket(); InetAddress addr = InetAddress.getByAddress(new byte[] {42, 42, 42, 42}); DatagramPacket packet = new DatagramPacket(new byte[0], 0, addr, 4242); socket.send(packet); } catch (IOException e) { // ignore } } }); } }
app/src/main/java/com/genymobile/gnirehtet/Forwarder.java
package com.genymobile.gnirehtet; import android.net.VpnService; import android.util.Log; import java.io.FileDescriptor; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InterruptedIOException; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; public class Forwarder { private static final ExecutorService EXECUTOR_SERVICE = Executors.newFixedThreadPool(3); private static final String TAG = Forwarder.class.getSimpleName(); private static final int BUFSIZE = 4096; private final FileDescriptor vpnFileDescriptor; private final Tunnel tunnel; private Future<?> deviceToTunnelFuture; private Future<?> tunnelToDeviceFuture; public Forwarder(VpnService vpnService, FileDescriptor vpnFileDescriptor) { this.vpnFileDescriptor = vpnFileDescriptor; tunnel = new PersistentRelayTunnel(vpnService); } public void forward() { deviceToTunnelFuture = EXECUTOR_SERVICE.submit(new Runnable() { @Override public void run() { try { forwardDeviceToTunnel(tunnel); } catch (InterruptedIOException e) { Log.d(TAG, "Device to tunnel interrupted"); } catch (IOException e) { Log.e(TAG, "Device to tunnel exception", e); } } }); tunnelToDeviceFuture = EXECUTOR_SERVICE.submit(new Runnable() { @Override public void run() { try { forwardTunnelToDevice(tunnel); } catch (InterruptedIOException e) { Log.d(TAG, "Device to tunnel interrupted"); } catch (IOException e) { Log.e(TAG, "Tunnel to device exception", e); } } }); } public void stop() { tunnel.close(); tunnelToDeviceFuture.cancel(true); deviceToTunnelFuture.cancel(true); wakeUpReadWorkaround(); } private void forwardDeviceToTunnel(Tunnel tunnel) throws IOException { Log.d(TAG, "Device to tunnel forwarding started"); FileInputStream vpnInput = new FileInputStream(vpnFileDescriptor); byte[] buffer = new byte[BUFSIZE]; while (true) { // blocking read int r = vpnInput.read(buffer); if (r == -1) { Log.d(TAG, "Tunnel closed"); break; } if (r > 0) { // blocking send tunnel.send(buffer, r); } } Log.d(TAG, "Device to tunnel forwarding stopped"); } private void forwardTunnelToDevice(Tunnel tunnel) throws IOException { Log.d(TAG, "Tunnel to device forwarding started"); FileOutputStream vpnOutput = new FileOutputStream(vpnFileDescriptor); IPPacketOutputStream packetOutputStream = new IPPacketOutputStream(vpnOutput); byte[] buffer = new byte[BUFSIZE]; while (true) { // blocking receive int w = tunnel.receive(buffer); if (w == -1) { Log.d(TAG, "Tunnel closed"); break; } if (w > 0) { if (GnirehtetService.VERBOSE) { Log.d(TAG, "WRITING " + w + "..." + Binary.toString(buffer, w)); } // blocking write packetOutputStream.write(buffer, 0, w); } } Log.d(TAG, "Tunnel to device forwarding stopped"); } /** * Neither vpnInterface.close() nor vpnInputStream.close() wake up a blocking * vpnInputStream.read(). * <p> * Therefore, we need to make Android send a packet to the VPN interface (here by requesting a * name resolution), so that any blocking read will be woken up. * <p> * Since the tunnel is closed at this point, it will never reach the network. */ private void wakeUpReadWorkaround() { // network actions may not be called from the main thread EXECUTOR_SERVICE.execute(new Runnable() { @Override public void run() { try { InetAddress.getByName("__fake_request__"); } catch (UnknownHostException e) { // ignore } } }); } }
Wake up blocking read() using a single UDP packet In order to wake up a blocking read() on VPN, we triggered a name resolution request, that in turn sent a UDP packet. However, a name resolution may send several UDP packets successively, because it retries if it gets no response. In that case, some UDP packets may actually be sent over the network, which is unnecessary. Instead, send a single meaningless UDP packet, just for waking up the blocking read().
app/src/main/java/com/genymobile/gnirehtet/Forwarder.java
Wake up blocking read() using a single UDP packet
Java
apache-2.0
d8f6c47c0ece6f164e7f314d1500d6d5c5dd297a
0
mgormley/pacaya,mgormley/pacaya
package edu.jhu.hltcoe; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.HashSet; import java.util.Set; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.commons.cli.PosixParser; import org.apache.log4j.BasicConfigurator; import org.apache.log4j.Logger; import org.jboss.dna.common.statistic.Stopwatch; import edu.jhu.hltcoe.data.DepTree; import edu.jhu.hltcoe.data.DepTreeNode; import edu.jhu.hltcoe.data.DepTreebank; import edu.jhu.hltcoe.data.FileMapTagReducer; import edu.jhu.hltcoe.data.Label; import edu.jhu.hltcoe.data.Ptb45To17TagReducer; import edu.jhu.hltcoe.data.Sentence; import edu.jhu.hltcoe.data.SentenceCollection; import edu.jhu.hltcoe.data.TaggedWord; import edu.jhu.hltcoe.data.VerbTreeFilter; import edu.jhu.hltcoe.data.WallDepTreeNode; import edu.jhu.hltcoe.eval.DependencyParserEvaluator; import edu.jhu.hltcoe.eval.Evaluator; import edu.jhu.hltcoe.gridsearch.dmv.BnBDmvTrainer; import edu.jhu.hltcoe.gridsearch.dmv.DmvProjector; import edu.jhu.hltcoe.gridsearch.dmv.DmvRelaxation; import edu.jhu.hltcoe.gridsearch.dmv.DmvSolution; import edu.jhu.hltcoe.gridsearch.dmv.RelaxedDmvSolution; import edu.jhu.hltcoe.model.Model; import edu.jhu.hltcoe.model.dmv.DmvDepTreeGenerator; import edu.jhu.hltcoe.model.dmv.DmvModel; import edu.jhu.hltcoe.model.dmv.SimpleStaticDmvModel; import edu.jhu.hltcoe.parse.ViterbiParser; import edu.jhu.hltcoe.train.DmvTrainCorpus; import edu.jhu.hltcoe.train.LocalBnBDmvTrainer; import edu.jhu.hltcoe.train.Trainer; import edu.jhu.hltcoe.train.TrainerFactory; import edu.jhu.hltcoe.train.LocalBnBDmvTrainer.InitSol; import edu.jhu.hltcoe.util.Command; import edu.jhu.hltcoe.util.Prng; import edu.jhu.hltcoe.util.Time; public class PipelineRunner { private static Logger log = Logger.getLogger(PipelineRunner.class); public PipelineRunner() { } public void run(CommandLine cmd) throws ParseException, IOException { // Get the training data DepTreebank trainTreebank; if (cmd.hasOption("train")) { // Read the data and (maybe) reduce size of treebank String trainPath = cmd.getOptionValue("train"); log.info("Reading train data: " + trainPath); int maxSentenceLength = Command.getOptionValue(cmd, "maxSentenceLength", Integer.MAX_VALUE); trainTreebank = getTreebank(cmd, trainPath, maxSentenceLength); } else if (cmd.hasOption("synthetic")) { String synthetic = cmd.getOptionValue("synthetic"); DmvModel trueModel; if (synthetic.equals("two")) { trueModel = SimpleStaticDmvModel.getTwoPosTagInstance(); } else if (synthetic.equals("three")) { trueModel = SimpleStaticDmvModel.getThreePosTagInstance(); } else { throw new ParseException("Unknown synthetic type: " + synthetic); } long syntheticSeed = 123454321; if (cmd.hasOption("syntheticSeed")) { syntheticSeed = Long.parseLong(cmd.getOptionValue("syntheticSeed")); } DmvDepTreeGenerator generator = new DmvDepTreeGenerator(trueModel, syntheticSeed); int maxNumSentences = Command.getOptionValue(cmd, "maxNumSentences", 100); trainTreebank = generator.getTreebank(maxNumSentences); } else { throw new ParseException("Either the option --train or --synthetic must be specified"); } // Divide into labeled and unlabeled data. double propSupervised = Command.getOptionValue(cmd, "propSupervised", 0.0); DmvTrainCorpus trainCorpus = new DmvTrainCorpus(trainTreebank, propSupervised); log.info("Number of unlabeled train sentences: " + trainCorpus.getNumUnlabeled()); log.info("Number of labeled train sentences: " + trainCorpus.getNumLabeled()); log.info("Number of train sentences: " + trainTreebank.size()); log.info("Number of train tokens: " + trainTreebank.getNumTokens()); log.info("Number of train types: " + trainTreebank.getNumTypes()); // Print train sentences to a file printSentences(cmd, trainTreebank); // Get the test data DepTreebank testTreebank = null; if (cmd.hasOption("test")) { // Read the data and (maybe) reduce size of treebank String testPath = cmd.getOptionValue("test"); log.info("Reading test data: " + testPath); int maxSentenceLengthTest = Command.getOptionValue(cmd, "maxSentenceLengthTest", Integer.MAX_VALUE); // TODO: remove this hack and replace with augmentation of the model. int numDropped = 0; Set<Label> trainTypes = trainTreebank.getTypes(); testTreebank = getTreebank(cmd, testPath, maxSentenceLengthTest); DepTreebank tmpTreebank = new DepTreebank(); for (int i=0; i<testTreebank.size(); i++) { DepTree tree = testTreebank.get(i); Set<Label> sentTypes = new HashSet<Label>(); for (DepTreeNode node : tree) { sentTypes.add(node.getLabel()); } sentTypes.remove(WallDepTreeNode.WALL_LABEL); if (trainTypes.containsAll(sentTypes)) { tmpTreebank.add(tree); } else { numDropped++; } } testTreebank = tmpTreebank; log.warn("Number of dropped test trees: " + numDropped); log.info("Number of test sentences: " + testTreebank.size()); log.info("Number of test tokens: " + testTreebank.getNumTokens()); log.info("Number of test types: " + testTreebank.getNumTypes()); testTreebank.addToAlphabet(trainTreebank.getAlphabet()); } if (cmd.hasOption("relaxOnly")) { DmvRelaxation dw = (DmvRelaxation)TrainerFactory.getTrainer(cmd, trainTreebank); dw.init1(trainCorpus); dw.init2(LocalBnBDmvTrainer.getInitSol(InitSol.UNIFORM, trainCorpus, null, null)); DmvSolution initBoundsSol = updateBounds(cmd, trainCorpus, dw, trainTreebank); Stopwatch timer = new Stopwatch(); timer.start(); RelaxedDmvSolution relaxSol = dw.solveRelaxation(); timer.stop(); log.info("relaxTime(ms): " + Time.totMs(timer)); log.info("relaxBound: " + relaxSol.getScore()); if (initBoundsSol != null) { log.info("relative: " + Math.abs(relaxSol.getScore() - initBoundsSol.getScore()) / Math.abs(initBoundsSol.getScore())); } // TODO: use add-lambda smoothing here. DmvProjector dmvProjector = new DmvProjector(trainCorpus, dw); DmvSolution projSol = dmvProjector.getProjectedDmvSolution(relaxSol); log.info("projLogLikelihood: " + projSol.getScore()); // TODO: Remove this hack. It's only to setup for getEvalParser(). // TrainerFactory.getTrainer(cmd, trainTreebank); // DependencyParserEvaluator dpEval = new DependencyParserEvaluator(TrainerFactory.getEvalParser(), trainTreebank, "train"); // dpEval.evaluate(projSol) // TODO: log.info("containsGoldSol: " + containsInitSol(dw.getBounds(), goldSol.getLogProbs())); } else { // Train the model log.info("Training model"); Trainer trainer = (Trainer)TrainerFactory.getTrainer(cmd, trainTreebank); if (trainer instanceof BnBDmvTrainer) { BnBDmvTrainer bnb = (BnBDmvTrainer) trainer; bnb.init(trainCorpus); updateBounds(cmd, trainCorpus, bnb.getRootRelaxation(), trainTreebank); bnb.train(); } else { trainer.train(trainCorpus); } Model model = trainer.getModel(); // Evaluate the model on the training data log.info("Evaluating model on train"); // Note: this parser must return the log-likelihood from parser.getParseWeight() ViterbiParser parser = TrainerFactory.getEvalParser(); Evaluator trainEval = new DependencyParserEvaluator(parser, trainTreebank, "train"); trainEval.evaluate(model); trainEval.print(); // Evaluate the model on the test data if (testTreebank != null) { log.info("Evaluating model on test"); Evaluator testEval = new DependencyParserEvaluator(parser, testTreebank, "test"); testEval.evaluate(model); testEval.print(); } // Print learned model to a file String printModel = Command.getOptionValue(cmd, "printModel", null); if (printModel != null) { BufferedWriter writer = new BufferedWriter(new FileWriter(printModel)); writer.write("Learned Model:\n"); writer.write(model.toString()); writer.close(); } } } private DepTreebank getTreebank(CommandLine cmd, String trainPath, int maxSentenceLength) { DepTreebank trainTreebank; int maxNumSentences = Command.getOptionValue(cmd, "maxNumSentences", Integer.MAX_VALUE); boolean mustContainVerb = cmd.hasOption("mustContainVerb"); String reduceTags = Command.getOptionValue(cmd, "reduceTags", "none"); trainTreebank = new DepTreebank(maxSentenceLength, maxNumSentences); if (mustContainVerb) { trainTreebank.setTreeFilter(new VerbTreeFilter()); } trainTreebank.loadPath(trainPath); if ("45to17".equals(reduceTags)) { log.info("Reducing PTB from 45 to 17 tags"); (new Ptb45To17TagReducer()).reduceTags(trainTreebank); } else if (!"none".equals(reduceTags)) { log.info("Reducing tags with file map: " + reduceTags); (new FileMapTagReducer(new File(reduceTags))).reduceTags(trainTreebank); } return trainTreebank; } private DmvSolution updateBounds(CommandLine cmd, DmvTrainCorpus trainCorpus, DmvRelaxation dw, DepTreebank trainTreebank) { if (cmd.hasOption("initBounds")) { InitSol opt = InitSol.getById(Command.getOptionValue(cmd, "initBounds", "none")); double offsetProb = Command.getOptionValue(cmd, "offsetProb", 1.0); double probOfSkipCm = Command.getOptionValue(cmd, "probOfSkipCm", 0.0); int numDoubledCms = Command.getOptionValue(cmd, "numDoubledCms", 0); DmvSolution initBoundsSol = LocalBnBDmvTrainer.getInitSol(opt, trainCorpus, dw, trainTreebank); if (numDoubledCms > 0) { // TODO: throw new RuntimeException("not implemented"); } LocalBnBDmvTrainer.setBoundsFromInitSol(dw, initBoundsSol, offsetProb, probOfSkipCm); return initBoundsSol; } return null; } private void printSentences(CommandLine cmd, DepTreebank depTreebank) throws IOException { SentenceCollection sentences = depTreebank.getSentences(); String printSentences = Command.getOptionValue(cmd, "printSentences", null); if (printSentences != null) { BufferedWriter writer = new BufferedWriter(new FileWriter(printSentences)); // TODO: improve this log.info("Printing sentences..."); writer.write("Sentences:\n"); for (Sentence sent : sentences) { StringBuilder sb = new StringBuilder(); for (Label label : sent) { if (label instanceof TaggedWord) { sb.append(((TaggedWord)label).getWord()); } else { sb.append(label.getLabel()); } sb.append(" "); } sb.append("\t"); for (Label label : sent) { if (label instanceof TaggedWord) { sb.append(((TaggedWord)label).getTag()); sb.append(" "); } } sb.append("\n"); writer.write(sb.toString()); } if (cmd.hasOption("synthetic")) { log.info("Printing trees..."); // Also print the synthetic trees writer.write("Trees:\n"); writer.write(depTreebank.toString()); } writer.close(); } } public static Options createOptions() { Options options = new Options(); // Options not specific to the model options.addOption("s", "seed", true, "Pseudo random number generator seed for everything else."); options.addOption("pm", "printModel", true, "File to which we should print the model."); options.addOption("ro", "relaxOnly", false, "Flag indicating that only a relaxation should be run"); // Options for data options.addOption("tr", "train", true, "Training data."); options.addOption("tr", "synthetic", true, "Generate synthetic training data."); options.addOption("msl", "maxSentenceLength", true, "Max sentence length."); options.addOption("mns", "maxNumSentences", true, "Max number of sentences for training."); options.addOption("vb", "mustContainVerb", false, "Filter down to sentences that contain certain verbs."); options.addOption("rd", "reduceTags", true, "Tag reduction type [none, 45to17, {a file map}]."); options.addOption("ps", "printSentences", true, "File to which we should print the sentences."); options.addOption("ss", "syntheticSeed", true, "Pseudo random number generator seed for synthetic data generation only."); options.addOption("psu", "propSupervised", true, "Proportion of labeled/supervised training data."); // Options for test data options.addOption("te", "test", true, "Test data."); options.addOption("mslt", "maxSentenceLengthTest", true, "Max sentence length for test data."); // Options to restrict the initialization options.addOption("ib", "initBounds", true, "How to initialize the bounds: [viterbi-em, gold, random, uniform, none]"); TrainerFactory.addOptions(options); return options; } private static void configureLogging() { BasicConfigurator.configure(); } public static void main(String[] args) throws IOException { configureLogging(); String usage = "java " + PipelineRunner.class.getName() + " [OPTIONS]"; CommandLineParser parser = new PosixParser(); Options options = createOptions(); String[] requiredOptions = new String[] { }; CommandLine cmd = null; final HelpFormatter formatter = new HelpFormatter(); try { cmd = parser.parse(options, args); } catch (ParseException e1) { log.error(e1.getMessage()); formatter.printHelp(usage, options, true); System.exit(1); } for (String requiredOption : requiredOptions) { if (!cmd.hasOption(requiredOption)) { formatter.printHelp(usage, options, true); System.exit(1); } } Prng.seed(Command.getOptionValue(cmd, "seed", Prng.DEFAULT_SEED)); PipelineRunner pipeline = new PipelineRunner(); try { pipeline.run(cmd); } catch (ParseException e1) { formatter.printHelp(usage, options, true); System.exit(1); } } }
src/edu/jhu/hltcoe/PipelineRunner.java
package edu.jhu.hltcoe; import java.io.BufferedWriter; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.util.HashSet; import java.util.Set; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.commons.cli.PosixParser; import org.apache.log4j.BasicConfigurator; import org.apache.log4j.Logger; import org.jboss.dna.common.statistic.Stopwatch; import edu.jhu.hltcoe.data.DepTree; import edu.jhu.hltcoe.data.DepTreeNode; import edu.jhu.hltcoe.data.DepTreebank; import edu.jhu.hltcoe.data.FileMapTagReducer; import edu.jhu.hltcoe.data.Label; import edu.jhu.hltcoe.data.Ptb45To17TagReducer; import edu.jhu.hltcoe.data.Sentence; import edu.jhu.hltcoe.data.SentenceCollection; import edu.jhu.hltcoe.data.TaggedWord; import edu.jhu.hltcoe.data.VerbTreeFilter; import edu.jhu.hltcoe.data.WallDepTreeNode; import edu.jhu.hltcoe.eval.DependencyParserEvaluator; import edu.jhu.hltcoe.eval.Evaluator; import edu.jhu.hltcoe.gridsearch.dmv.BnBDmvTrainer; import edu.jhu.hltcoe.gridsearch.dmv.DmvProjector; import edu.jhu.hltcoe.gridsearch.dmv.DmvRelaxation; import edu.jhu.hltcoe.gridsearch.dmv.DmvSolution; import edu.jhu.hltcoe.gridsearch.dmv.RelaxedDmvSolution; import edu.jhu.hltcoe.model.Model; import edu.jhu.hltcoe.model.dmv.DmvDepTreeGenerator; import edu.jhu.hltcoe.model.dmv.DmvModel; import edu.jhu.hltcoe.model.dmv.SimpleStaticDmvModel; import edu.jhu.hltcoe.parse.ViterbiParser; import edu.jhu.hltcoe.train.DmvTrainCorpus; import edu.jhu.hltcoe.train.LocalBnBDmvTrainer; import edu.jhu.hltcoe.train.Trainer; import edu.jhu.hltcoe.train.TrainerFactory; import edu.jhu.hltcoe.train.LocalBnBDmvTrainer.InitSol; import edu.jhu.hltcoe.util.Command; import edu.jhu.hltcoe.util.Prng; import edu.jhu.hltcoe.util.Time; public class PipelineRunner { private static Logger log = Logger.getLogger(PipelineRunner.class); public PipelineRunner() { } public void run(CommandLine cmd) throws ParseException, IOException { // Get the training data DepTreebank trainTreebank; if (cmd.hasOption("train")) { // Read the data and (maybe) reduce size of treebank String trainPath = cmd.getOptionValue("train"); log.info("Reading train data: " + trainPath); int maxSentenceLength = Command.getOptionValue(cmd, "maxSentenceLength", Integer.MAX_VALUE); trainTreebank = getTreebank(cmd, trainPath, maxSentenceLength); } else if (cmd.hasOption("synthetic")) { String synthetic = cmd.getOptionValue("synthetic"); DmvModel trueModel; if (synthetic.equals("two")) { trueModel = SimpleStaticDmvModel.getTwoPosTagInstance(); } else if (synthetic.equals("three")) { trueModel = SimpleStaticDmvModel.getThreePosTagInstance(); } else { throw new ParseException("Unknown synthetic type: " + synthetic); } long syntheticSeed = 123454321; if (cmd.hasOption("syntheticSeed")) { syntheticSeed = Long.parseLong(cmd.getOptionValue("syntheticSeed")); } DmvDepTreeGenerator generator = new DmvDepTreeGenerator(trueModel, syntheticSeed); int maxNumSentences = Command.getOptionValue(cmd, "maxNumSentences", 100); trainTreebank = generator.getTreebank(maxNumSentences); } else { throw new ParseException("Either the option --train or --synthetic must be specified"); } // Divide into labeled and unlabeled data. double propSupervised = Command.getOptionValue(cmd, "propSupervised", 0.0); DmvTrainCorpus trainCorpus = new DmvTrainCorpus(trainTreebank, propSupervised); log.info("Number of unlabeled train sentences: " + trainCorpus.getNumUnlabeled()); log.info("Number of labeled train sentences: " + trainCorpus.getNumLabeled()); log.info("Number of train sentences: " + trainTreebank.size()); log.info("Number of train tokens: " + trainTreebank.getNumTokens()); log.info("Number of train types: " + trainTreebank.getNumTypes()); // Print train sentences to a file printSentences(cmd, trainTreebank); // Get the test data DepTreebank testTreebank = null; if (cmd.hasOption("test")) { // Read the data and (maybe) reduce size of treebank String testPath = cmd.getOptionValue("test"); log.info("Reading test data: " + testPath); int maxSentenceLengthTest = Command.getOptionValue(cmd, "maxSentenceLengthTest", Integer.MAX_VALUE); // TODO: remove this hack and replace with augmentation of the model. int numDropped = 0; Set<Label> trainTypes = trainTreebank.getTypes(); testTreebank = getTreebank(cmd, testPath, maxSentenceLengthTest); DepTreebank tmpTreebank = new DepTreebank(); for (int i=0; i<testTreebank.size(); i++) { DepTree tree = testTreebank.get(i); Set<Label> sentTypes = new HashSet<Label>(); for (DepTreeNode node : tree) { sentTypes.add(node.getLabel()); } sentTypes.remove(WallDepTreeNode.WALL_LABEL); if (trainTypes.containsAll(sentTypes)) { tmpTreebank.add(tree); } else { numDropped++; } } testTreebank = tmpTreebank; log.warn("Number of dropped test trees: " + numDropped); log.info("Number of test sentences: " + testTreebank.size()); log.info("Number of test tokens: " + testTreebank.getNumTokens()); log.info("Number of test types: " + testTreebank.getNumTypes()); testTreebank.addToAlphabet(trainTreebank.getAlphabet()); } if (cmd.hasOption("relaxOnly")) { DmvRelaxation dw = (DmvRelaxation)TrainerFactory.getTrainer(cmd, trainTreebank); dw.init1(trainCorpus); dw.init2(LocalBnBDmvTrainer.getInitSol(InitSol.UNIFORM, trainCorpus, null, null)); DmvSolution initBoundsSol = updateBounds(cmd, trainCorpus, dw, trainTreebank); Stopwatch timer = new Stopwatch(); timer.start(); RelaxedDmvSolution relaxSol = dw.solveRelaxation(); timer.stop(); log.info("relaxTime(ms): " + Time.totMs(timer)); log.info("relaxBound: " + relaxSol.getScore()); if (initBoundsSol != null) { log.info("relative: " + Math.abs(relaxSol.getScore() - initBoundsSol.getScore()) / Math.abs(initBoundsSol.getScore())); } // TODO: use add-lambda smoothing here. DmvProjector dmvProjector = new DmvProjector(trainCorpus, dw); DmvSolution projSol = dmvProjector.getProjectedDmvSolution(relaxSol); log.info("projLogLikelihood: " + projSol.getScore()); // TODO: Remove this hack. It's only to setup for getEvalParser(). // TrainerFactory.getTrainer(cmd, trainTreebank); // DependencyParserEvaluator dpEval = new DependencyParserEvaluator(TrainerFactory.getEvalParser(), trainTreebank, "train"); // dpEval.evaluate(projSol) // TODO: log.info("containsGoldSol: " + containsInitSol(dw.getBounds(), goldSol.getLogProbs())); } else { // Train the model log.info("Training model"); Trainer trainer = (Trainer)TrainerFactory.getTrainer(cmd, trainTreebank); if (trainer instanceof BnBDmvTrainer) { BnBDmvTrainer bnb = (BnBDmvTrainer) trainer; bnb.init(trainCorpus); updateBounds(cmd, trainCorpus, bnb.getRootRelaxation(), trainTreebank); bnb.train(); } else { trainer.train(trainCorpus); } Model model = trainer.getModel(); // Evaluate the model on the training data log.info("Evaluating model on train"); // Note: this parser must return the log-likelihood from parser.getParseWeight() ViterbiParser parser = TrainerFactory.getEvalParser(); Evaluator trainEval = new DependencyParserEvaluator(parser, trainTreebank, "train"); trainEval.evaluate(model); trainEval.print(); // Evaluate the model on the test data if (testTreebank != null) { log.info("Evaluating model on test"); Evaluator testEval = new DependencyParserEvaluator(parser, testTreebank, "test"); testEval.evaluate(model); testEval.print(); } // Print learned model to a file String printModel = Command.getOptionValue(cmd, "printModel", null); if (printModel != null) { BufferedWriter writer = new BufferedWriter(new FileWriter(printModel)); writer.write("Learned Model:\n"); writer.write(model.toString()); writer.close(); } } } private DepTreebank getTreebank(CommandLine cmd, String trainPath, int maxSentenceLength) { DepTreebank trainTreebank; int maxNumSentences = Command.getOptionValue(cmd, "maxNumSentences", Integer.MAX_VALUE); boolean mustContainVerb = cmd.hasOption("mustContainVerb"); String reduceTags = Command.getOptionValue(cmd, "reduceTags", "none"); trainTreebank = new DepTreebank(maxSentenceLength, maxNumSentences); if (mustContainVerb) { trainTreebank.setTreeFilter(new VerbTreeFilter()); } trainTreebank.loadPath(trainPath); if ("45to17".equals(reduceTags)) { log.info("Reducing PTB from 45 to 17 tags"); (new Ptb45To17TagReducer()).reduceTags(trainTreebank); } else if (!"none".equals(reduceTags)) { log.info("Reducing tags with file map: " + reduceTags); (new FileMapTagReducer(new File(reduceTags))).reduceTags(trainTreebank); } return trainTreebank; } private DmvSolution updateBounds(CommandLine cmd, DmvTrainCorpus trainCorpus, DmvRelaxation dw, DepTreebank trainTreebank) { if (cmd.hasOption("initBounds")) { InitSol opt = InitSol.getById(Command.getOptionValue(cmd, "initBounds", "none")); double offsetProb = Command.getOptionValue(cmd, "offsetProb", 1.0); double probOfSkipCm = Command.getOptionValue(cmd, "probOfSkipCm", 0.0); int numDoubledCms = Command.getOptionValue(cmd, "numDoubledCms", 0); DmvSolution initBoundsSol = LocalBnBDmvTrainer.getInitSol(opt, trainCorpus, dw, trainTreebank); if (numDoubledCms > 0) { // TODO: throw new RuntimeException("not implemented"); } LocalBnBDmvTrainer.setBoundsFromInitSol(dw, initBoundsSol, offsetProb, probOfSkipCm); return initBoundsSol; } return null; } private void printSentences(CommandLine cmd, DepTreebank depTreebank) throws IOException { SentenceCollection sentences = depTreebank.getSentences(); String printSentences = Command.getOptionValue(cmd, "printSentences", null); if (printSentences != null) { BufferedWriter writer = new BufferedWriter(new FileWriter(printSentences)); // TODO: improve this log.info("Printing sentences..."); writer.write("Sentences:\n"); for (Sentence sent : sentences) { StringBuilder sb = new StringBuilder(); for (Label label : sent) { if (label instanceof TaggedWord) { sb.append(((TaggedWord)label).getWord()); } else { sb.append(label.getLabel()); } sb.append(" "); } sb.append("\t"); for (Label label : sent) { if (label instanceof TaggedWord) { sb.append(((TaggedWord)label).getTag()); sb.append(" "); } } sb.append("\n"); writer.write(sb.toString()); } if (cmd.hasOption("synthetic")) { log.info("Printing trees..."); // Also print the synthetic trees writer.write("Trees:\n"); writer.write(depTreebank.toString()); } writer.close(); } } public static Options createOptions() { Options options = new Options(); // Options not specific to the model options.addOption("s", "seed", true, "Pseudo random number generator seed for everything else."); options.addOption("pm", "printModel", true, "File to which we should print the model."); options.addOption("ro", "relaxOnly", false, "Flag indicating that only a relaxation should be run"); // Options for data options.addOption("tr", "train", true, "Training data."); options.addOption("tr", "synthetic", true, "Generate synthetic training data."); options.addOption("msl", "maxSentenceLength", true, "Max sentence length."); options.addOption("mns", "maxNumSentences", true, "Max number of sentences for training."); options.addOption("vb", "mustContainVerb", false, "Filter down to sentences that contain certain verbs."); options.addOption("rd", "reduceTags", true, "Tag reduction type [none, 45to17, {a file map}]."); options.addOption("ps", "printSentences", true, "File to which we should print the sentences."); options.addOption("ss", "syntheticSeed", true, "Pseudo random number generator seed for synthetic data generation only."); options.addOption("psu", "propSupervised", true, "Proportion of labeled/supervised training data."); // Options for test data options.addOption("te", "test", true, "Test data."); options.addOption("mslt", "maxSentenceLengthTest", true, "Max sentence length for test data."); // Options to restrict the initialization options.addOption("ib", "initBounds", true, "How to initialize the bounds: [viterbi-em, gold, random, uniform, none]"); TrainerFactory.addOptions(options); return options; } private static void configureLogging() { BasicConfigurator.configure(); } public static void main(String[] args) throws IOException { configureLogging(); String usage = "java " + PipelineRunner.class.getName() + " [OPTIONS]"; CommandLineParser parser = new PosixParser(); Options options = createOptions(); String[] requiredOptions = new String[] { }; CommandLine cmd = null; final HelpFormatter formatter = new HelpFormatter(); try { cmd = parser.parse(options, args); } catch (ParseException e1) { formatter.printHelp(usage, options, true); System.exit(1); } for (String requiredOption : requiredOptions) { if (!cmd.hasOption(requiredOption)) { formatter.printHelp(usage, options, true); System.exit(1); } } Prng.seed(Command.getOptionValue(cmd, "seed", Prng.DEFAULT_SEED)); PipelineRunner pipeline = new PipelineRunner(); try { pipeline.run(cmd); } catch (ParseException e1) { formatter.printHelp(usage, options, true); System.exit(1); } } }
Printing out usage error message. git-svn-id: e0d426d5bc6690521be35eb4f63eeada706d4dc7@436 0408881f-cb4b-4750-8b71-c94bcb194269
src/edu/jhu/hltcoe/PipelineRunner.java
Printing out usage error message.
Java
apache-2.0
6110e2bffb27a8f809c8406c189c2aff82eba017
0
traneio/future,traneio/future
package io.trane.future; import static java.util.stream.Collectors.toList; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Optional; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import java.util.stream.Stream; import org.junit.After; import org.junit.Test; public class FutureTest { private <T> T get(Future<T> future) throws CheckedFutureException { return future.get(1, TimeUnit.SECONDS); } private final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(); private final Exception ex = new TestException(); @After public void shutdownScheduler() { scheduler.shutdown(); } /*** never ***/ @Test public void never() { assertTrue(Future.never() instanceof NoFuture); } /*** apply ***/ @Test public void applyValue() throws CheckedFutureException { Integer value = 1; Future<Integer> future = Future.apply(() -> value); assertEquals(value, get(future)); } @Test(expected = ArithmeticException.class) public void applyException() throws CheckedFutureException { Future<Integer> future = Future.apply(() -> 1 / 0); get(future); } /*** value ***/ @Test public void value() throws CheckedFutureException { Integer value = 1; Future<Integer> future = Future.value(value); assertEquals(value, get(future)); } /*** exception ***/ @Test(expected = TestException.class) public void exception() throws CheckedFutureException { Future<Integer> future = Future.exception(ex); get(future); } /*** flatten ***/ @Test public void flatten() throws CheckedFutureException { Future<Future<Integer>> future = Future.value(Future.value(1)); assertEquals(get(Future.flatten(future)), get(future.flatMap(f -> f))); } /*** tailrec ***/ Future<Integer> tailrecLoop(Future<Integer> f) { return Tailrec.apply(() -> { return f.flatMap(i -> { if (i == 0) return Future.value(0); else return tailrecLoop(Future.value(i - 1)); }); }); } @Test public void tailrec() throws CheckedFutureException { assertEquals(new Integer(0), get(tailrecLoop(Future.value(20000)))); } Future<Integer> tailrecLoopDelayed(Future<Integer> f) { return Tailrec.apply(() -> { return f.flatMap(i -> { if (i == 0) return Future.value(0); else return tailrecLoopDelayed(Future.value(i - 1).delayed(1, TimeUnit.NANOSECONDS, scheduler)); }); }); } @Test public void tailrecDelayed() throws CheckedFutureException { assertEquals(new Integer(0), tailrecLoopDelayed(Future.value(20000)).get(10, TimeUnit.SECONDS)); } Future<Integer> nonTailrecLoop(Future<Integer> f) { return f.flatMap(i -> { if (i == 0) return Future.value(0); else return nonTailrecLoop(Future.value(i - 1)); }); } @Test(expected = StackOverflowError.class) public void nonTailrec() throws CheckedFutureException { assertEquals(new Integer(0), get(nonTailrecLoop(Future.value(20000)))); } Future<Integer> nonTailrecLoopDelayed(Future<Integer> f) { return f.flatMap(i -> { if (i == 0) return Future.value(0); else return nonTailrecLoop(Future.value(i - 1).delayed(1, TimeUnit.NANOSECONDS, scheduler)); }); } @Test(expected = StackOverflowError.class) public void nonTailrecDelayed() throws CheckedFutureException { assertEquals(new Integer(0), get(nonTailrecLoop(Future.value(20000)))); } /*** emptyList ***/ @Test public void emptyList() throws CheckedFutureException { Future<List<String>> future = Future.emptyList(); assertTrue(get(future).isEmpty()); } @Test(expected = UnsupportedOperationException.class) public void emptyListIsUnmodifiable() throws CheckedFutureException { Future<List<String>> future = Future.emptyList(); get(future).add("s"); } /*** emptyOptional ***/ @Test public void emptyOptional() throws CheckedFutureException { Future<Optional<String>> future = Future.emptyOptional(); assertFalse(get(future).isPresent()); } /*** collect ***/ @Test public void collectEmpty() { Future<List<String>> future = Future.collect(new ArrayList<>()); assertEquals(Future.emptyList(), future); } @Test public void collectOne() throws CheckedFutureException { Future<List<Integer>> future = Future.collect(Arrays.asList(Future.value(1))); Integer[] expected = { 1 }; assertArrayEquals(expected, get(future).toArray()); } @Test public void collectTwo() throws CheckedFutureException { Future<List<Integer>> future = Future.collect(Arrays.asList(Future.value(1), Future.value(2))); Integer[] expected = { 1, 2 }; assertArrayEquals(expected, get(future).toArray()); } @Test public void collectSatisfiedFutures() throws CheckedFutureException { Future<List<Integer>> future = Future.collect(Arrays.asList(Future.value(1), Future.value(2), Future.value(3))); Integer[] expected = { 1, 2, 3 }; assertArrayEquals(expected, get(future).toArray()); } @Test(expected = TestException.class) public void collectSatisfiedFuturesException() throws CheckedFutureException { Future<List<Integer>> future = Future .collect(Arrays.asList(Future.value(1), Future.exception(ex), Future.value(3))); get(future); } @Test public void collectPromises() throws CheckedFutureException { Promise<Integer> p1 = Promise.apply(); Promise<Integer> p2 = Promise.apply(); Promise<Integer> p3 = Promise.apply(); Future<List<Integer>> future = Future.collect(Arrays.asList(p1, p2, p3)); p1.setValue(1); p2.setValue(2); p3.setValue(3); Integer[] expected = { 1, 2, 3 }; Object[] result = get(future).toArray(); assertArrayEquals(expected, result); } @Test(expected = TestException.class) public void collectPromisesException() throws CheckedFutureException { Promise<Integer> p1 = Promise.apply(); Promise<Integer> p2 = Promise.apply(); Promise<Integer> p3 = Promise.apply(); Future<List<Integer>> future = Future.collect(Arrays.asList(p1, p2, p3)); p1.setValue(1); p2.setException(ex); p3.setValue(3); get(future); } @Test public void collectMixed() throws CheckedFutureException { Promise<Integer> p1 = Promise.apply(); Promise<Integer> p2 = Promise.apply(); Future<List<Integer>> future = Future.collect(Arrays.asList(p1, p2, Future.value(3))); p1.setValue(1); p2.setValue(2); Integer[] expected = { 1, 2, 3 }; assertArrayEquals(expected, get(future).toArray()); } @Test(expected = TestException.class) public void collectMixedException() throws CheckedFutureException { Promise<Integer> p1 = Promise.apply(); Promise<Integer> p2 = Promise.apply(); Future<List<Integer>> future = Future.collect(Arrays.asList(p1, p2, Future.value(3))); p1.setValue(1); p2.setException(ex); Integer[] expected = { 1, 2, 3 }; assertArrayEquals(expected, get(future).toArray()); } @Test public void collectConcurrentResults() throws CheckedFutureException { ExecutorService ex = Executors.newFixedThreadPool(10); try { List<Promise<Integer>> promises = Stream.generate(() -> Promise.<Integer>apply()).limit(20000).collect(toList()); AtomicBoolean start = new AtomicBoolean(); Future<List<Integer>> future = Future.collect(promises); for (Promise<Integer> p : promises) { ex.submit(() -> { while (true) { if (start.get()) break; } p.setValue(p.hashCode()); }); } start.set(true); List<Integer> expected = promises.stream().map(p -> p.hashCode()).collect(toList()); List<Integer> result = future.get(1, TimeUnit.SECONDS); assertArrayEquals(expected.toArray(), result.toArray()); } finally { ex.shutdown(); } } @Test public void collectInterrupts() { AtomicReference<Throwable> p1Intr = new AtomicReference<>(); AtomicReference<Throwable> p2Intr = new AtomicReference<>(); AtomicReference<Throwable> p3Intr = new AtomicReference<>(); Promise<Integer> p1 = Promise.apply(p1Intr::set); Promise<Integer> p2 = Promise.apply(p2Intr::set); Promise<Integer> p3 = Promise.apply(p3Intr::set); Future<List<Integer>> future = Future.collect(Arrays.asList(p1, p2, p3)); future.raise(ex); assertEquals(ex, p1Intr.get()); assertEquals(ex, p2Intr.get()); assertEquals(ex, p3Intr.get()); } @Test(expected = TimeoutException.class) public void collectTimeout() throws CheckedFutureException { Promise<Integer> p1 = Promise.apply(); Promise<Integer> p2 = Promise.apply(); Future<List<Integer>> future = Future.collect(Arrays.asList(p1, p2, Future.value(3))); p1.setValue(1); future.get(10, TimeUnit.MILLISECONDS); } /*** join ***/ @Test public void joinEmpty() { Future<Void> future = Future.join(new ArrayList<>()); assertEquals(Future.VOID, future); } @Test public void joinOne() throws CheckedFutureException { Future<Integer> f = Future.value(1); assertEquals(f.voided(), Future.join(Arrays.asList(f))); } @Test public void joinSatisfiedFutures() throws CheckedFutureException { Future<Void> future = Future.join(Arrays.asList(Future.value(1), Future.value(2))); get(future); } @Test(expected = TestException.class) public void joinSatisfiedFuturesException() throws CheckedFutureException { Future<Void> future = Future.join(Arrays.asList(Future.value(1), Future.exception(ex))); get(future); } @Test public void joinPromises() throws CheckedFutureException { Promise<Integer> p1 = Promise.apply(); Promise<Integer> p2 = Promise.apply(); Future<Void> future = Future.join(Arrays.asList(p1, p2)); p1.setValue(1); p2.setValue(2); get(future); } @Test(expected = TestException.class) public void joinPromisesException() throws CheckedFutureException { Promise<Integer> p1 = Promise.apply(); Promise<Integer> p2 = Promise.apply(); Future<Void> future = Future.join(Arrays.asList(p1, p2)); p1.setValue(1); p2.setException(ex); get(future); } @Test public void joinMixed() throws CheckedFutureException { Promise<Integer> p1 = Promise.apply(); Promise<Integer> p2 = Promise.apply(); Future<Void> future = Future.join(Arrays.asList(p1, p2, Future.value(3))); p1.setValue(1); p2.setValue(2); get(future); } @Test(expected = TestException.class) public void joinMixedException() throws CheckedFutureException { Promise<Integer> p1 = Promise.apply(); Promise<Integer> p2 = Promise.apply(); Future<Void> future = Future.join(Arrays.asList(p1, p2, Future.value(3))); p1.setValue(1); p2.setException(ex); get(future); } @Test public void joinConcurrentResults() throws CheckedFutureException { List<Promise<Integer>> promises = Stream.generate(() -> Promise.<Integer>apply()).limit(20000).collect(toList()); ExecutorService ex = Executors.newFixedThreadPool(10); try { Future<Void> future = Future.join(promises); for (Promise<Integer> p : promises) { ex.submit(() -> { p.setValue(p.hashCode()); }); } future.get(1, TimeUnit.SECONDS); } finally { ex.shutdown(); } } @Test public void joinInterrupts() { AtomicReference<Throwable> p1Intr = new AtomicReference<>(); AtomicReference<Throwable> p2Intr = new AtomicReference<>(); Promise<Integer> p1 = Promise.apply(p1Intr::set); Promise<Integer> p2 = Promise.apply(p2Intr::set); Future<Void> future = Future.join(Arrays.asList(p1, p2)); future.raise(ex); assertEquals(ex, p1Intr.get()); assertEquals(ex, p2Intr.get()); } @Test(expected = TimeoutException.class) public void joinTimeout() throws CheckedFutureException { Promise<Integer> p1 = Promise.apply(); Promise<Integer> p2 = Promise.apply(); Future<Void> future = Future.join(Arrays.asList(p1, p2, Future.value(3))); p1.setValue(1); future.get(10, TimeUnit.MILLISECONDS); } /*** selectIndex **/ @Test(expected = IllegalArgumentException.class) public void selectIndexEmpty() throws CheckedFutureException { get(Future.selectIndex(new ArrayList<>())); } @Test public void selectIndexOne() throws CheckedFutureException { Future<Integer> f = Future.selectIndex(Arrays.asList(Future.value(1))); assertEquals(new Integer(0), get(f)); } @Test public void selectIndexSatisfiedFutures() throws CheckedFutureException { Future<Integer> future = Future.selectIndex(Arrays.asList(Future.value(1), Future.value(2))); assertEquals(new Integer(0), get(future)); } @Test public void selectIndexPromises() throws CheckedFutureException { Promise<Integer> p1 = Promise.apply(); Promise<Integer> p2 = Promise.apply(); Future<Integer> future = Future.selectIndex(Arrays.asList(p1, p2)); p2.setValue(2); assertEquals(new Integer(1), get(future)); } @Test public void selectIndexPromisesException() throws CheckedFutureException { Promise<Integer> p1 = Promise.apply(); Promise<Integer> p2 = Promise.apply(); Future<Integer> future = Future.selectIndex(Arrays.asList(p1, p2)); p1.setException(new Throwable()); assertEquals(new Integer(0), get(future)); } @Test public void selectIndexMixed() throws CheckedFutureException { Promise<Integer> p1 = Promise.apply(); Promise<Integer> p2 = Promise.apply(); Future<Integer> future = Future.selectIndex(Arrays.asList(p1, p2, Future.value(3))); p1.setValue(1); p2.setValue(2); assertEquals(new Integer(2), get(future)); } @Test public void selectIndexMixedException() throws CheckedFutureException { Promise<Integer> p1 = Promise.apply(); Promise<Integer> p2 = Promise.apply(); Future<Integer> future = Future.selectIndex(Arrays.asList(p1, p2, Future.value(3))); p1.setValue(1); p2.setException(new Throwable()); assertEquals(new Integer(2), get(future)); } @Test public void selectIndexInterrupts() { AtomicReference<Throwable> p1Intr = new AtomicReference<>(); AtomicReference<Throwable> p2Intr = new AtomicReference<>(); Promise<Integer> p1 = Promise.apply(p1Intr::set); Promise<Integer> p2 = Promise.apply(p2Intr::set); Future<Integer> future = Future.selectIndex(Arrays.asList(p1, p2)); future.raise(ex); assertEquals(ex, p1Intr.get()); assertEquals(ex, p2Intr.get()); } @Test(expected = TimeoutException.class) public void selectIndexTimeout() throws CheckedFutureException { Promise<Integer> p1 = Promise.apply(); Promise<Integer> p2 = Promise.apply(); Future<Integer> future = Future.selectIndex(Arrays.asList(p1, p2)); future.get(10, TimeUnit.MILLISECONDS); } /*** firstCompletedOf **/ @Test(expected = IllegalArgumentException.class) public void firstCompletedOfEmpty() throws CheckedFutureException { get(Future.firstCompletedOf(new ArrayList<>())); } @Test public void firstCompletedOfOne() throws CheckedFutureException { Future<Integer> f = Future.firstCompletedOf(Arrays.asList(Future.value(1))); assertEquals(new Integer(1), get(f)); } @Test public void firstCompletedOfSatisfiedFutures() throws CheckedFutureException { Future<Integer> future = Future.firstCompletedOf(Arrays.asList(Future.value(1), Future.value(2))); assertEquals(new Integer(1), get(future)); } @Test public void firstCompletedOfPromises() throws CheckedFutureException { Promise<Integer> p1 = Promise.apply(); Promise<Integer> p2 = Promise.apply(); Future<Integer> future = Future.firstCompletedOf(Arrays.asList(p1, p2)); p2.setValue(2); assertEquals(new Integer(2), get(future)); } @Test(expected = TestException.class) public void firstCompletedOfPromisesException() throws CheckedFutureException { Promise<Integer> p1 = Promise.apply(); Promise<Integer> p2 = Promise.apply(); Future<Integer> future = Future.firstCompletedOf(Arrays.asList(p1, p2)); p1.setException(new TestException()); get(future); } @Test public void firstCompletedOfMixed() throws CheckedFutureException { Promise<Integer> p1 = Promise.apply(); Promise<Integer> p2 = Promise.apply(); Future<Integer> future = Future.firstCompletedOf(Arrays.asList(p1, p2, Future.value(3))); p1.setValue(1); p2.setValue(2); assertEquals(new Integer(3), get(future)); } @Test public void firstCompletedOfMixedException() throws CheckedFutureException { Promise<Integer> p1 = Promise.apply(); Promise<Integer> p2 = Promise.apply(); Future<Integer> future = Future.firstCompletedOf(Arrays.asList(p1, p2, Future.value(3))); p1.setValue(1); p2.setException(new Throwable()); assertEquals(new Integer(3), get(future)); } @Test public void firstCompletedOfInterrupts() { AtomicReference<Throwable> p1Intr = new AtomicReference<>(); AtomicReference<Throwable> p2Intr = new AtomicReference<>(); Promise<Integer> p1 = Promise.apply(p1Intr::set); Promise<Integer> p2 = Promise.apply(p2Intr::set); Future<Integer> future = Future.firstCompletedOf(Arrays.asList(p1, p2)); future.raise(ex); assertEquals(ex, p1Intr.get()); assertEquals(ex, p2Intr.get()); } @Test(expected = TimeoutException.class) public void firstCompletedOfTimeout() throws CheckedFutureException { Promise<Integer> p1 = Promise.apply(); Promise<Integer> p2 = Promise.apply(); Future<Integer> future = Future.firstCompletedOf(Arrays.asList(p1, p2)); future.get(10, TimeUnit.MILLISECONDS); } /*** whileDo ***/ @Test public void whileDo() throws CheckedFutureException { int iterations = 200000; AtomicInteger count = new AtomicInteger(iterations); AtomicInteger callCount = new AtomicInteger(0); Future<Void> future = Future.whileDo(() -> count.decrementAndGet() >= 0, () -> Future.apply(() -> callCount.incrementAndGet())); get(future); assertEquals(-1, count.get()); assertEquals(iterations, callCount.get()); } /*** within ***/ @Test(expected = TimeoutException.class) public void withinDefaultExceptionFailure() throws CheckedFutureException { Future<Integer> f = (Promise.<Integer>apply()).within(1, TimeUnit.MILLISECONDS, scheduler); get(f); } @Test public void withinDefaultExceptionSuccess() throws CheckedFutureException { Promise<Integer> p = Promise.<Integer>apply(); Future<Integer> f = p.within(10, TimeUnit.MILLISECONDS, scheduler); p.setValue(1); assertEquals(new Integer(1), get(f)); } }
future-java/src/test/java/io/trane/future/FutureTest.java
package io.trane.future; import static java.util.stream.Collectors.toList; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Optional; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import java.util.stream.Stream; import org.junit.After; import org.junit.Test; public class FutureTest { private <T> T get(Future<T> future) throws CheckedFutureException { return future.get(1, TimeUnit.SECONDS); } private final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(); private final Exception ex = new TestException(); @After public void shutdownScheduler() { scheduler.shutdown(); } /*** never ***/ @Test public void never() { assertTrue(Future.never() instanceof NoFuture); } /*** apply ***/ @Test public void applyValue() throws CheckedFutureException { Integer value = 1; Future<Integer> future = Future.apply(() -> value); assertEquals(value, get(future)); } @Test(expected = ArithmeticException.class) public void applyException() throws CheckedFutureException { Future<Integer> future = Future.apply(() -> 1 / 0); get(future); } /*** value ***/ @Test public void value() throws CheckedFutureException { Integer value = 1; Future<Integer> future = Future.value(value); assertEquals(value, get(future)); } /*** exception ***/ @Test(expected = TestException.class) public void exception() throws CheckedFutureException { Future<Integer> future = Future.exception(ex); get(future); } /*** flatten ***/ @Test public void flatten() throws CheckedFutureException { Future<Future<Integer>> future = Future.value(Future.value(1)); assertEquals(get(Future.flatten(future)), get(future.flatMap(f -> f))); } /*** tailrec ***/ Future<Integer> tailrecLoop(Future<Integer> f) { return Tailrec.apply(() -> { return f.flatMap(i -> { if (i == 0) return Future.value(0); else return tailrecLoop(Future.value(i - 1)); }); }); } @Test public void tailrec() throws CheckedFutureException { assertEquals(new Integer(0), get(tailrecLoop(Future.value(20000)))); } Future<Integer> tailrecLoopDelayed(Future<Integer> f) { return Tailrec.apply(() -> { return f.flatMap(i -> { if (i == 0) return Future.value(0); else return tailrecLoopDelayed(Future.value(i - 1).delayed(1, TimeUnit.NANOSECONDS, scheduler)); }); }); } @Test public void tailrecDelayed() throws CheckedFutureException { assertEquals(new Integer(0), tailrecLoopDelayed(Future.value(20000)).get(10, TimeUnit.SECONDS)); } Future<Integer> nonTailrecLoop(Future<Integer> f) { return f.flatMap(i -> { if (i == 0) return Future.value(0); else return nonTailrecLoop(Future.value(i - 1)); }); } @Test(expected = StackOverflowError.class) public void nonTailrec() throws CheckedFutureException { assertEquals(new Integer(0), get(nonTailrecLoop(Future.value(20000)))); } Future<Integer> nonTailrecLoopDelayed(Future<Integer> f) { return f.flatMap(i -> { if (i == 0) return Future.value(0); else return nonTailrecLoop(Future.value(i - 1).delayed(1, TimeUnit.NANOSECONDS, scheduler)); }); } @Test(expected = StackOverflowError.class) public void nonTailrecDelayed() throws CheckedFutureException { assertEquals(new Integer(0), get(nonTailrecLoop(Future.value(20000)))); } /*** emptyList ***/ @Test public void emptyList() throws CheckedFutureException { Future<List<String>> future = Future.emptyList(); assertTrue(get(future).isEmpty()); } @Test(expected = UnsupportedOperationException.class) public void emptyListIsUnmodifiable() throws CheckedFutureException { Future<List<String>> future = Future.emptyList(); get(future).add("s"); } /*** emptyOptional ***/ @Test public void emptyOptional() throws CheckedFutureException { Future<Optional<String>> future = Future.emptyOptional(); assertFalse(get(future).isPresent()); } /*** collect ***/ @Test public void collectEmpty() { Future<List<String>> future = Future.collect(new ArrayList<>()); assertEquals(Future.emptyList(), future); } @Test public void collectOne() throws CheckedFutureException { Future<List<Integer>> future = Future.collect(Arrays.asList(Future.value(1))); Integer[] expected = { 1 }; assertArrayEquals(expected, get(future).toArray()); } @Test public void collectTwo() throws CheckedFutureException { Future<List<Integer>> future = Future.collect(Arrays.asList(Future.value(1), Future.value(2))); Integer[] expected = { 1, 2 }; assertArrayEquals(expected, get(future).toArray()); } @Test public void collectSatisfiedFutures() throws CheckedFutureException { Future<List<Integer>> future = Future.collect(Arrays.asList(Future.value(1), Future.value(2), Future.value(3))); Integer[] expected = { 1, 2, 3 }; assertArrayEquals(expected, get(future).toArray()); } @Test(expected = TestException.class) public void collectSatisfiedFuturesException() throws CheckedFutureException { Future<List<Integer>> future = Future .collect(Arrays.asList(Future.value(1), Future.exception(ex), Future.value(3))); get(future); } @Test public void collectPromises() throws CheckedFutureException { Promise<Integer> p1 = Promise.apply(); Promise<Integer> p2 = Promise.apply(); Promise<Integer> p3 = Promise.apply(); Future<List<Integer>> future = Future.collect(Arrays.asList(p1, p2, p3)); p1.setValue(1); p2.setValue(2); p3.setValue(3); Integer[] expected = { 1, 2, 3 }; Object[] result = get(future).toArray(); assertArrayEquals(expected, result); } @Test(expected = TestException.class) public void collectPromisesException() throws CheckedFutureException { Promise<Integer> p1 = Promise.apply(); Promise<Integer> p2 = Promise.apply(); Promise<Integer> p3 = Promise.apply(); Future<List<Integer>> future = Future.collect(Arrays.asList(p1, p2, p3)); p1.setValue(1); p2.setException(ex); p3.setValue(3); get(future); } @Test public void collectMixed() throws CheckedFutureException { Promise<Integer> p1 = Promise.apply(); Promise<Integer> p2 = Promise.apply(); Future<List<Integer>> future = Future.collect(Arrays.asList(p1, p2, Future.value(3))); p1.setValue(1); p2.setValue(2); Integer[] expected = { 1, 2, 3 }; assertArrayEquals(expected, get(future).toArray()); } @Test(expected = TestException.class) public void collectMixedException() throws CheckedFutureException { Promise<Integer> p1 = Promise.apply(); Promise<Integer> p2 = Promise.apply(); Future<List<Integer>> future = Future.collect(Arrays.asList(p1, p2, Future.value(3))); p1.setValue(1); p2.setException(ex); Integer[] expected = { 1, 2, 3 }; assertArrayEquals(expected, get(future).toArray()); } @Test public void collectConcurrentResults() throws CheckedFutureException { ExecutorService ex = Executors.newFixedThreadPool(10); try { List<Promise<Integer>> promises = Stream.generate(() -> Promise.<Integer>apply()).limit(20000).collect(toList()); AtomicBoolean start = new AtomicBoolean(); Future<List<Integer>> future = Future.collect(promises); for (Promise<Integer> p : promises) { ex.submit(() -> { while (true) { if (start.get()) break; } p.setValue(p.hashCode()); }); } start.set(true); List<Integer> expected = promises.stream().map(p -> p.hashCode()).collect(toList()); List<Integer> result = future.get(100, TimeUnit.MILLISECONDS); assertArrayEquals(expected.toArray(), result.toArray()); } finally { ex.shutdown(); } } @Test public void collectInterrupts() { AtomicReference<Throwable> p1Intr = new AtomicReference<>(); AtomicReference<Throwable> p2Intr = new AtomicReference<>(); AtomicReference<Throwable> p3Intr = new AtomicReference<>(); Promise<Integer> p1 = Promise.apply(p1Intr::set); Promise<Integer> p2 = Promise.apply(p2Intr::set); Promise<Integer> p3 = Promise.apply(p3Intr::set); Future<List<Integer>> future = Future.collect(Arrays.asList(p1, p2, p3)); future.raise(ex); assertEquals(ex, p1Intr.get()); assertEquals(ex, p2Intr.get()); assertEquals(ex, p3Intr.get()); } @Test(expected = TimeoutException.class) public void collectTimeout() throws CheckedFutureException { Promise<Integer> p1 = Promise.apply(); Promise<Integer> p2 = Promise.apply(); Future<List<Integer>> future = Future.collect(Arrays.asList(p1, p2, Future.value(3))); p1.setValue(1); future.get(10, TimeUnit.MILLISECONDS); } /*** join ***/ @Test public void joinEmpty() { Future<Void> future = Future.join(new ArrayList<>()); assertEquals(Future.VOID, future); } @Test public void joinOne() throws CheckedFutureException { Future<Integer> f = Future.value(1); assertEquals(f.voided(), Future.join(Arrays.asList(f))); } @Test public void joinSatisfiedFutures() throws CheckedFutureException { Future<Void> future = Future.join(Arrays.asList(Future.value(1), Future.value(2))); get(future); } @Test(expected = TestException.class) public void joinSatisfiedFuturesException() throws CheckedFutureException { Future<Void> future = Future.join(Arrays.asList(Future.value(1), Future.exception(ex))); get(future); } @Test public void joinPromises() throws CheckedFutureException { Promise<Integer> p1 = Promise.apply(); Promise<Integer> p2 = Promise.apply(); Future<Void> future = Future.join(Arrays.asList(p1, p2)); p1.setValue(1); p2.setValue(2); get(future); } @Test(expected = TestException.class) public void joinPromisesException() throws CheckedFutureException { Promise<Integer> p1 = Promise.apply(); Promise<Integer> p2 = Promise.apply(); Future<Void> future = Future.join(Arrays.asList(p1, p2)); p1.setValue(1); p2.setException(ex); get(future); } @Test public void joinMixed() throws CheckedFutureException { Promise<Integer> p1 = Promise.apply(); Promise<Integer> p2 = Promise.apply(); Future<Void> future = Future.join(Arrays.asList(p1, p2, Future.value(3))); p1.setValue(1); p2.setValue(2); get(future); } @Test(expected = TestException.class) public void joinMixedException() throws CheckedFutureException { Promise<Integer> p1 = Promise.apply(); Promise<Integer> p2 = Promise.apply(); Future<Void> future = Future.join(Arrays.asList(p1, p2, Future.value(3))); p1.setValue(1); p2.setException(ex); get(future); } @Test public void joinConcurrentResults() throws CheckedFutureException { List<Promise<Integer>> promises = Stream.generate(() -> Promise.<Integer>apply()).limit(20000).collect(toList()); ExecutorService ex = Executors.newFixedThreadPool(10); try { Future<Void> future = Future.join(promises); for (Promise<Integer> p : promises) { ex.submit(() -> { p.setValue(p.hashCode()); }); } future.get(1, TimeUnit.SECONDS); } finally { ex.shutdown(); } } @Test public void joinInterrupts() { AtomicReference<Throwable> p1Intr = new AtomicReference<>(); AtomicReference<Throwable> p2Intr = new AtomicReference<>(); Promise<Integer> p1 = Promise.apply(p1Intr::set); Promise<Integer> p2 = Promise.apply(p2Intr::set); Future<Void> future = Future.join(Arrays.asList(p1, p2)); future.raise(ex); assertEquals(ex, p1Intr.get()); assertEquals(ex, p2Intr.get()); } @Test(expected = TimeoutException.class) public void joinTimeout() throws CheckedFutureException { Promise<Integer> p1 = Promise.apply(); Promise<Integer> p2 = Promise.apply(); Future<Void> future = Future.join(Arrays.asList(p1, p2, Future.value(3))); p1.setValue(1); future.get(10, TimeUnit.MILLISECONDS); } /*** selectIndex **/ @Test(expected = IllegalArgumentException.class) public void selectIndexEmpty() throws CheckedFutureException { get(Future.selectIndex(new ArrayList<>())); } @Test public void selectIndexOne() throws CheckedFutureException { Future<Integer> f = Future.selectIndex(Arrays.asList(Future.value(1))); assertEquals(new Integer(0), get(f)); } @Test public void selectIndexSatisfiedFutures() throws CheckedFutureException { Future<Integer> future = Future.selectIndex(Arrays.asList(Future.value(1), Future.value(2))); assertEquals(new Integer(0), get(future)); } @Test public void selectIndexPromises() throws CheckedFutureException { Promise<Integer> p1 = Promise.apply(); Promise<Integer> p2 = Promise.apply(); Future<Integer> future = Future.selectIndex(Arrays.asList(p1, p2)); p2.setValue(2); assertEquals(new Integer(1), get(future)); } @Test public void selectIndexPromisesException() throws CheckedFutureException { Promise<Integer> p1 = Promise.apply(); Promise<Integer> p2 = Promise.apply(); Future<Integer> future = Future.selectIndex(Arrays.asList(p1, p2)); p1.setException(new Throwable()); assertEquals(new Integer(0), get(future)); } @Test public void selectIndexMixed() throws CheckedFutureException { Promise<Integer> p1 = Promise.apply(); Promise<Integer> p2 = Promise.apply(); Future<Integer> future = Future.selectIndex(Arrays.asList(p1, p2, Future.value(3))); p1.setValue(1); p2.setValue(2); assertEquals(new Integer(2), get(future)); } @Test public void selectIndexMixedException() throws CheckedFutureException { Promise<Integer> p1 = Promise.apply(); Promise<Integer> p2 = Promise.apply(); Future<Integer> future = Future.selectIndex(Arrays.asList(p1, p2, Future.value(3))); p1.setValue(1); p2.setException(new Throwable()); assertEquals(new Integer(2), get(future)); } @Test public void selectIndexInterrupts() { AtomicReference<Throwable> p1Intr = new AtomicReference<>(); AtomicReference<Throwable> p2Intr = new AtomicReference<>(); Promise<Integer> p1 = Promise.apply(p1Intr::set); Promise<Integer> p2 = Promise.apply(p2Intr::set); Future<Integer> future = Future.selectIndex(Arrays.asList(p1, p2)); future.raise(ex); assertEquals(ex, p1Intr.get()); assertEquals(ex, p2Intr.get()); } @Test(expected = TimeoutException.class) public void selectIndexTimeout() throws CheckedFutureException { Promise<Integer> p1 = Promise.apply(); Promise<Integer> p2 = Promise.apply(); Future<Integer> future = Future.selectIndex(Arrays.asList(p1, p2)); future.get(10, TimeUnit.MILLISECONDS); } /*** firstCompletedOf **/ @Test(expected = IllegalArgumentException.class) public void firstCompletedOfEmpty() throws CheckedFutureException { get(Future.firstCompletedOf(new ArrayList<>())); } @Test public void firstCompletedOfOne() throws CheckedFutureException { Future<Integer> f = Future.firstCompletedOf(Arrays.asList(Future.value(1))); assertEquals(new Integer(1), get(f)); } @Test public void firstCompletedOfSatisfiedFutures() throws CheckedFutureException { Future<Integer> future = Future.firstCompletedOf(Arrays.asList(Future.value(1), Future.value(2))); assertEquals(new Integer(1), get(future)); } @Test public void firstCompletedOfPromises() throws CheckedFutureException { Promise<Integer> p1 = Promise.apply(); Promise<Integer> p2 = Promise.apply(); Future<Integer> future = Future.firstCompletedOf(Arrays.asList(p1, p2)); p2.setValue(2); assertEquals(new Integer(2), get(future)); } @Test(expected = TestException.class) public void firstCompletedOfPromisesException() throws CheckedFutureException { Promise<Integer> p1 = Promise.apply(); Promise<Integer> p2 = Promise.apply(); Future<Integer> future = Future.firstCompletedOf(Arrays.asList(p1, p2)); p1.setException(new TestException()); get(future); } @Test public void firstCompletedOfMixed() throws CheckedFutureException { Promise<Integer> p1 = Promise.apply(); Promise<Integer> p2 = Promise.apply(); Future<Integer> future = Future.firstCompletedOf(Arrays.asList(p1, p2, Future.value(3))); p1.setValue(1); p2.setValue(2); assertEquals(new Integer(3), get(future)); } @Test public void firstCompletedOfMixedException() throws CheckedFutureException { Promise<Integer> p1 = Promise.apply(); Promise<Integer> p2 = Promise.apply(); Future<Integer> future = Future.firstCompletedOf(Arrays.asList(p1, p2, Future.value(3))); p1.setValue(1); p2.setException(new Throwable()); assertEquals(new Integer(3), get(future)); } @Test public void firstCompletedOfInterrupts() { AtomicReference<Throwable> p1Intr = new AtomicReference<>(); AtomicReference<Throwable> p2Intr = new AtomicReference<>(); Promise<Integer> p1 = Promise.apply(p1Intr::set); Promise<Integer> p2 = Promise.apply(p2Intr::set); Future<Integer> future = Future.firstCompletedOf(Arrays.asList(p1, p2)); future.raise(ex); assertEquals(ex, p1Intr.get()); assertEquals(ex, p2Intr.get()); } @Test(expected = TimeoutException.class) public void firstCompletedOfTimeout() throws CheckedFutureException { Promise<Integer> p1 = Promise.apply(); Promise<Integer> p2 = Promise.apply(); Future<Integer> future = Future.firstCompletedOf(Arrays.asList(p1, p2)); future.get(10, TimeUnit.MILLISECONDS); } /*** whileDo ***/ @Test public void whileDo() throws CheckedFutureException { int iterations = 200000; AtomicInteger count = new AtomicInteger(iterations); AtomicInteger callCount = new AtomicInteger(0); Future<Void> future = Future.whileDo(() -> count.decrementAndGet() >= 0, () -> Future.apply(() -> callCount.incrementAndGet())); get(future); assertEquals(-1, count.get()); assertEquals(iterations, callCount.get()); } /*** within ***/ @Test(expected = TimeoutException.class) public void withinDefaultExceptionFailure() throws CheckedFutureException { Future<Integer> f = (Promise.<Integer>apply()).within(1, TimeUnit.MILLISECONDS, scheduler); get(f); } @Test public void withinDefaultExceptionSuccess() throws CheckedFutureException { Promise<Integer> p = Promise.<Integer>apply(); Future<Integer> f = p.within(10, TimeUnit.MILLISECONDS, scheduler); p.setValue(1); assertEquals(new Integer(1), get(f)); } }
fix flaky test
future-java/src/test/java/io/trane/future/FutureTest.java
fix flaky test
Java
apache-2.0
4eb22489a20c0ca5e3e5f1dff72b6bd446349035
0
bodar/totallylazy,bodar/totallylazy,bodar/totallylazy
package com.googlecode.totallylazy; import com.googlecode.totallylazy.iterators.NodeIterator; import com.googlecode.totallylazy.iterators.PoppingIterator; import org.w3c.dom.Attr; import org.w3c.dom.CharacterData; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.EntityResolver; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpression; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.StringReader; import java.io.StringWriter; import java.util.Iterator; import java.util.Map; import java.util.NoSuchElementException; import static com.googlecode.totallylazy.Strings.bytes; import static com.googlecode.totallylazy.Strings.string; import static com.googlecode.totallylazy.xml.FunctionResolver.resolver; import static java.lang.Integer.getInteger; public class Xml { public static final Escaper DEFAULT_ESCAPER = new Escaper(). withRule('&', "&amp;"). withRule('<', "&lt;"). withRule('>', "&gt;"). withRule('\'', "&#39;"). withRule('"', "&quot;"). withRule(Strings.unicodeControlOrUndefinedCharacter(), toXmlEntity()); public static String selectContents(final Node node, final String expression) { return contents(internalSelectNodes(node, expression)); } public static Sequence<Node> selectNodes(final Node node, final String expression) { return internalSelectNodes(node, expression); } public static Sequence<Node> selectNodesForwardOnly(final Node node, final String expression) { return Sequences.forwardOnly(new PoppingIterator<Node>(selectNodes(node, expression).toList().iterator())); } public static Number selectNumber(final Node node, final String expression) { try { return (Number) xpathExpression(expression).evaluate(node, XPathConstants.NUMBER); } catch (XPathExpressionException e) { throw LazyException.lazyException(e); } } public static boolean matches(final Node node, final String expression) { try { return (Boolean) xpathExpression(expression).evaluate(node, XPathConstants.BOOLEAN); } catch (XPathExpressionException e) { throw LazyException.lazyException(e); } } private static Sequence<Node> internalSelectNodes(final Node node, final String expression) { try { return sequence((NodeList) xpathExpression(expression).evaluate(node, XPathConstants.NODESET)); } catch (XPathExpressionException e) { try { String nodeAsString = (String) xpathExpression(expression).evaluate(node, XPathConstants.STRING); return Sequences.<Node>sequence(documentFor(node).createTextNode(nodeAsString)); } catch (XPathExpressionException ignore) { throw new IllegalArgumentException(String.format("Failed to compile xpath '%s'", expression), e); } } } private static Document documentFor(Node node) { return node instanceof Document ? (Document) node : node.getOwnerDocument(); } public static Node expectNode(final Node node, String xpath) { Option<Node> foundNode = selectNode(node, xpath); if (foundNode.isEmpty()) throw new NoSuchElementException("No node for xpath " + xpath); return foundNode.get(); } public static Option<Node> selectNode(final Node node, final String expression) { return selectNodes(node, expression).headOption(); } public static Sequence<Element> selectElements(final Node node, final String expression) { return selectNodes(node, expression).safeCast(Element.class); } public static Element expectElement(final Node node, String xpath) { Option<Element> element = selectElement(node, xpath); if (element.isEmpty()) throw new NoSuchElementException("No element for xpath " + xpath); return element.get(); } public static Option<Element> selectElement(final Node node, final String expression) { return selectElements(node, expression).headOption(); } private static ThreadLocal<XPath> xpath = new ThreadLocal<XPath>() { @Override protected XPath initialValue() { return internalXpath(); } }; private static XPath internalXpath() { XPath xPath = XPathFactory.newInstance().newXPath(); xPath.setXPathFunctionResolver(resolver); return xPath; } public static XPath xpath() { return xpath.get(); } private static ThreadLocal<Map<String, XPathExpression>> expressions = new ThreadLocal<Map<String, XPathExpression>>() { @Override protected Map<String, XPathExpression> initialValue() { return Maps.lruMap(getInteger("totallylazy.xpath.cache.size", 1000)); } }; private static XPathExpression xpathExpression(String expression) throws XPathExpressionException { Map<String, XPathExpression> expressionMap = expressions.get(); if (!expressionMap.containsKey(expression)) { expressionMap.put(expression, xpath().compile(expression)); } return expressionMap.get(expression); } public static Sequence<Node> sequence(final NodeList nodes) { return new Sequence<Node>() { public Iterator<Node> iterator() { return new NodeIterator(nodes); } }; } public static String contents(Sequence<Node> nodes) { return contentsSequence(nodes).toString(""); } public static Sequence<String> contentsSequence(Sequence<Node> nodes) { return nodes.map(contents()); } public static Sequence<String> textContents(Sequence<Node> nodes) { return nodes.map(textContent()); } public static Sequence<String> textContents(NodeList nodes) { return Xml.textContents(Xml.sequence(nodes)); } public static final Function1<Node, String> textContent = new Function1<Node, String>() { @Override public String call(Node node) throws Exception { return node.getTextContent(); } }; public static Function1<Node, String> textContent() { return textContent; } public static Block<Element> removeAttribute(final String name) { return new Block<Element>() { @Override protected void execute(Element element) throws Exception { element.removeAttribute(name); } }; } public static Function1<Node, String> contents() { return new Function1<Node, String>() { public String call(Node node) throws Exception { return contents(node); } }; } public static String contents(Node node) throws Exception { if (node instanceof Attr) { return contents((Attr) node); } if (node instanceof CharacterData) { return contents((CharacterData) node); } if (node instanceof Element) { return contents((Element) node); } throw new UnsupportedOperationException("Unknown node type " + node.getClass()); } public static String contents(CharacterData characterData) { return characterData.getData(); } public static String contents(Attr attr) { return attr.getValue(); } public static String contents(Element element) throws Exception { return sequence(element.getChildNodes()).map(new Callable1<Node, String>() { public String call(Node node) throws Exception { if (node instanceof Element) { return asString((Element) node); } return contents(node); } }).toString(""); } public static String asString(Node node) throws Exception { return asString(node, true); } public static String asString(Node node, boolean omitXmlDeclaration) throws TransformerException { Transformer transformer = transformer(); StringWriter writer = new StringWriter(); if (omitXmlDeclaration) transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.transform(new DOMSource(node), new StreamResult(writer)); return writer.toString(); } @SuppressWarnings("unchecked") public static Transformer transformer() throws TransformerConfigurationException { return internalTransformer(); } public static Transformer transformer(Pair<String, Object>... attributes) throws TransformerConfigurationException { return internalTransformer(attributes); } private static Transformer internalTransformer(Pair<String, Object>... attributes) throws TransformerConfigurationException { TransformerFactory transformerFactory = TransformerFactory.newInstance(); for (Pair<String, Object> attribute : attributes) { transformerFactory.setAttribute(attribute.first(), attribute.second()); } return transformerFactory.newTransformer(); } public static Document document(byte[] bytes) { return document(string(bytes)); } public static Document document(String xml) { try { DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); documentBuilder.setEntityResolver(ignoreEntities()); documentBuilder.setErrorHandler(null); return documentBuilder.parse(new ByteArrayInputStream(bytes(xml))); } catch (Exception e) { throw LazyException.lazyException(e); } } private static EntityResolver ignoreEntities() { return new EntityResolver() { public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException { return new InputSource(new StringReader("")); } }; } public static Sequence<Node> remove(final Node root, final String expression) { return remove(selectNodes(root, expression)); } public static Sequence<Node> remove(final Sequence<Node> nodes) { return nodes.map(remove()).realise(); } private static Function1<Node, Node> remove() { return new Function1<Node, Node>() { public Node call(Node node) throws Exception { return node.getParentNode().removeChild(node); } }; } @SuppressWarnings("unchecked") public static String format(final Node node) throws Exception { return format(node, new Pair[0]); } public static String format(final Node node, final Pair<String, Object>... attributes) throws Exception { Transformer transformer = transformer(attributes); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); StringWriter writer = new StringWriter(); transformer.transform(new DOMSource(node), new StreamResult(writer)); return writer.toString(); } public static String escape(Object value) { return DEFAULT_ESCAPER. escape(value); } public static Function1<Object, String> escape() { return new Function1<Object, String>() { public String call(Object value) throws Exception { return escape(value); } }; } public static Function1<Character, String> toXmlEntity() { return new Function1<Character, String>() { public String call(Character character) throws Exception { return String.format("&#%s;", Integer.toString(character, 10)); } }; } public static class functions { public static Function1<Element, Element> setAttribute(final String name, final String value) { return new Function1<Element, Element>() { public Element call(Element element) throws Exception { element.setAttribute(name, value); return element; } }; } public static Predicate<Node> matches(final String expression) { return new Predicate<Node>() { @Override public boolean matches(Node node) { return Xml.matches(node, expression); } }; } public static Function1<Element, String> attribute(final String attributeName) { return new Function1<Element, String>() { public String call(Element element) throws Exception { return element.getAttribute(attributeName); } }; } public static Function2<Node, String, String> selectContents() { return new Function2<Node, String, String>() { @Override public String call(Node node, String expression) throws Exception { return Xml.selectContents(node, expression); } }; } public static Function1<Node, String> selectContents(final String expression) { return new Function1<Node, String>() { @Override public String call(Node node) throws Exception { return Xml.selectContents(node, expression); } }; } public static Function2<Node, String, Sequence<Node>> selectNodes() { return new Function2<Node, String, Sequence<Node>>() { @Override public Sequence<Node> call(final Node node, final String expression) throws Exception { return Xml.selectNodes(node, expression); } }; } public static Function1<String, Document> document() { return new Function1<String, Document>() { @Override public Document call(String value) throws Exception { return Xml.document(value); } }; } public static Block<Element> setTextContent(final Function<String> function) { return new Block<Element>() { @Override protected void execute(Element element) throws Exception { element.setTextContent(function.apply()); } }; } } }
src/com/googlecode/totallylazy/Xml.java
package com.googlecode.totallylazy; import com.googlecode.totallylazy.iterators.NodeIterator; import com.googlecode.totallylazy.iterators.PoppingIterator; import org.w3c.dom.Attr; import org.w3c.dom.CharacterData; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.EntityResolver; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpression; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.StringReader; import java.io.StringWriter; import java.util.Iterator; import java.util.Map; import java.util.NoSuchElementException; import static com.googlecode.totallylazy.Strings.bytes; import static com.googlecode.totallylazy.Strings.string; import static com.googlecode.totallylazy.xml.FunctionResolver.resolver; import static java.lang.Integer.getInteger; public class Xml { public static final Escaper DEFAULT_ESCAPER = new Escaper(). withRule('&', "&amp;"). withRule('<', "&lt;"). withRule('>', "&gt;"). withRule('\'', "&#39;"). withRule('"', "&quot;"). withRule(Strings.unicodeControlOrUndefinedCharacter(), toXmlEntity()); public static String selectContents(final Node node, final String expression) { return contents(internalSelectNodes(node, expression)); } public static Sequence<Node> selectNodes(final Node node, final String expression) { return internalSelectNodes(node, expression); } public static Sequence<Node> selectNodesForwardOnly(final Node node, final String expression) { return Sequences.forwardOnly(new PoppingIterator<Node>(selectNodes(node, expression).toList().iterator())); } public static Number selectNumber(final Node node, final String expression) { try { return (Number) xpathExpression(expression).evaluate(node, XPathConstants.NUMBER); } catch (XPathExpressionException e) { throw LazyException.lazyException(e); } } public static boolean matches(final Node node, final String expression) { try { return (Boolean) xpathExpression(expression).evaluate(node, XPathConstants.BOOLEAN); } catch (XPathExpressionException e) { throw LazyException.lazyException(e); } } private static Sequence<Node> internalSelectNodes(final Node node, final String expression) { try { return sequence((NodeList) xpathExpression(expression).evaluate(node, XPathConstants.NODESET)); } catch (XPathExpressionException e) { try { String nodeAsString = (String) xpathExpression(expression).evaluate(node, XPathConstants.STRING); return Sequences.<Node>sequence(documentFor(node).createTextNode(nodeAsString)); } catch (XPathExpressionException ignore) { throw new IllegalArgumentException(String.format("Failed to compile xpath '%s'", expression),e); } } } private static Document documentFor(Node node) { return node instanceof Document ? (Document) node : node.getOwnerDocument(); } public static Node expectNode(final Node node, String xpath) { Option<Node> foundNode = selectNode(node, xpath); if(foundNode.isEmpty()) throw new NoSuchElementException("No node for xpath " + xpath); return foundNode.get(); } public static Option<Node> selectNode(final Node node, final String expression) { return selectNodes(node, expression).headOption(); } public static Sequence<Element> selectElements(final Node node, final String expression) { return selectNodes(node, expression).safeCast(Element.class); } public static Element expectElement(final Node node, String xpath) { Option<Element> element = selectElement(node, xpath); if(element.isEmpty()) throw new NoSuchElementException("No element for xpath " + xpath); return element.get(); } public static Option<Element> selectElement(final Node node, final String expression) { return selectElements(node, expression).headOption(); } private static ThreadLocal<XPath> xpath = new ThreadLocal<XPath>() { @Override protected XPath initialValue() { return internalXpath(); } }; private static XPath internalXpath() { XPath xPath = XPathFactory.newInstance().newXPath(); xPath.setXPathFunctionResolver(resolver); return xPath; } public static XPath xpath() { return xpath.get(); } private static ThreadLocal<Map<String, XPathExpression>> expressions = new ThreadLocal<Map<String, XPathExpression>>() { @Override protected Map<String, XPathExpression> initialValue() { return Maps.lruMap(getInteger("totallylazy.xpath.cache.size", 1000)); } }; private static XPathExpression xpathExpression(String expression) throws XPathExpressionException { Map<String, XPathExpression> expressionMap = expressions.get(); if (!expressionMap.containsKey(expression)) { expressionMap.put(expression, xpath().compile(expression)); } return expressionMap.get(expression); } public static Sequence<Node> sequence(final NodeList nodes) { return new Sequence<Node>() { public Iterator<Node> iterator() { return new NodeIterator(nodes); } }; } public static String contents(Sequence<Node> nodes) { return contentsSequence(nodes).toString(""); } public static Sequence<String> contentsSequence(Sequence<Node> nodes) { return nodes.map(contents()); } public static Sequence<String> textContents(Sequence<Node> nodes) { return nodes.map(textContent()); } public static Sequence<String> textContents(NodeList nodes) { return Xml.textContents(Xml.sequence(nodes)); } public static final Function1<Node, String> textContent = new Function1<Node, String>() { @Override public String call(Node node) throws Exception { return node.getTextContent(); } }; public static Function1<Node, String> textContent() { return textContent; } public static Block<Element> removeAttribute(final String name) { return new Block<Element>() { @Override protected void execute(Element element) throws Exception { element.removeAttribute(name); } }; } public static Function1<Node, String> contents() { return new Function1<Node, String>() { public String call(Node node) throws Exception { return contents(node); } }; } public static String contents(Node node) throws Exception { if (node instanceof Attr) { return contents((Attr) node); } if (node instanceof CharacterData) { return contents((CharacterData) node); } if (node instanceof Element) { return contents((Element) node); } throw new UnsupportedOperationException("Unknown node type " + node.getClass()); } public static String contents(CharacterData characterData) { return characterData.getData(); } public static String contents(Attr attr) { return attr.getValue(); } public static String contents(Element element) throws Exception { return sequence(element.getChildNodes()).map(new Callable1<Node, String>() { public String call(Node node) throws Exception { if (node instanceof Element) { return asString((Element) node); } return contents(node); } }).toString(""); } public static String asString(Node node) throws Exception { Transformer transformer = transformer(); StringWriter writer = new StringWriter(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.transform(new DOMSource(node), new StreamResult(writer)); return writer.toString(); } @SuppressWarnings("unchecked") public static Transformer transformer() throws TransformerConfigurationException { return internalTransformer(); } public static Transformer transformer(Pair<String, Object>... attributes) throws TransformerConfigurationException { return internalTransformer(attributes); } private static Transformer internalTransformer(Pair<String, Object>... attributes) throws TransformerConfigurationException { TransformerFactory transformerFactory = TransformerFactory.newInstance(); for (Pair<String, Object> attribute : attributes) { transformerFactory.setAttribute(attribute.first(), attribute.second()); } return transformerFactory.newTransformer(); } public static Document document(byte[] bytes) { return document(string(bytes)); } public static Document document(String xml) { try { DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); documentBuilder.setEntityResolver(ignoreEntities()); documentBuilder.setErrorHandler(null); return documentBuilder.parse(new ByteArrayInputStream(bytes(xml))); } catch (Exception e) { throw LazyException.lazyException(e); } } private static EntityResolver ignoreEntities() { return new EntityResolver() { public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException { return new InputSource(new StringReader("")); } }; } public static Sequence<Node> remove(final Node root, final String expression) { return remove(selectNodes(root, expression)); } public static Sequence<Node> remove(final Sequence<Node> nodes) { return nodes.map(remove()).realise(); } private static Function1<Node, Node> remove() { return new Function1<Node, Node>() { public Node call(Node node) throws Exception { return node.getParentNode().removeChild(node); } }; } @SuppressWarnings("unchecked") public static String format(final Node node) throws Exception { return format(node, new Pair[0]); } public static String format(final Node node, final Pair<String, Object>... attributes) throws Exception { Transformer transformer = transformer(attributes); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); StringWriter writer = new StringWriter(); transformer.transform(new DOMSource(node), new StreamResult(writer)); return writer.toString(); } public static String escape(Object value) { return DEFAULT_ESCAPER. escape(value); } public static Function1<Object, String> escape() { return new Function1<Object, String>() { public String call(Object value) throws Exception { return escape(value); } }; } public static Function1<Character, String> toXmlEntity() { return new Function1<Character, String>() { public String call(Character character) throws Exception { return String.format("&#%s;", Integer.toString(character, 10)); } }; } public static class functions { public static Function1<Element, Element> setAttribute(final String name, final String value) { return new Function1<Element, Element>() { public Element call(Element element) throws Exception { element.setAttribute(name,value); return element; } }; } public static Predicate<Node> matches(final String expression) { return new Predicate<Node>() { @Override public boolean matches(Node node) { return Xml.matches(node, expression); } }; } public static Function1<Element, String> attribute(final String attributeName) { return new Function1<Element, String>() { public String call(Element element) throws Exception { return element.getAttribute(attributeName); } }; } public static Function2<Node, String, String> selectContents() { return new Function2<Node, String, String>() { @Override public String call(Node node, String expression) throws Exception { return Xml.selectContents(node, expression); } }; } public static Function1<Node, String> selectContents(final String expression) { return new Function1<Node, String>() { @Override public String call(Node node) throws Exception { return Xml.selectContents(node, expression); } }; } public static Function2<Node, String, Sequence<Node>> selectNodes() { return new Function2<Node, String, Sequence<Node>>() { @Override public Sequence<Node> call(final Node node, final String expression) throws Exception { return Xml.selectNodes(node, expression); } }; } public static Function1<String, Document> document() { return new Function1<String, Document>() { @Override public Document call(String value) throws Exception { return Xml.document(value); } }; } } }
added Xml.asString overload to allow xml declaration
src/com/googlecode/totallylazy/Xml.java
added Xml.asString overload to allow xml declaration
Java
apache-2.0
aec8675a8aa8258a086c255eec445445fec9a19e
0
TeamDev-Ltd/JxMaps-Examples
/* * Copyright (c) 2000-2016 TeamDev Ltd. All rights reserved. * Use is subject to Apache 2.0 license terms. */ package com.teamdev.jxmaps.demo; import com.teamdev.jxmaps.examples.ControlPanel; import javax.swing.*; import javax.swing.event.HyperlinkEvent; import javax.swing.event.HyperlinkListener; import java.awt.*; import java.net.URL; class AboutPanel extends JPanel implements ControlPanel { public AboutPanel() { setBackground(Color.white); setLayout(new BorderLayout()); JTextPane aboutText = new JTextPane(); aboutText.setContentType("text/html"); aboutText.setText("<html><font size=\"3\" face=\"Roboto>\">" + "JxMaps Demo<br><br>" + "Version 1.1<br><br>" + "This application is created for demonstration purposes only.<br>" + "&copy; 2016 TeamDev Ltd. All rights reserved.<br><br>" + "Powered by <font color=\"#3d82f8\"><a href=\"https://www.teamdev.com/jxmaps\" style=\"text-decoration:none\">JxMaps</a>. <a href=\"https://www.teamdev.com/jxmaps-licence-agreement\" style=\"text-decoration:none\">See terms of use.</a></font><br>" + "Created using <font color=\"#3d82f8\"><a href=\"https://developers.google.com/maps/terms\" style=\"text-decoration:none\">Google Maps JavaScript API.</a></font><br>" + "Based on <font color=\"#3d82f8\"><a href=\"http://www.chromium.org/\" style=\"text-decoration:none\">Chromium project</a></font>. See <font color=\"#3d82f8\"><a href=\"http://jxmaps-support.teamdev.com/documentation/open-source-components\" style=\"text-decoration:none\">full list</a></font> of Chromium<br>components, used in the current JxMaps version.<br>"+ "This demo uses <font color=\"#3d82f8\"><a href=\"https://www.google.com/fonts/specimen/Roboto\" style=\"text-decoration:none\">WebKit</a></font> project under LGPL. </font><br>" + "This demo uses <font color=\"#3d82f8\"><a href=\"https://www.google.com/fonts/specimen/Roboto\" style=\"text-decoration:none\">Roboto</a></font> font, distributed under <font color=\"#3d82f8\"><a href=\"http://www.apache.org/licenses/LICENSE-2.0.html\" style=\"text-decoration:none\">Apache 2.0</a></font><br>licence, and <font color=\"#3d82f8\"><a href=\"https://design.google.com/icons/\" style=\"text-decoration:none\">Material icons.</a></font><br>" + "</font><</html>"); Font robotoPlain13 = new Font("Roboto", 0, 12); aboutText.setFont(robotoPlain13); aboutText.setBorder(BorderFactory.createEmptyBorder(20, 20, 0, 20)); aboutText.setEditable(false); aboutText.addHyperlinkListener(new HyperlinkListener() { @Override public void hyperlinkUpdate(HyperlinkEvent e) { if (e.getEventType().equals(HyperlinkEvent.EventType.ACTIVATED)) { URL url = e.getURL(); try { Desktop desktop = java.awt.Desktop.getDesktop(); desktop.browse(url.toURI()); } catch (Exception e1) { throw new RuntimeException(e1); } } } }); add(aboutText, BorderLayout.CENTER); } @Override public JComponent getControlPanel() { return this; } @Override public void configureControlPanel() { } @Override public int getPreferredHeight() { return 340; } }
src/com/teamdev/jxmaps/demo/AboutPanel.java
/* * Copyright (c) 2000-2016 TeamDev Ltd. All rights reserved. * Use is subject to Apache 2.0 license terms. */ package com.teamdev.jxmaps.demo; import com.teamdev.jxmaps.examples.ControlPanel; import javax.swing.*; import javax.swing.event.HyperlinkEvent; import javax.swing.event.HyperlinkListener; import java.awt.*; import java.net.URL; class AboutPanel extends JPanel implements ControlPanel { public AboutPanel() { setBackground(Color.white); setLayout(new BorderLayout()); JTextPane aboutText = new JTextPane(); aboutText.setContentType("text/html"); aboutText.setText("<html><font size=\"3\" face=\"Roboto>\">" + "JxMaps Demo<br><br>" + "Version 1.0.1<br><br>" + "This application is created for demonstration purposes only.<br>" + "&copy; 2016 TeamDev Ltd. All rights reserved.<br><br>" + "Powered by <font color=\"#3d82f8\"><a href=\"https://www.teamdev.com/jxmaps\" style=\"text-decoration:none\">JxMaps</a>. <a href=\"https://www.teamdev.com/jxmaps-licence-agreement\" style=\"text-decoration:none\">See terms of use.</a></font><br>" + "Created using <font color=\"#3d82f8\"><a href=\"https://developers.google.com/maps/terms\" style=\"text-decoration:none\">Google Maps JavaScript API.</a></font><br>" + "Based on <font color=\"#3d82f8\"><a href=\"http://www.chromium.org/\" style=\"text-decoration:none\">Chromium project</a></font>. See <font color=\"#3d82f8\"><a href=\"https://github.com/TeamDev-Ltd/JxMaps-Examples/wiki/Open-Source-Components\" style=\"text-decoration:none\">full list</a></font> of Chromium<br>components, used in the current JxMaps version.<br>"+ "This demo uses <font color=\"#3d82f8\"><a href=\"https://www.google.com/fonts/specimen/Roboto\" style=\"text-decoration:none\">Roboto</a></font> font, distributed under <font color=\"#3d82f8\"><a href=\"http://www.apache.org/licenses/LICENSE-2.0.html\" style=\"text-decoration:none\">Apache 2.0</a></font><br>licence, and <font color=\"#3d82f8\"><a href=\"https://design.google.com/icons/\" style=\"text-decoration:none\">Material icons.</a></font><br>" + "</font><</html>"); Font robotoPlain13 = new Font("Roboto", 0, 12); aboutText.setFont(robotoPlain13); aboutText.setBorder(BorderFactory.createEmptyBorder(20, 20, 0, 20)); aboutText.setEditable(false); aboutText.addHyperlinkListener(new HyperlinkListener() { @Override public void hyperlinkUpdate(HyperlinkEvent e) { if (e.getEventType().equals(HyperlinkEvent.EventType.ACTIVATED)) { URL url = e.getURL(); try { Desktop desktop = java.awt.Desktop.getDesktop(); desktop.browse(url.toURI()); } catch (Exception e1) { throw new RuntimeException(e1); } } } }); add(aboutText, BorderLayout.CENTER); } @Override public JComponent getControlPanel() { return this; } @Override public void configureControlPanel() { } @Override public int getPreferredHeight() { return 320; } }
About dialog updated
src/com/teamdev/jxmaps/demo/AboutPanel.java
About dialog updated
Java
apache-2.0
cf0ed8de622561f68c2083e6185099f0a149b652
0
HanSolo/tilesfx,HanSolo/tilesfx,HanSolo/tilesfx
/* * Copyright (c) 2016 by Gerrit Grunwald * * 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 eu.hansolo.tilesfx.tools; import java.time.Duration; import java.time.Instant; import java.util.LinkedList; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; /** * Created by hansolo on 01.11.16. */ public class MovingAverage { public static final int MAX_PERIOD = 1000; private static final int DEFAULT_PERIOD = 10; private final Queue<Data> window; private int period; private double sum; // ******************** Constructors ************************************** public MovingAverage() { this(DEFAULT_PERIOD); } public MovingAverage(final int PERIOD) { period = Helper.clamp(0, MAX_PERIOD, PERIOD); window = new ConcurrentLinkedQueue<>(); } // ******************** Methods ******************************************* public void addData(final Data DATA) { sum += DATA.getValue(); window.add(DATA); if (window.size() > period) { sum -= window.remove().getValue(); } } public void addValue(final double VALUE) { addData(new Data(VALUE)); } public Queue<Data> getWindow() { return new LinkedList<>(window); } public Data getFirstEntry() { return window.peek(); } public Data getLastEntry() { return window.stream().reduce((first, second) -> second).orElse(null); } public Instant getTimeSpan() { Data firstEntry = getFirstEntry(); Data lastEntry = getLastEntry(); if (null == firstEntry || null == lastEntry) return null; return lastEntry.getTimestamp().minusSeconds(firstEntry.getTimestamp().getEpochSecond()); } public double getAverage() { if (window.isEmpty()) return 0; // technically the average is undefined return (sum / window.size()); } public double getTimeBasedAverageOf(final Duration DURATION) { assert !DURATION.isNegative() : "Time period must be positive"; Instant now = Instant.now(); double average = window.stream() .filter(v -> v.getTimestamp().isAfter(now.minus(DURATION))) .mapToDouble(Data::getValue) .average() .getAsDouble(); return average; } public int getPeriod() { return period; } public void setPeriod(final int PERIOD) { period = Helper.clamp(0, MAX_PERIOD, PERIOD); reset(); } public void reset() { window.clear(); } }
src/main/java/eu/hansolo/tilesfx/tools/MovingAverage.java
/* * Copyright (c) 2016 by Gerrit Grunwald * * 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 eu.hansolo.tilesfx.tools; import java.time.Duration; import java.time.Instant; import java.util.LinkedList; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; /** * Created by hansolo on 01.11.16. */ public class MovingAverage { public static final int MAX_PERIOD = 1000; private static final int DEFAULT_PERIOD = 10; private final Queue<Data> window; private int numberPeriod; private double sum; // ******************** Constructors ************************************** public MovingAverage() { this(DEFAULT_PERIOD); } public MovingAverage(final int NUMBER_PERIOD) { numberPeriod = Helper.clamp(0, MAX_PERIOD, NUMBER_PERIOD); window = new ConcurrentLinkedQueue<>(); } // ******************** Methods ******************************************* public void addData(final Data DATA) { sum += DATA.getValue(); window.add(DATA); if (window.size() > numberPeriod) { sum -= window.remove().getValue(); } } public void addValue(final double VALUE) { addData(new Data(VALUE)); } public Queue<Data> getWindow() { return new LinkedList<>(window); } public Data getFirstEntry() { return window.peek(); } public Data getLastEntry() { return window.stream().reduce((first, second) -> second).orElse(null); } public Instant getTimeSpan() { Data firstEntry = getFirstEntry(); Data lastEntry = getLastEntry(); if (null == firstEntry || null == lastEntry) return null; return lastEntry.getTimestamp().minusSeconds(firstEntry.getTimestamp().getEpochSecond()); } public double getAverage() { if (window.isEmpty()) return 0; // technically the average is undefined return (sum / window.size()); } public double getTimeBasedAverageOf(final Duration DURATION) { assert !DURATION.isNegative() : "Time period must be positive"; Instant now = Instant.now(); double average = window.stream() .filter(v -> v.getTimestamp().isAfter(now.minus(DURATION))) .mapToDouble(Data::getValue) .average() .getAsDouble(); return average; } public void reset() { window.clear(); } }
Added possibility to set averaging period in MovingAverage
src/main/java/eu/hansolo/tilesfx/tools/MovingAverage.java
Added possibility to set averaging period in MovingAverage
Java
bsd-2-clause
eebe2edca8542918bd42d9494efbe0dd7834c7b3
0
chototsu/MikuMikuStudio,chototsu/MikuMikuStudio,chototsu/MikuMikuStudio,chototsu/MikuMikuStudio
/* * Copyright (c) 2003-2008 jMonkeyEngine * 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 'jMonkeyEngine' 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 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 com.jme.scene; import java.io.IOException; import java.io.Serializable; import java.nio.FloatBuffer; import java.util.ArrayList; import java.util.Stack; import java.util.logging.Logger; import com.jme.bounding.BoundingVolume; import com.jme.intersection.PickResults; import com.jme.math.FastMath; import com.jme.math.Quaternion; import com.jme.math.Ray; import com.jme.math.Vector2f; import com.jme.math.Vector3f; import com.jme.renderer.ColorRGBA; import com.jme.renderer.Renderer; import com.jme.scene.state.LightState; import com.jme.scene.state.LightUtil; import com.jme.scene.state.RenderState; import com.jme.scene.state.TextureState; import com.jme.util.export.InputCapsule; import com.jme.util.export.JMEExporter; import com.jme.util.export.JMEImporter; import com.jme.util.export.OutputCapsule; import com.jme.util.export.Savable; import com.jme.util.geom.BufferUtils; /** * <code>Geometry</code> defines a leaf node of the scene graph. The leaf node * contains the geometric data for rendering objects. It manages all rendering * information such as a collection of states and the data for a model. * Subclasses define what the model data is. * * @author Mark Powell * @author Joshua Slack * @version $Id: Geometry.java,v 1.113 2007/10/05 22:40:35 nca Exp $ */ public abstract class Geometry extends Spatial implements Serializable, Savable { private static final Logger logger = Logger.getLogger(Geometry.class.getName()); private static final long serialVersionUID = 1; /** The local bounds of this Geometry object. */ protected BoundingVolume bound; /** The number of vertexes in this geometry. */ protected int vertQuantity = 0; /** The geometry's per vertex color information. */ protected transient FloatBuffer colorBuf; /** The geometry's per vertex normal information. */ protected transient FloatBuffer normBuf; /** The geometry's vertex information. */ protected transient FloatBuffer vertBuf; /** The geometry's per Texture per vertex texture coordinate information. */ protected transient ArrayList<TexCoords> texBuf; /** The geometry's per vertex color information. */ protected transient FloatBuffer tangentBuf; /** The geometry's per vertex normal information. */ protected transient FloatBuffer binormalBuf; /** The geometry's per vertex fog buffer depth values */ protected transient FloatBuffer fogBuf; /** The geometry's VBO information. */ protected transient VBOInfo vboInfo; protected boolean enabled = true; protected boolean castsShadows = true; protected boolean hasDirtyVertices = false; /** * The compiled list of renderstates for this geometry, taking into account * ancestors' states - updated with updateRenderStates() */ public RenderState[] states = new RenderState[RenderState.RS_MAX_STATE]; private LightState lightState; protected ColorRGBA defaultColor = new ColorRGBA(ColorRGBA.white); /** * Non -1 values signal that drawing this scene should use the provided * display list instead of drawing from the buffers. */ protected int displayListID = -1; /** Static computation field */ protected static Vector3f compVect = new Vector3f(); /** * Empty Constructor to be used internally only. */ public Geometry() { super(); texBuf = new ArrayList<TexCoords>(1); texBuf.add(null); } /** * Constructor instantiates a new <code>Geometry</code> object. This is * the default object which has an empty vertex array. All other data is * null. * * @param name * the name of the scene element. This is required for * identification and comparision purposes. */ public Geometry(String name) { super(name); texBuf = new ArrayList<TexCoords>(1); texBuf.add(null); if (!(this instanceof SharedMesh)) reconstruct(null, null, null, null); } /** * Constructor creates a new <code>Geometry</code> object. During * instantiation the geometry is set including vertex, normal, color and * texture information. * * @param name * the name of the scene element. This is required for * identification and comparision purposes. * @param vertex * the points that make up the geometry. * @param normal * the normals of the geometry. * @param color * the color of each point of the geometry. * @param coords * the texture coordinates of the geometry (position 0.) */ public Geometry(String name, FloatBuffer vertex, FloatBuffer normal, FloatBuffer color, TexCoords coords) { super(name); texBuf = new ArrayList<TexCoords>(1); texBuf.add(null); reconstruct(vertex, normal, color, coords); } /** * returns the number of vertices contained in this geometry. */ @Override public int getVertexCount() { return vertQuantity; } public void setVertexCount(int vertQuantity) { this.vertQuantity = vertQuantity; } @Override public int getTriangleCount() { return 0; } /** * <code>reconstruct</code> reinitializes the geometry with new data. This * will reuse the geometry object. * * @param vertices * the new vertices to use. * @param normals * the new normals to use. * @param colors * the new colors to use. * @param coords * the new texture coordinates to use (position 0). */ public void reconstruct(FloatBuffer vertices, FloatBuffer normals, FloatBuffer colors, TexCoords coords) { if (vertices == null) setVertexCount(0); else setVertexCount(vertices.limit() / 3); setVertexBuffer(vertices); setNormalBuffer(normals); setColorBuffer(colors); if (getTextureCoords() == null) { setTextureCoords(new ArrayList<TexCoords>(1)); } clearTextureBuffers(); addTextureCoordinates(coords); if (getVBOInfo() != null) resizeTextureIds(1); } /** * Sets VBO info on this Geometry. * * @param info * the VBO info to set * @see VBOInfo */ public void setVBOInfo(VBOInfo info) { vboInfo = info; if (vboInfo != null) { vboInfo.resizeTextureIds(texBuf.size()); } } /** * @return VBO info object * @see VBOInfo */ public VBOInfo getVBOInfo() { return vboInfo; } /** * <code>setSolidColor</code> sets the color array of this geometry to a * single color. For greater efficiency, try setting the the ColorBuffer to * null and using DefaultColor instead. * * @param color * the color to set. */ public void setSolidColor(ColorRGBA color) { if (colorBuf == null) colorBuf = BufferUtils.createColorBuffer(vertQuantity); colorBuf.rewind(); for (int x = 0, cLength = colorBuf.remaining(); x < cLength; x += 4) { colorBuf.put(color.r); colorBuf.put(color.g); colorBuf.put(color.b); colorBuf.put(color.a); } colorBuf.flip(); } /** * Sets every color of this geometry's color array to a random color. */ public void setRandomColors() { if (colorBuf == null) colorBuf = BufferUtils.createColorBuffer(vertQuantity); for (int x = 0, cLength = colorBuf.limit(); x < cLength; x += 4) { colorBuf.put(FastMath.nextRandomFloat()); colorBuf.put(FastMath.nextRandomFloat()); colorBuf.put(FastMath.nextRandomFloat()); colorBuf.put(1); } colorBuf.flip(); } /** * <code>getVertexBuffer</code> returns the float buffer that contains * this geometry's vertex information. * * @return the float buffer that contains this geometry's vertex * information. */ public FloatBuffer getVertexBuffer() { return vertBuf; } /** * <code>setVertexBuffer</code> sets this geometry's vertices via a float * buffer consisting of groups of three floats: x,y and z. * * @param vertBuf * the new vertex buffer. */ public void setVertexBuffer(FloatBuffer vertBuf) { this.vertBuf = vertBuf; if (vertBuf != null) vertQuantity = vertBuf.limit() / 3; else vertQuantity = 0; } /** * Set the fog coordinates buffer. This should have the vertex count entries * * @param fogBuf The fog buffer to use in this geometry */ public void setFogCoordBuffer(FloatBuffer fogBuf) { this.fogBuf = fogBuf; } /** * The fog depth coord buffer * * @return The per vertex depth values for fog coordinates */ public FloatBuffer getFogBuffer() { return fogBuf; } /** * <code>getNormalBuffer</code> retrieves this geometry's normal * information as a float buffer. * * @return the float buffer containing the geometry information. */ public FloatBuffer getNormalBuffer() { return normBuf; } /** * <code>setNormalBuffer</code> sets this geometry's normals via a float * buffer consisting of groups of three floats: x,y and z. * * @param normBuf * the new normal buffer. */ public void setNormalBuffer(FloatBuffer normBuf) { this.normBuf = normBuf; } /** * <code>getColorBufferfer</code> retrieves the float buffer that contains * this geometry's color information. * * @return the buffer that contains this geometry's color information. */ public FloatBuffer getColorBuffer() { return colorBuf; } /** * <code>setColorBuffer</code> sets this geometry's colors via a float * buffer consisting of groups of four floats: r,g,b and a. * * @param colorBuf * the new color buffer. */ public void setColorBuffer(FloatBuffer colorBuf) { this.colorBuf = colorBuf; } /** * <code>copyTextureCoords</code> copys the texture coordinates of a given * texture unit to another location. If the texture unit is not valid, then * the coordinates are ignored. Coords are multiplied by the given factor. * * @param fromIndex * the coordinates to copy. * @param toIndex * the texture unit to set them to. * @param factor * a multiple to apply when copying */ public void copyTextureCoordinates(int fromIndex, int toIndex, float factor) { if (texBuf == null) return; if (fromIndex < 0 || fromIndex >= texBuf.size() || texBuf.get(fromIndex) == null) { return; } if (toIndex < 0 || toIndex == fromIndex) { return; } // make sure we are big enough while (toIndex >= texBuf.size()) { texBuf.add(null); } TexCoords dest = texBuf.get(toIndex); TexCoords src = texBuf.get(fromIndex); if (dest == null || dest.coords.capacity() != src.coords.limit()) { dest = new TexCoords(BufferUtils.createFloatBuffer(src.coords.capacity()), src.perVert); texBuf.set(toIndex, dest); } dest.coords.clear(); int oldLimit = src.coords.limit(); src.coords.clear(); for (int i = 0, len = dest.coords.capacity(); i < len; i++) { dest.coords.put(factor * src.coords.get()); } src.coords.limit(oldLimit); dest.coords.limit(oldLimit); if (vboInfo != null) { vboInfo.resizeTextureIds(this.texBuf.size()); } checkTextureCoordinates(); } /** * <code>getTextureBuffers</code> retrieves this geometry's texture * information contained within a float buffer array. * * @return the float buffers that contain this geometry's texture * information. */ public ArrayList<TexCoords> getTextureCoords() { return texBuf; } /** * <code>getTextureAsFloatBuffer</code> retrieves the texture buffer of a * given texture unit. * * @param textureUnit * the texture unit to check. * @return the texture coordinates at the given texture unit. */ public TexCoords getTextureCoords(int textureUnit) { if (texBuf == null) return null; if (textureUnit >= texBuf.size()) return null; return texBuf.get(textureUnit); } /** * <code>setTextureBuffer</code> sets this geometry's textures (position * 0) via a float buffer. This convenience method assumes we are setting * coordinates for texture unit 0 and that there are 2 coordinate values per * vertex. * * @param coords * the new coords for unit 0. */ public void setTextureCoords(TexCoords coords) { setTextureCoords(coords, 0); } /** * <code>setTextureBuffer</code> sets this geometry's textures at the * position given via a float buffer. This convenience method assumes that * there are 2 coordinate values per vertex. * * @param coords * the new coords. * @param unit * the texture unit we are providing coordinates for. */ public void setTextureCoords(TexCoords coords, int unit) { while (unit >= texBuf.size()) { texBuf.add(null); } texBuf.set(unit, coords); if (vboInfo != null) { vboInfo.resizeTextureIds(texBuf.size()); } checkTextureCoordinates(); } /** * Clears all vertex, normal, texture, and color buffers by setting them to * null. */ public void clearBuffers() { reconstruct(null, null, null, null); } /** * <code>updateBound</code> recalculates the bounding object assigned to * the geometry. This resets it parameters to adjust for any changes to the * vertex information. */ public void updateModelBound() { if (bound != null && getVertexBuffer() != null) { bound.computeFromPoints(getVertexBuffer()); updateWorldBound(); } } /** * <code>setModelBound</code> sets the bounding object for this geometry. * * @param modelBound * the bounding object for this geometry. */ public void setModelBound(BoundingVolume modelBound) { this.worldBound = null; this.bound = modelBound; } /** * <code>draw</code> prepares the geometry for rendering to the display. * The renderstate is set and the subclass is responsible for rendering the * actual data. * * @see com.jme.scene.Spatial#draw(com.jme.renderer.Renderer) * @param r * the renderer that displays to the context. */ @Override public void draw(Renderer r) { } /** * <code>updateWorldBound</code> updates the bounding volume that contains * this geometry. The location of the geometry is based on the location of * all this node's parents. * * @see com.jme.scene.Spatial#updateWorldBound() */ public void updateWorldBound() { if (bound != null) { worldBound = bound.transform(getWorldRotation(), getWorldTranslation(), getWorldScale(), worldBound); } } /** * <code>applyRenderState</code> determines if a particular render state * is set for this Geometry. If not, the default state will be used. */ @Override protected void applyRenderState(Stack[] states) { for (int x = 0; x < states.length; x++) { if (states[x].size() > 0) { this.states[x] = ((RenderState) states[x].peek()).extract( states[x], this); } else { this.states[x] = Renderer.defaultStateList[x]; } } } /** * sorts the lights based on distance to geometry bounding volume */ public void sortLights() { if (lightState != null && lightState.getLightList().size() > LightState.MAX_LIGHTS_ALLOWED) { LightUtil.sort(this, lightState.getLightList()); } } /** * <code>randomVertex</code> returns a random vertex from the list of * vertices set to this geometry. If there are no vertices set, null is * returned. * * @param fill * a Vector3f to fill with the results. If null, one is created. * It is more efficient to pass in a nonnull vector. * @return Vector3f a random vertex from the vertex list. Null is returned * if the vertex list is not set. */ public Vector3f randomVertex(Vector3f fill) { if (getVertexBuffer() == null) return null; int i = (int) (FastMath.nextRandomFloat() * getVertexCount()); if (fill == null) fill = new Vector3f(); BufferUtils.populateFromBuffer(fill, getVertexBuffer(), i); localToWorld(fill, fill); return fill; } /** * Check if this geom intersects the ray if yes add it to the results. * * @param ray * ray to check intersection with. The direction of the ray must * be normalized (length 1). * @param results * result list */ @Override public void findPick(Ray ray, PickResults results) { if (getWorldBound() == null || !isCollidable) { return; } if (getWorldBound().intersects(ray)) { // find the triangle that is being hit. // add this node and the triangle to the PickResults list. results.addPick(ray, this); } } /** * <code>setDefaultColor</code> sets the color to be used if no per vertex * color buffer is set. * * @param color */ public void setDefaultColor(ColorRGBA color) { defaultColor = color; } /** * <code>getWorldCoords</code> translates/rotates and scales the * coordinates of this Geometry to world coordinates based on its world * settings. The results are stored in the given FloatBuffer. If given * FloatBuffer is null, one is created. * * @param store * the FloatBuffer to store the results in, or null if you want * one created. * @return store or new FloatBuffer if store == null. */ public FloatBuffer getWorldCoords(FloatBuffer store) { if (store == null || store.capacity() != getVertexBuffer().limit()) { store = BufferUtils.createFloatBuffer(getVertexBuffer().limit()); if (store == null) { return null; } } // ensure vertex buffer starts at 0 for reading. getVertexBuffer().rewind(); for (int v = 0, vSize = store.capacity() / 3; v < vSize; v++) { BufferUtils.populateFromBuffer(compVect, getVertexBuffer(), v); localToWorld(compVect, compVect); BufferUtils.setInBuffer(compVect, store, v); } store.clear(); return store; } /** * <code>getWorldNormals</code> rotates the normals of this Geometry to * world normals based on its world settings. The results are stored in the * given FloatBuffer. If given FloatBuffer is null, one is created. * * @param store * the FloatBuffer to store the results in, or null if you want * one created. * @return store or new FloatBuffer if store == null. */ public FloatBuffer getWorldNormals(FloatBuffer store) { if (store == null || store.capacity() != getNormalBuffer().limit()) store = BufferUtils.clone(getNormalBuffer()); for (int v = 0, vSize = store.capacity() / 3; v < vSize; v++) { BufferUtils.populateFromBuffer(compVect, store, v); getWorldRotation().multLocal(compVect); BufferUtils.setInBuffer(compVect, store, v); } store.clear(); return store; } public int getDisplayListID() { return displayListID; } public void setDisplayListID(int displayListID) { this.displayListID = displayListID; } public void setTextureCoords(ArrayList<TexCoords> texBuf) { this.texBuf = texBuf; checkTextureCoordinates(); } public void clearTextureBuffers() { if (texBuf != null) { texBuf.clear(); } } public void addTextureCoordinates(TexCoords textureCoords) { addTextureCoordinates(textureCoords, 2); } public void addTextureCoordinates(TexCoords textureCoords, int coordSize) { if (texBuf != null) { texBuf.add(textureCoords); } checkTextureCoordinates(); } public void resizeTextureIds(int i) { vboInfo.resizeTextureIds(i); } protected void checkTextureCoordinates() { int max = TextureState.getNumberOfFragmentTexCoordUnits(); if (max == -1) return; // No texture state created yet. if (texBuf != null && texBuf.size() > max) { for (int i = max; i < texBuf.size(); i++) { if (texBuf.get(i) != null) { logger.warning("Texture coordinates set for unit " + i + ". Only " + max + " units are available."); } } } } public void scaleTextureCoordinates(int index, float factor) { scaleTextureCoordinates(index, new Vector2f(factor, factor)); } public void scaleTextureCoordinates(int index, Vector2f factor) { if (texBuf == null) return; if (index < 0 || index >= texBuf.size() || texBuf.get(index) == null) { return; } TexCoords tc = texBuf.get(index); for (int i = 0, len = tc.coords.limit() / 2; i < len; i++) { BufferUtils.multInBuffer(factor, tc.coords, i); } if (vboInfo != null) { vboInfo.resizeTextureIds(this.texBuf.size()); } } public boolean isCastsShadows() { return castsShadows; } public void setCastsShadows(boolean castsShadows) { this.castsShadows = castsShadows; } /** * <code>getNumberOfUnits</code> returns the number of texture units this * geometry is currently using. * * @return the number of texture units in use. */ public int getNumberOfUnits() { if (texBuf == null) return 0; return texBuf.size(); } @Override public void lockMeshes(Renderer r) { if (getDisplayListID() != -1) { logger.warning("This Geometry already has locked meshes." + "(Use unlockMeshes to clear)"); return; } updateRenderState(); lockedMode |= LOCKED_MESH_DATA; setDisplayListID(r.createDisplayList(this)); } @Override public void unlockMeshes(Renderer r) { lockedMode &= ~LOCKED_MESH_DATA; if (getDisplayListID() != -1) { r.releaseDisplayList(getDisplayListID()); setDisplayListID(-1); } } /** * Called just before renderer starts drawing this geometry. If it returns * false, we'll skip rendering. */ public boolean predraw(Renderer r) { return true; } /** * Called after renderer finishes drawing this geometry. */ public void postdraw(Renderer r) { } public void translatePoints(float x, float y, float z) { translatePoints(new Vector3f(x, y, z)); } public void translatePoints(Vector3f amount) { for (int x = 0; x < vertQuantity; x++) { BufferUtils.addInBuffer(amount, vertBuf, x); } } public void rotatePoints(Quaternion rotate) { Vector3f store = new Vector3f(); for (int x = 0; x < vertQuantity; x++) { BufferUtils.populateFromBuffer(store, vertBuf, x); rotate.mult(store, store); BufferUtils.setInBuffer(store, vertBuf, x); } } public void rotateNormals(Quaternion rotate) { Vector3f store = new Vector3f(); for (int x = 0; x < vertQuantity; x++) { BufferUtils.populateFromBuffer(store, normBuf, x); rotate.mult(store, store); BufferUtils.setInBuffer(store, normBuf, x); } } /** * <code>getDefaultColor</code> returns the color used if no per vertex * colors are specified. * * @return default color */ public ColorRGBA getDefaultColor() { return defaultColor; } public void write(JMEExporter e) throws IOException { super.write(e); OutputCapsule capsule = e.getCapsule(this); capsule.write(colorBuf, "colorBuf", null); capsule.write(normBuf, "normBuf", null); capsule.write(vertBuf, "vertBuf", null); capsule.writeSavableArrayList(texBuf, "texBuf", new ArrayList<TexCoords>(1)); capsule.write(enabled, "enabled", true); capsule.write(castsShadows, "castsShadows", true); capsule.write(bound, "bound", null); capsule.write(defaultColor, "defaultColor", ColorRGBA.white); } @SuppressWarnings("unchecked") public void read(JMEImporter e) throws IOException { super.read(e); InputCapsule capsule = e.getCapsule(this); colorBuf = capsule.readFloatBuffer("colorBuf", null); normBuf = capsule.readFloatBuffer("normBuf", null); vertBuf = capsule.readFloatBuffer("vertBuf", null); if (vertBuf != null) vertQuantity = vertBuf.limit() / 3; else vertQuantity = 0; texBuf = capsule.readSavableArrayList("texBuf", new ArrayList<TexCoords>(1)); checkTextureCoordinates(); enabled = capsule.readBoolean("enabled", true); castsShadows = capsule.readBoolean("castsShadows", true); bound = (BoundingVolume) capsule.readSavable("bound", null); if (bound != null) worldBound = bound.clone(null); defaultColor = (ColorRGBA) capsule.readSavable("defaultColor", ColorRGBA.white.clone()); } /** * <code>getModelBound</code> retrieves the bounding object that contains * the geometry's vertices. * * @return the bounding object for this geometry. */ public BoundingVolume getModelBound() { return bound; } public boolean hasDirtyVertices() { return hasDirtyVertices; } public void setHasDirtyVertices(boolean flag) { hasDirtyVertices = flag; } public void setTangentBuffer(FloatBuffer tangentBuf) { this.tangentBuf = tangentBuf; } public FloatBuffer getTangentBuffer() { return this.tangentBuf; } public void setBinormalBuffer(FloatBuffer binormalBuf) { this.binormalBuf = binormalBuf; } public FloatBuffer getBinormalBuffer() { return binormalBuf; } public void setLightState(LightState lightState) { this.lightState = lightState; } public LightState getLightState() { return lightState; } }
src/com/jme/scene/Geometry.java
/* * Copyright (c) 2003-2008 jMonkeyEngine * 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 'jMonkeyEngine' 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 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 com.jme.scene; import java.io.IOException; import java.io.Serializable; import java.nio.FloatBuffer; import java.util.ArrayList; import java.util.Stack; import java.util.logging.Logger; import com.jme.bounding.BoundingVolume; import com.jme.intersection.PickResults; import com.jme.math.FastMath; import com.jme.math.Quaternion; import com.jme.math.Ray; import com.jme.math.Vector2f; import com.jme.math.Vector3f; import com.jme.renderer.ColorRGBA; import com.jme.renderer.Renderer; import com.jme.scene.state.LightState; import com.jme.scene.state.LightUtil; import com.jme.scene.state.RenderState; import com.jme.scene.state.TextureState; import com.jme.util.export.InputCapsule; import com.jme.util.export.JMEExporter; import com.jme.util.export.JMEImporter; import com.jme.util.export.OutputCapsule; import com.jme.util.export.Savable; import com.jme.util.geom.BufferUtils; /** * <code>Geometry</code> defines a leaf node of the scene graph. The leaf node * contains the geometric data for rendering objects. It manages all rendering * information such as a collection of states and the data for a model. * Subclasses define what the model data is. * * @author Mark Powell * @author Joshua Slack * @version $Id: Geometry.java,v 1.113 2007/10/05 22:40:35 nca Exp $ */ public abstract class Geometry extends Spatial implements Serializable, Savable { private static final Logger logger = Logger.getLogger(Geometry.class.getName()); private static final long serialVersionUID = 1; /** The local bounds of this Geometry object. */ protected BoundingVolume bound; /** The number of vertexes in this geometry. */ protected int vertQuantity = 0; /** The geometry's per vertex color information. */ protected transient FloatBuffer colorBuf; /** The geometry's per vertex normal information. */ protected transient FloatBuffer normBuf; /** The geometry's vertex information. */ protected transient FloatBuffer vertBuf; /** The geometry's per Texture per vertex texture coordinate information. */ protected transient ArrayList<TexCoords> texBuf; /** The geometry's per vertex color information. */ protected transient FloatBuffer tangentBuf; /** The geometry's per vertex normal information. */ protected transient FloatBuffer binormalBuf; /** The geometry's per vertex fog buffer depth values */ protected transient FloatBuffer fogBuf; /** The geometry's VBO information. */ protected transient VBOInfo vboInfo; protected boolean enabled = true; protected boolean castsShadows = true; protected boolean hasDirtyVertices = false; /** * The compiled list of renderstates for this geometry, taking into account * ancestors' states - updated with updateRenderStates() */ public RenderState[] states = new RenderState[RenderState.RS_MAX_STATE]; private LightState lightState; protected ColorRGBA defaultColor = new ColorRGBA(ColorRGBA.white); /** * Non -1 values signal that drawing this scene should use the provided * display list instead of drawing from the buffers. */ protected int displayListID = -1; /** Static computation field */ protected static Vector3f compVect = new Vector3f(); /** * Empty Constructor to be used internally only. */ public Geometry() { super(); texBuf = new ArrayList<TexCoords>(1); texBuf.add(null); } /** * Constructor instantiates a new <code>Geometry</code> object. This is * the default object which has an empty vertex array. All other data is * null. * * @param name * the name of the scene element. This is required for * identification and comparision purposes. */ public Geometry(String name) { super(name); texBuf = new ArrayList<TexCoords>(1); texBuf.add(null); if (!(this instanceof SharedMesh)) reconstruct(null, null, null, null); } /** * Constructor creates a new <code>Geometry</code> object. During * instantiation the geometry is set including vertex, normal, color and * texture information. * * @param name * the name of the scene element. This is required for * identification and comparision purposes. * @param vertex * the points that make up the geometry. * @param normal * the normals of the geometry. * @param color * the color of each point of the geometry. * @param coords * the texture coordinates of the geometry (position 0.) */ public Geometry(String name, FloatBuffer vertex, FloatBuffer normal, FloatBuffer color, TexCoords coords) { super(name); texBuf = new ArrayList<TexCoords>(1); texBuf.add(null); reconstruct(vertex, normal, color, coords); } /** * returns the number of vertices contained in this geometry. */ @Override public int getVertexCount() { return vertQuantity; } public void setVertexCount(int vertQuantity) { this.vertQuantity = vertQuantity; } @Override public int getTriangleCount() { return 0; } /** * <code>reconstruct</code> reinitializes the geometry with new data. This * will reuse the geometry object. * * @param vertices * the new vertices to use. * @param normals * the new normals to use. * @param colors * the new colors to use. * @param coords * the new texture coordinates to use (position 0). */ public void reconstruct(FloatBuffer vertices, FloatBuffer normals, FloatBuffer colors, TexCoords coords) { if (vertices == null) setVertexCount(0); else setVertexCount(vertices.limit() / 3); setVertexBuffer(vertices); setNormalBuffer(normals); setColorBuffer(colors); if (getTextureCoords() == null) { setTextureCoords(new ArrayList<TexCoords>(1)); } clearTextureBuffers(); addTextureCoordinates(coords); if (getVBOInfo() != null) resizeTextureIds(1); } /** * Sets VBO info on this Geometry. * * @param info * the VBO info to set * @see VBOInfo */ public void setVBOInfo(VBOInfo info) { vboInfo = info; if (vboInfo != null) { vboInfo.resizeTextureIds(texBuf.size()); } } /** * @return VBO info object * @see VBOInfo */ public VBOInfo getVBOInfo() { return vboInfo; } /** * <code>setSolidColor</code> sets the color array of this geometry to a * single color. For greater efficiency, try setting the the ColorBuffer to * null and using DefaultColor instead. * * @param color * the color to set. */ public void setSolidColor(ColorRGBA color) { if (colorBuf == null) colorBuf = BufferUtils.createColorBuffer(vertQuantity); colorBuf.rewind(); for (int x = 0, cLength = colorBuf.remaining(); x < cLength; x += 4) { colorBuf.put(color.r); colorBuf.put(color.g); colorBuf.put(color.b); colorBuf.put(color.a); } colorBuf.flip(); } /** * Sets every color of this geometry's color array to a random color. */ public void setRandomColors() { if (colorBuf == null) colorBuf = BufferUtils.createColorBuffer(vertQuantity); for (int x = 0, cLength = colorBuf.limit(); x < cLength; x += 4) { colorBuf.put(FastMath.nextRandomFloat()); colorBuf.put(FastMath.nextRandomFloat()); colorBuf.put(FastMath.nextRandomFloat()); colorBuf.put(1); } colorBuf.flip(); } /** * <code>getVertexBuffer</code> returns the float buffer that contains * this geometry's vertex information. * * @return the float buffer that contains this geometry's vertex * information. */ public FloatBuffer getVertexBuffer() { return vertBuf; } /** * <code>setVertexBuffer</code> sets this geometry's vertices via a float * buffer consisting of groups of three floats: x,y and z. * * @param vertBuf * the new vertex buffer. */ public void setVertexBuffer(FloatBuffer vertBuf) { this.vertBuf = vertBuf; if (vertBuf != null) vertQuantity = vertBuf.limit() / 3; else vertQuantity = 0; } /** * Set the fog coordinates buffer. This should have the vertex count entries * * @param fogBuf The fog buffer to use in this geometry */ public void setFogCoordBuffer(FloatBuffer fogBuf) { this.fogBuf = fogBuf; } /** * The fog depth coord buffer * * @return The per vertex depth values for fog coordinates */ public FloatBuffer getFogBuffer() { return fogBuf; } /** * <code>getNormalBuffer</code> retrieves this geometry's normal * information as a float buffer. * * @return the float buffer containing the geometry information. */ public FloatBuffer getNormalBuffer() { return normBuf; } /** * <code>setNormalBuffer</code> sets this geometry's normals via a float * buffer consisting of groups of three floats: x,y and z. * * @param normBuf * the new normal buffer. */ public void setNormalBuffer(FloatBuffer normBuf) { this.normBuf = normBuf; } /** * <code>getColorBufferfer</code> retrieves the float buffer that contains * this geometry's color information. * * @return the buffer that contains this geometry's color information. */ public FloatBuffer getColorBuffer() { return colorBuf; } /** * <code>setColorBuffer</code> sets this geometry's colors via a float * buffer consisting of groups of four floats: r,g,b and a. * * @param colorBuf * the new color buffer. */ public void setColorBuffer(FloatBuffer colorBuf) { this.colorBuf = colorBuf; } /** * <code>copyTextureCoords</code> copys the texture coordinates of a given * texture unit to another location. If the texture unit is not valid, then * the coordinates are ignored. Coords are multiplied by the given factor. * * @param fromIndex * the coordinates to copy. * @param toIndex * the texture unit to set them to. * @param factor * a multiple to apply when copying */ public void copyTextureCoordinates(int fromIndex, int toIndex, float factor) { if (texBuf == null) return; if (fromIndex < 0 || fromIndex >= texBuf.size() || texBuf.get(fromIndex) == null) { return; } if (toIndex < 0 || toIndex == fromIndex) { return; } // make sure we are big enough while (toIndex >= texBuf.size()) { texBuf.add(null); } TexCoords dest = texBuf.get(toIndex); TexCoords src = texBuf.get(fromIndex); if (dest == null || dest.coords.capacity() != src.coords.limit()) { dest = new TexCoords(BufferUtils.createFloatBuffer(src.coords.capacity()), src.perVert); texBuf.set(toIndex, dest); } dest.coords.clear(); int oldLimit = src.coords.limit(); src.coords.clear(); for (int i = 0, len = dest.coords.capacity(); i < len; i++) { dest.coords.put(factor * src.coords.get()); } src.coords.limit(oldLimit); dest.coords.limit(oldLimit); if (vboInfo != null) { vboInfo.resizeTextureIds(this.texBuf.size()); } checkTextureCoordinates(); } /** * <code>getTextureBuffers</code> retrieves this geometry's texture * information contained within a float buffer array. * * @return the float buffers that contain this geometry's texture * information. */ public ArrayList<TexCoords> getTextureCoords() { return texBuf; } /** * <code>getTextureAsFloatBuffer</code> retrieves the texture buffer of a * given texture unit. * * @param textureUnit * the texture unit to check. * @return the texture coordinates at the given texture unit. */ public TexCoords getTextureCoords(int textureUnit) { if (texBuf == null) return null; if (textureUnit >= texBuf.size()) return null; return texBuf.get(textureUnit); } /** * <code>setTextureBuffer</code> sets this geometry's textures (position * 0) via a float buffer. This convenience method assumes we are setting * coordinates for texture unit 0 and that there are 2 coordinate values per * vertex. * * @param coords * the new coords for unit 0. */ public void setTextureCoords(TexCoords coords) { setTextureCoords(coords, 0); } /** * <code>setTextureBuffer</code> sets this geometry's textures at the * position given via a float buffer. This convenience method assumes that * there are 2 coordinate values per vertex. * * @param coords * the new coords. * @param unit * the texture unit we are providing coordinates for. */ public void setTextureCoords(TexCoords coords, int unit) { while (unit >= texBuf.size()) { texBuf.add(null); } texBuf.set(unit, coords); if (vboInfo != null) { vboInfo.resizeTextureIds(texBuf.size()); } checkTextureCoordinates(); } /** * Clears all vertex, normal, texture, and color buffers by setting them to * null. */ public void clearBuffers() { reconstruct(null, null, null, null); } /** * <code>updateBound</code> recalculates the bounding object assigned to * the geometry. This resets it parameters to adjust for any changes to the * vertex information. */ public void updateModelBound() { if (bound != null && getVertexBuffer() != null) { bound.computeFromPoints(getVertexBuffer()); updateWorldBound(); } } /** * <code>setModelBound</code> sets the bounding object for this geometry. * * @param modelBound * the bounding object for this geometry. */ public void setModelBound(BoundingVolume modelBound) { this.worldBound = null; this.bound = modelBound; } /** * <code>draw</code> prepares the geometry for rendering to the display. * The renderstate is set and the subclass is responsible for rendering the * actual data. * * @see com.jme.scene.Spatial#draw(com.jme.renderer.Renderer) * @param r * the renderer that displays to the context. */ @Override public void draw(Renderer r) { } /** * <code>updateWorldBound</code> updates the bounding volume that contains * this geometry. The location of the geometry is based on the location of * all this node's parents. * * @see com.jme.scene.Spatial#updateWorldBound() */ public void updateWorldBound() { if (bound != null) { worldBound = bound.transform(getWorldRotation(), getWorldTranslation(), getWorldScale(), worldBound); } } /** * <code>applyRenderState</code> determines if a particular render state * is set for this Geometry. If not, the default state will be used. */ @Override protected void applyRenderState(Stack[] states) { for (int x = 0; x < states.length; x++) { if (states[x].size() > 0) { this.states[x] = ((RenderState) states[x].peek()).extract( states[x], this); } else { this.states[x] = Renderer.defaultStateList[x]; } } } /** * sorts the lights based on distance to geometry bounding volume */ public void sortLights() { if (lightState != null && lightState.getLightList().size() > LightState.MAX_LIGHTS_ALLOWED) { LightUtil.sort(this, lightState.getLightList()); } } /** * <code>randomVertex</code> returns a random vertex from the list of * vertices set to this geometry. If there are no vertices set, null is * returned. * * @param fill * a Vector3f to fill with the results. If null, one is created. * It is more efficient to pass in a nonnull vector. * @return Vector3f a random vertex from the vertex list. Null is returned * if the vertex list is not set. */ public Vector3f randomVertex(Vector3f fill) { if (getVertexBuffer() == null) return null; int i = (int) (FastMath.nextRandomFloat() * getVertexCount()); if (fill == null) fill = new Vector3f(); BufferUtils.populateFromBuffer(fill, getVertexBuffer(), i); localToWorld(fill, fill); return fill; } /** * Check if this geom intersects the ray if yes add it to the results. * * @param ray * ray to check intersection with. The direction of the ray must * be normalized (length 1). * @param results * result list */ @Override public void findPick(Ray ray, PickResults results) { if (getWorldBound() == null || !isCollidable) { return; } if (getWorldBound().intersects(ray)) { // find the triangle that is being hit. // add this node and the triangle to the PickResults list. results.addPick(ray, this); } } /** * <code>setDefaultColor</code> sets the color to be used if no per vertex * color buffer is set. * * @param color */ public void setDefaultColor(ColorRGBA color) { defaultColor = color; } /** * <code>getWorldCoords</code> translates/rotates and scales the * coordinates of this Geometry to world coordinates based on its world * settings. The results are stored in the given FloatBuffer. If given * FloatBuffer is null, one is created. * * @param store * the FloatBuffer to store the results in, or null if you want * one created. * @return store or new FloatBuffer if store == null. */ public FloatBuffer getWorldCoords(FloatBuffer store) { if (store == null || store.capacity() != getVertexBuffer().limit()) { store = BufferUtils.clone(getVertexBuffer()); if (store == null) return null; } for (int v = 0, vSize = store.capacity() / 3; v < vSize; v++) { BufferUtils.populateFromBuffer(compVect, store, v); localToWorld(compVect, compVect); BufferUtils.setInBuffer(compVect, store, v); } store.clear(); return store; } /** * <code>getWorldNormals</code> rotates the normals of this Geometry to * world normals based on its world settings. The results are stored in the * given FloatBuffer. If given FloatBuffer is null, one is created. * * @param store * the FloatBuffer to store the results in, or null if you want * one created. * @return store or new FloatBuffer if store == null. */ public FloatBuffer getWorldNormals(FloatBuffer store) { if (store == null || store.capacity() != getNormalBuffer().limit()) store = BufferUtils.clone(getNormalBuffer()); for (int v = 0, vSize = store.capacity() / 3; v < vSize; v++) { BufferUtils.populateFromBuffer(compVect, store, v); getWorldRotation().multLocal(compVect); BufferUtils.setInBuffer(compVect, store, v); } store.clear(); return store; } public int getDisplayListID() { return displayListID; } public void setDisplayListID(int displayListID) { this.displayListID = displayListID; } public void setTextureCoords(ArrayList<TexCoords> texBuf) { this.texBuf = texBuf; checkTextureCoordinates(); } public void clearTextureBuffers() { if (texBuf != null) { texBuf.clear(); } } public void addTextureCoordinates(TexCoords textureCoords) { addTextureCoordinates(textureCoords, 2); } public void addTextureCoordinates(TexCoords textureCoords, int coordSize) { if (texBuf != null) { texBuf.add(textureCoords); } checkTextureCoordinates(); } public void resizeTextureIds(int i) { vboInfo.resizeTextureIds(i); } protected void checkTextureCoordinates() { int max = TextureState.getNumberOfFragmentTexCoordUnits(); if (max == -1) return; // No texture state created yet. if (texBuf != null && texBuf.size() > max) { for (int i = max; i < texBuf.size(); i++) { if (texBuf.get(i) != null) { logger.warning("Texture coordinates set for unit " + i + ". Only " + max + " units are available."); } } } } public void scaleTextureCoordinates(int index, float factor) { scaleTextureCoordinates(index, new Vector2f(factor, factor)); } public void scaleTextureCoordinates(int index, Vector2f factor) { if (texBuf == null) return; if (index < 0 || index >= texBuf.size() || texBuf.get(index) == null) { return; } TexCoords tc = texBuf.get(index); for (int i = 0, len = tc.coords.limit() / 2; i < len; i++) { BufferUtils.multInBuffer(factor, tc.coords, i); } if (vboInfo != null) { vboInfo.resizeTextureIds(this.texBuf.size()); } } public boolean isCastsShadows() { return castsShadows; } public void setCastsShadows(boolean castsShadows) { this.castsShadows = castsShadows; } /** * <code>getNumberOfUnits</code> returns the number of texture units this * geometry is currently using. * * @return the number of texture units in use. */ public int getNumberOfUnits() { if (texBuf == null) return 0; return texBuf.size(); } @Override public void lockMeshes(Renderer r) { if (getDisplayListID() != -1) { logger.warning("This Geometry already has locked meshes." + "(Use unlockMeshes to clear)"); return; } updateRenderState(); lockedMode |= LOCKED_MESH_DATA; setDisplayListID(r.createDisplayList(this)); } @Override public void unlockMeshes(Renderer r) { lockedMode &= ~LOCKED_MESH_DATA; if (getDisplayListID() != -1) { r.releaseDisplayList(getDisplayListID()); setDisplayListID(-1); } } /** * Called just before renderer starts drawing this geometry. If it returns * false, we'll skip rendering. */ public boolean predraw(Renderer r) { return true; } /** * Called after renderer finishes drawing this geometry. */ public void postdraw(Renderer r) { } public void translatePoints(float x, float y, float z) { translatePoints(new Vector3f(x, y, z)); } public void translatePoints(Vector3f amount) { for (int x = 0; x < vertQuantity; x++) { BufferUtils.addInBuffer(amount, vertBuf, x); } } public void rotatePoints(Quaternion rotate) { Vector3f store = new Vector3f(); for (int x = 0; x < vertQuantity; x++) { BufferUtils.populateFromBuffer(store, vertBuf, x); rotate.mult(store, store); BufferUtils.setInBuffer(store, vertBuf, x); } } public void rotateNormals(Quaternion rotate) { Vector3f store = new Vector3f(); for (int x = 0; x < vertQuantity; x++) { BufferUtils.populateFromBuffer(store, normBuf, x); rotate.mult(store, store); BufferUtils.setInBuffer(store, normBuf, x); } } /** * <code>getDefaultColor</code> returns the color used if no per vertex * colors are specified. * * @return default color */ public ColorRGBA getDefaultColor() { return defaultColor; } public void write(JMEExporter e) throws IOException { super.write(e); OutputCapsule capsule = e.getCapsule(this); capsule.write(colorBuf, "colorBuf", null); capsule.write(normBuf, "normBuf", null); capsule.write(vertBuf, "vertBuf", null); capsule.writeSavableArrayList(texBuf, "texBuf", new ArrayList<TexCoords>(1)); capsule.write(enabled, "enabled", true); capsule.write(castsShadows, "castsShadows", true); capsule.write(bound, "bound", null); capsule.write(defaultColor, "defaultColor", ColorRGBA.white); } @SuppressWarnings("unchecked") public void read(JMEImporter e) throws IOException { super.read(e); InputCapsule capsule = e.getCapsule(this); colorBuf = capsule.readFloatBuffer("colorBuf", null); normBuf = capsule.readFloatBuffer("normBuf", null); vertBuf = capsule.readFloatBuffer("vertBuf", null); if (vertBuf != null) vertQuantity = vertBuf.limit() / 3; else vertQuantity = 0; texBuf = capsule.readSavableArrayList("texBuf", new ArrayList<TexCoords>(1)); checkTextureCoordinates(); enabled = capsule.readBoolean("enabled", true); castsShadows = capsule.readBoolean("castsShadows", true); bound = (BoundingVolume) capsule.readSavable("bound", null); if (bound != null) worldBound = bound.clone(null); defaultColor = (ColorRGBA) capsule.readSavable("defaultColor", ColorRGBA.white.clone()); } /** * <code>getModelBound</code> retrieves the bounding object that contains * the geometry's vertices. * * @return the bounding object for this geometry. */ public BoundingVolume getModelBound() { return bound; } public boolean hasDirtyVertices() { return hasDirtyVertices; } public void setHasDirtyVertices(boolean flag) { hasDirtyVertices = flag; } public void setTangentBuffer(FloatBuffer tangentBuf) { this.tangentBuf = tangentBuf; } public FloatBuffer getTangentBuffer() { return this.tangentBuf; } public void setBinormalBuffer(FloatBuffer binormalBuf) { this.binormalBuf = binormalBuf; } public FloatBuffer getBinormalBuffer() { return binormalBuf; } public void setLightState(LightState lightState) { this.lightState = lightState; } public LightState getLightState() { return lightState; } }
Patch for issue #4 reported at jme's googlecode site. git-svn-id: 5afc437a751a4ff2ced778146f5faadda0b504ab@3972 75d07b2b-3a1a-0410-a2c5-0572b91ccdca
src/com/jme/scene/Geometry.java
Patch for issue #4 reported at jme's googlecode site.
Java
bsd-2-clause
230c584ca482256d17c222234fddcc2bf261a3c8
0
tempbottle/jodd,mohanaraosv/jodd,javachengwc/jodd,wsldl123292/jodd,mosoft521/jodd,mosoft521/jodd,Artemish/jodd,javachengwc/jodd,vilmospapp/jodd,wjw465150/jodd,vilmospapp/jodd,oblac/jodd,oblac/jodd,tempbottle/jodd,southwolf/jodd,mohanaraosv/jodd,tempbottle/jodd,vilmospapp/jodd,Artemish/jodd,Artemish/jodd,southwolf/jodd,mosoft521/jodd,oetting/jodd,southwolf/jodd,wsldl123292/jodd,tempbottle/jodd,mtakaki/jodd,wjw465150/jodd,oblac/jodd,mtakaki/jodd,southwolf/jodd,wsldl123292/jodd,vilmospapp/jodd,mohanaraosv/jodd,Artemish/jodd,vilmospapp/jodd,oetting/jodd,oetting/jodd,wsldl123292/jodd,wjw465150/jodd,oetting/jodd,mosoft521/jodd,javachengwc/jodd,mtakaki/jodd,mohanaraosv/jodd,javachengwc/jodd,mtakaki/jodd,oblac/jodd,Artemish/jodd,wjw465150/jodd
// Copyright (c) 2003-2010, Jodd Team (jodd.org). All Rights Reserved. package jodd.jtx.worker; import jodd.jtx.JtxTransactionManager; import jodd.jtx.JtxTransaction; import jodd.jtx.JtxTransactionMode; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Lean transaction worker helps dealing transactions when they were requested * in several places, usually in separated methods. This worker knows when requested transaction is * the same as current one, or completely new. It might be useful for aspects. */ public class LeanTransactionWorker { private static final Logger log = LoggerFactory.getLogger(LeanTransactionWorker.class); protected final JtxTransactionManager txManager; public LeanTransactionWorker(JtxTransactionManager txManager) { this.txManager = txManager; } /** * Returns transaction manager. */ public JtxTransactionManager getTransactionManager() { return txManager; } /** * Returns current transaction or <code>null</code> if there is no transaction at the moment. */ public JtxTransaction getCurrentTransaction() { return txManager.getTransaction(); } /** * Requests for transaction and returns non-null value <b>only</b> when new transaction * is created! When <code>null</code> is returned, transaction may be get by * {@link #getCurrentTransaction()}. * * @see jodd.jtx.JtxTransactionManager#requestTransaction(jodd.jtx.JtxTransactionMode) */ public JtxTransaction maybeRequestTransaction(JtxTransactionMode txMode, Object context) { if (txMode == null) { return null; } JtxTransaction currentTx = txManager.getTransaction(); JtxTransaction requestedTx = txManager.requestTransaction(txMode, context); if (currentTx == requestedTx) { return null; } return requestedTx; } /** * Commits transaction if created in the same level where this method is invoked. * Returns <code>true</code> if transaction was actually committed or <code>false</code> * if transaction was not created on this level. */ public boolean maybeCommitTransaction(JtxTransaction tx) { if (tx == null) { return false; } log.error("commit tx"); tx.commit(); return true; } /** * Rollbacks transaction if created in the same scope where this method is invoked. * If not, current transaction is marked for rollback. * Returns <code>true</code> if transaction was actually roll backed. */ public boolean markOrRollbackTransaction(JtxTransaction tx, Throwable cause) { log.error("rollback tx", cause); if (tx == null) { tx = getCurrentTransaction(); if (tx == null) { return false; } tx.setRollbackOnly(cause); return false; } tx.rollback(); return true; } }
mod/jodd-wot/src/jodd/jtx/worker/LeanTransactionWorker.java
// Copyright (c) 2003-2010, Jodd Team (jodd.org). All Rights Reserved. package jodd.jtx.worker; import jodd.jtx.JtxTransactionManager; import jodd.jtx.JtxTransaction; import jodd.jtx.JtxTransactionMode; /** * Lean transaction worker helps dealing transactions when they were requested * in several places, usually in separated methods. This worker knows when requested transaction is * the same as current one, or completely new. It might be useful for aspects. */ public class LeanTransactionWorker { protected final JtxTransactionManager txManager; public LeanTransactionWorker(JtxTransactionManager txManager) { this.txManager = txManager; } /** * Returns transaction manager. */ public JtxTransactionManager getTransactionManager() { return txManager; } /** * Returns current transaction or <code>null</code> if there is no transaction at the moment. */ public JtxTransaction getCurrentTransaction() { return txManager.getTransaction(); } /** * Requests for transaction and returns non-null value <b>only</b> when new transaction * is created! When <code>null</code> is returned, transaction may be get by * {@link #getCurrentTransaction()}. * * @see jodd.jtx.JtxTransactionManager#requestTransaction(jodd.jtx.JtxTransactionMode) */ public JtxTransaction maybeRequestTransaction(JtxTransactionMode txMode, Object context) { if (txMode == null) { return null; } JtxTransaction currentTx = txManager.getTransaction(); JtxTransaction requestedTx = txManager.requestTransaction(txMode, context); if (currentTx == requestedTx) { return null; } return requestedTx; } /** * Commits transaction if created in the same level where this method is invoked. * Returns <code>true</code> if transaction was actually committed or <code>false</code> * if transaction was not created on this level. */ public boolean maybeCommitTransaction(JtxTransaction tx) { if (tx == null) { return false; } tx.commit(); return true; } /** * Rollbacks transaction if created in the same scope where this method is invoked. * If not, current transaction is marked for rollback. * Returns <code>true</code> if transaction was actually roll backed. */ public boolean markOrRollbackTransaction(JtxTransaction tx, Throwable cause) { if (tx == null) { tx = getCurrentTransaction(); if (tx == null) { return false; } tx.setRollbackOnly(cause); return false; } tx.rollback(); return true; } }
added log! it was missing on rollback
mod/jodd-wot/src/jodd/jtx/worker/LeanTransactionWorker.java
added log! it was missing on rollback
Java
bsd-3-clause
1e20b03931f115798d52b4f41fdd6a341774ac26
0
svn2github/semanticvectors,svn2github/semanticvectors,svn2github/semanticvectors,svn2github/semanticvectors
/** Copyright (c) 2009, the SemanticVectors AUTHORS. 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 Pittsburgh 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 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 pitt.search.semanticvectors; import java.lang.Enum; import java.lang.IllegalArgumentException; import java.lang.reflect.Field; import java.util.Arrays; import java.util.logging.Logger; import pitt.search.semanticvectors.utils.VerbatimLogger; import pitt.search.semanticvectors.vectors.RealVector; import pitt.search.semanticvectors.vectors.RealVector.RealBindMethod; /** Imports must include the declarations of all enums used as flag values */ import pitt.search.semanticvectors.vectors.VectorType; import pitt.search.semanticvectors.CompoundVectorBuilder.VectorLookupSyntax; import pitt.search.semanticvectors.DocVectors.DocIndexingStrategy; import pitt.search.semanticvectors.ElementalVectorStore.ElementalGenerationMethod; import pitt.search.semanticvectors.LuceneUtils.TermWeight; import pitt.search.semanticvectors.Search.SearchType; import pitt.search.semanticvectors.TermTermVectorsFromLucene.PositionalMethod; import pitt.search.semanticvectors.VectorStoreUtils.VectorStoreFormat; /** * Class for representing and parsing command line flags into a configuration * instance to be passed to other components. * * Nearly all flags are configured once when an instance is created. Exceptions * are {@link #dimension()} and {#link vectortype()}, since these can be set * when a {@code VectorStore} is opened for reading. * * @author Dominic Widdows */ public class FlagConfig { private static final Logger logger = Logger.getLogger(FlagConfig.class.getCanonicalName()); private FlagConfig() { Field[] fields = FlagConfig.class.getDeclaredFields(); for (int q = 0; q < fields.length; q++) fields[q].setAccessible(true); } public String[] remainingArgs; // Add new command line flags here. By convention, please use lower case. private int dimension = 200; /** Dimension of semantic vector space, default value 200. Can be set when a {@code VectorStore} is opened. Recommended values are in the hundreds for {@link VectorType#REAL} and {@link VectorType#COMPLEX} and in the thousands for {@link VectorType#BINARY}, since binary dimensions are single bits. */ public int dimension() { return dimension; } /** Sets the {@link #dimension()}. */ public void setDimension(int dimension) { this.dimension = dimension; this.makeFlagsCompatible(); } private VectorType vectortype = VectorType.REAL; /** Ground field for vectors: real, binary or complex. Can be set when a {@code VectorStore} is opened. * Default value {@link VectorType#REAL}, corresponding to "-vectortype real". */ public VectorType vectortype() { return vectortype; } /** Sets the {@link #vectortype()}. */ public void setVectortype(VectorType vectortype) { this.vectortype = vectortype; this.makeFlagsCompatible(); } private RealBindMethod realbindmethod = RealBindMethod.CONVOLUTION; /** The binding method used for real vectors, see {@link RealVector#BIND_METHOD}. */ public RealBindMethod realbindmethod() { return realbindmethod; } private ElementalGenerationMethod elementalmethod = ElementalGenerationMethod.RANDOM; /** The method used for generating elemental vectors. */ public ElementalGenerationMethod elementalmethod() { return elementalmethod; } public int seedlength = 10; /** Number of nonzero entries in a sparse random vector, default value 10 except for * when {@link #vectortype()} is {@link VectorType#BINARY}, in which case default of * {@link #dimension()} / 2 is enforced by {@link #makeFlagsCompatible()}. */ public int seedlength() { return seedlength; } private int minfrequency = 0; /** Minimum frequency of a term for it to be indexed, default value 0. */ public int minfrequency() { return minfrequency; } private int maxfrequency = Integer.MAX_VALUE; /** Maximum frequency of a term for it to be indexed, default value {@link Integer#MAX_VALUE}. */ public int maxfrequency() { return maxfrequency; } private int maxnonalphabetchars = Integer.MAX_VALUE; /** Maximum number of nonalphabetic characters in a term for it to be indexed, default value {@link Integer#MAX_VALUE}. */ public int maxnonalphabetchars() { return maxnonalphabetchars; } private int mintermlength = 0; /** Minimum number of characters in a term */ public int mintermlength() { return mintermlength; } private boolean filteroutnumbers = false; /** If {@code true}, terms containing only numeric characters are filtered out during indexing, default value {@code true}. */ public boolean filteroutnumbers() { return filteroutnumbers; } private boolean bindnotreleasehack = false; /** !hack! bind instead of release when constructing queries **/ public boolean bindnotreleasehack() { return bindnotreleasehack; } private boolean hybridvectors = false; /** If {@code true}, the StringEdit Class will produce hybrid vectors where each term vector = orthographic vector + semantic vector (from -queryvectorfile), default value {@code false}. */ public boolean hybridvectors() { return hybridvectors; } private int numsearchresults = 20; /** Number of search results to return, default value 20. */ public int numsearchresults() { return numsearchresults; } private int treceval = -1; /** Output search results in trec_eval format, with query number = treceval**/ public int treceval() { return treceval;} private String jsonfile = ""; /** Output search results as graph representation of a connectivity matrix in JSON**/ public String jsonfile() { return jsonfile;} /** Pathfinder parameters - default q = (n-1), default r = + infinity**/ private int pathfinderQ = -1; public int pathfinderQ() { return pathfinderQ; } private double pathfinderR = Double.POSITIVE_INFINITY; public double pathfinderR() { return pathfinderR; } private double searchresultsminscore = -1.0; /** Search results with similarity scores below this value will not be included in search results, default value -1. */ public double searchresultsminscore() { return searchresultsminscore; } private int numclusters = 10; /** Number of clusters used in {@link ClusterResults} and {@link ClusterVectorStore}, default value 10. */ public int numclusters() { return numclusters; } private int trainingcycles = 0; /** Number of training cycles used for Reflective Random Indexing in {@link BuildIndex}. */ public int trainingcycles() { return trainingcycles; } private int windowradius = 5; /** Window radius used in {@link BuildPositionalIndex}, default value 5. */ public int windowradius() { return windowradius; } private SearchType searchtype = SearchType.SUM; /** Method used for combining and searching vectors, * default value {@link SearchType#SUM} corresponding to "-searchtype sum". */ public SearchType searchtype() { return searchtype; } private boolean fieldweight = false; /** Set to true if you want document vectors built from multiple fields to emphasize terms from shorter fields, default value {@code false}. */ public boolean fieldweight() { return fieldweight; } private TermWeight termweight = TermWeight.NONE; /** Term weighting used when constructing document vectors, default value {@link TermWeight#NONE} */ public LuceneUtils.TermWeight termweight() { return termweight; } private boolean porterstemmer = false; /** Tells {@link pitt.search.lucene.IndexFilePositions} to stem terms using Porter Stemmer, default value false. */ public boolean porterstemmer() { return porterstemmer; } private boolean usetermweightsinsearch = false; /** Tells search implementations to scale each comparison score by a term weight during search, default value false. */ public boolean usetermweightsinsearch() { return usetermweightsinsearch; } private boolean stdev = false; /** Score search results according to number of SDs above the mean across all search vectors, default false. */ public boolean stdev() { return stdev; } private boolean expandsearchspace = false; /** Generate bound products from each pairwise element of the search space, default false. * Expands the size of the space to n-squared. */ public boolean expandsearchspace() { return expandsearchspace; } private VectorStoreFormat indexfileformat = VectorStoreFormat.LUCENE; /** Format used for serializing / deserializing vectors from disk, default lucene. */ VectorStoreFormat indexfileformat() { return indexfileformat; } private String termvectorsfile = "termvectors"; /** File to which termvectors are written during indexing. */ public String termvectorsfile() { return termvectorsfile; } private String docvectorsfile = "docvectors"; /** File to which docvectors are written during indexing. */ public String docvectorsfile() { return docvectorsfile; } private String termtermvectorsfile = "termtermvectors"; /** File to which docvectors are written during indexing. */ public String termtermvectorsfile() { return termtermvectorsfile; } private String queryvectorfile = "termvectors"; /** Principal vector store for finding query vectors, default termvectors.bin. */ public String queryvectorfile() { return queryvectorfile; } private String searchvectorfile = ""; /** Vector store for searching. Defaults to being the same as {@link #queryvectorfile}. May be different from queryvectorfile e.g., when using terms to search for documents. */ public String searchvectorfile() { return searchvectorfile; } private String boundvectorfile = ""; /** Auxiliary vector store used when searching for boundproducts. Used only in some searchtypes. */ public String boundvectorfile() { return boundvectorfile; } private String elementalvectorfile = "elementalvectors"; /** Random elemental vectors, sometimes written out, and used (e.g.) in conjunction with permuted vector file. */ public String elementalvectorfile() { return elementalvectorfile; } private String semanticvectorfile = "semanticvectors"; /** Semantic vectors; used so far as a name in PSI. */ public String semanticvectorfile() { return semanticvectorfile; } private String predicatevectorfile = "predicatevectors"; /** Vectors used to represent predicates in PSI. */ public String predicatevectorfile() { return predicatevectorfile; } private String permutedvectorfile = "permtermvectors"; /** "Permuted term vectors, output by -positionalmethod permutation. */ public String permutedvectorfile() { return permutedvectorfile; } private String proximityvectorfile = "proxtermvectors"; /** "Permuted term vectors, output by -positionalmethod proximity. */ public String proximityvectorfile() { return proximityvectorfile; } private String directionalvectorfile ="drxntermvectors"; /** Permuted term vectors, output by -positionalmethod directional. */ public String directionalvectorfile() { return directionalvectorfile; } private String permplustermvectorfile ="permplustermvectors"; /** "Permuted term vectors, output by -positionalmethod permutationplusbasic. */ public String permplustermvectorfile() { return permplustermvectorfile; } private PositionalMethod positionalmethod = PositionalMethod.BASIC; /** Method used for positional indexing. */ public PositionalMethod positionalmethod() { return positionalmethod; } private String stoplistfile = ""; /** Path to file containing stopwords, one word per line, no default value. */ public String stoplistfile() { return stoplistfile; } private String startlistfile = ""; /** Path to file containing startwords, to be indexed always, no default value. */ public String getStartlistfile() { return startlistfile; } private String luceneindexpath = ""; /** Path to a Lucene index. Must contain term position information for positional applications, * See {@link BuildPositionalIndex}. */ public String luceneindexpath() { return luceneindexpath; } private String initialtermvectors = ""; /** If set, use the vectors in this file for initialization instead of new random vectors. */ public String initialtermvectors() { return initialtermvectors; } private String initialdocumentvectors = ""; /** If set, use the vectors in this file for initialization instead of new random vectors. */ public String initialdocumentvectors() { return initialdocumentvectors; } private DocIndexingStrategy docindexing = DocIndexingStrategy.INMEMORY; /** Memory management method used for indexing documents. */ public DocIndexingStrategy docindexing() { return docindexing; } private VectorLookupSyntax vectorlookupsyntax = VectorLookupSyntax.EXACTMATCH; /** Method used for looking up vectors in a vector store, default value {@link VectorLookupSyntax#EXACTMATCH}. */ public VectorLookupSyntax vectorlookupsyntax() { return vectorlookupsyntax; } private boolean matchcase = false; /** If true, matching of query terms is case-sensitive; otherwise case-insensitive, default false. */ public boolean matchcase() { return matchcase; } private String batchcompareseparator = "\\|"; /** Separator for documents on a single line in batch comparison mode, default '\\|' (as a regular expression for '|'). */ public String batchcompareseparator() { return batchcompareseparator; } private boolean suppressnegatedqueries = false; /** If true, suppress checking for the query negation token which indicates subsequent terms are to be negated when comparing terms, default false. * If this is set to {@code true}, all terms are treated as positive. */ public boolean suppressnegatedqueries() { return suppressnegatedqueries; } private String[] contentsfields = {"contents"}; /** Fields to be indexed for their contents, e.g., "title,description,notes", default "contents". */ public String[] contentsfields() { return contentsfields; } /** Set contentsfields (e.g. to specify for TermFilter **/ public void setContentsfields(String[] contentsfields) { this.contentsfields = contentsfields; } private String docidfield = "path"; /** Field used by Lucene to record the identifier for each document, default "path". */ public String docidfield() { return docidfield; } /** * Parse flags from a single string. Presumes that string contains only command line flags. */ public static FlagConfig parseFlagsFromString(String header) { String[] args = header.split("\\s"); return getFlagConfig(args); } /** * Parse command line flags and create public data structures for accessing them. * @param args * @return trimmed list of arguments with command line flags consumed */ // This implementation is linear in the number of flags available // and the number of command line arguments given. This is quadratic // and so inefficient, but in practice we only have to do it once // per command so it's probably negligible. public static FlagConfig getFlagConfig(String[] args) throws IllegalArgumentException { FlagConfig flagConfig = new FlagConfig(); if (args == null || args.length == 0) { flagConfig.remainingArgs = new String[0]; return flagConfig; } int argc = 0; while (args[argc].charAt(0) == '-') { String flagName = args[argc]; // Ignore trivial flags (without raising an error). if (flagName.equals("-")) continue; // Strip off initial "-" repeatedly to get desired flag name. while (flagName.charAt(0) == '-') { flagName = flagName.substring(1, flagName.length()); } try { Field field = FlagConfig.class.getDeclaredField(flagName); // Parse String arguments. if (field.getType().getName().equals("java.lang.String")) { String flagValue; try { flagValue = args[argc + 1]; } catch (ArrayIndexOutOfBoundsException e) { throw new IllegalArgumentException("option -" + flagName + " requires an argument"); } field.set(flagConfig, flagValue); argc += 2; // Parse String[] arguments, presuming they are comma-separated. // String[] arguments do not currently support fixed Value lists. } else if (field.getType().getName().equals("[Ljava.lang.String;")) { // All string values are lowercased. String flagValue; try { flagValue = args[argc + 1].toLowerCase(); } catch (ArrayIndexOutOfBoundsException e) { throw new IllegalArgumentException("option -" + flagName + " requires an argument"); } field.set(flagConfig, flagValue.split(",")); argc += 2; } else if (field.getType().getName().equals("int")) { // Parse int arguments. try { field.setInt(flagConfig, Integer.parseInt(args[argc + 1])); } catch (ArrayIndexOutOfBoundsException e) { throw new IllegalArgumentException("option -" + flagName + " requires an argument"); } argc += 2; } else if (field.getType().getName().equals("double")) { // Parse double arguments. try { field.setDouble(flagConfig, Double.parseDouble(args[argc + 1])); } catch (ArrayIndexOutOfBoundsException e) { throw new IllegalArgumentException("option -" + flagName + " requires an argument"); } argc += 2; } else if (field.getType().isEnum()) { // Parse enum arguments. try { @SuppressWarnings({ "rawtypes", "unchecked" }) Class<Enum> className = (Class<Enum>) field.getType(); try { field.set(flagConfig, Enum.valueOf(className, args[argc + 1].toUpperCase())); } catch (IllegalArgumentException e) { throw new IllegalArgumentException(String.format( e.getMessage() + "\nAccepted values for '-%s' are:\n%s%n", field.getName(), Arrays.asList(className.getEnumConstants()), e)); } } catch (ArrayIndexOutOfBoundsException e) { throw new IllegalArgumentException("option -" + flagName + " requires an argument"); } argc += 2; } else if (field.getType().getName().equals("boolean")) { // Parse boolean arguments. field.setBoolean(flagConfig, true); ++argc; } else { logger.warning("No support for fields of type: " + field.getType().getName()); argc += 2; } } catch (NoSuchFieldException e) { throw new IllegalArgumentException("Command line flag not defined: " + flagName); } catch (IllegalAccessException e) { logger.warning("Must be able to access all fields publicly, including: " + flagName); e.printStackTrace(); } if (argc >= args.length) { logger.fine("Consumed all command line input while parsing flags"); flagConfig.makeFlagsCompatible(); return flagConfig; } } // Enforce constraints between flags. flagConfig.makeFlagsCompatible(); // No more command line flags to parse. Trim args[] list and return. flagConfig.remainingArgs = new String[args.length - argc]; for (int i = 0; i < args.length - argc; ++i) { flagConfig.remainingArgs[i] = args[argc + i]; } return flagConfig; } public static void mergeWriteableFlagsFromString(String source, FlagConfig target) { FlagConfig sourceConfig = FlagConfig.parseFlagsFromString(source); mergeWriteableFlags(sourceConfig, target); } /** * Sets dimension and vectortype of target to be the same as that of source. */ public static void mergeWriteableFlags(FlagConfig source, FlagConfig target) { if (target.dimension != source.dimension) { VerbatimLogger.info("Setting dimension of target config to: " + source.dimension + "\n"); target.dimension = source.dimension; } if (target.vectortype != source.vectortype) { VerbatimLogger.info("Setting vectortype of target config to: " + source.vectortype + "\n"); target.vectortype = source.vectortype; } target.makeFlagsCompatible(); } /** * Checks some interaction between flags, and fixes them up to make them compatible. * * <br/> * In practice, this means: * <ul><li>If {@link #vectortype()} is {@code binary}, {@link #dimension()} is a multiple of 64, * or is increased to be become a multiple of 64. {@link #seedlength()} is set to be half this * number.</li> * <li>Setting {@link #searchvectorfile()} to {@link #queryvectorfile()} unless explicitly set otherwise.</li> * <li>Setting {@link RealVector#setBindType} if directed (this is something of a hack).</li> * </ul> */ private void makeFlagsCompatible() { if (vectortype == VectorType.BINARY) { // Impose "multiple-of-64" constraint, to facilitate permutation of 64-bit chunks. if (dimension % 64 != 0) { dimension = (1 + (dimension / 64)) * 64; logger.fine("For performance reasons, dimensions for binary vectors must be a mutliple " + "of 64. Flags.dimension set to: " + dimension + "."); } // Impose "balanced binary vectors" constraint, to facilitate reasonable voting. if (seedlength != dimension / 2) { seedlength = dimension / 2; logger.fine("Binary vectors must be generated with a balanced number of zeros and ones." + " FlagConfig.seedlength set to: " + seedlength + "."); } } if (searchvectorfile.isEmpty()) searchvectorfile = queryvectorfile; // This is a potentially dangerous pattern! An alternative would be to make this setting // part of each real vector, as with complex Modes. But they aren't so nice either. // Let's avoid getting too committed to either approach and refactor at will. // dwiddows, 2013-09-27. if (vectortype == VectorType.REAL && realbindmethod == RealVector.RealBindMethod.PERMUTATION) { RealVector.setBindType(RealVector.RealBindMethod.PERMUTATION); } } //utility method to allow control of this option without //reconfiguring a FlagConfig public void setExpandsearchspace(boolean b) { // TODO Auto-generated method stub this.expandsearchspace = b; } }
src/main/java/pitt/search/semanticvectors/FlagConfig.java
/** Copyright (c) 2009, the SemanticVectors AUTHORS. 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 Pittsburgh 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 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 pitt.search.semanticvectors; import java.lang.Enum; import java.lang.IllegalArgumentException; import java.lang.reflect.Field; import java.util.Arrays; import java.util.logging.Logger; import pitt.search.semanticvectors.utils.VerbatimLogger; import pitt.search.semanticvectors.vectors.RealVector; import pitt.search.semanticvectors.vectors.RealVector.RealBindMethod; /** Imports must include the declarations of all enums used as flag values */ import pitt.search.semanticvectors.vectors.VectorType; import pitt.search.semanticvectors.CompoundVectorBuilder.VectorLookupSyntax; import pitt.search.semanticvectors.DocVectors.DocIndexingStrategy; import pitt.search.semanticvectors.ElementalVectorStore.ElementalGenerationMethod; import pitt.search.semanticvectors.LuceneUtils.TermWeight; import pitt.search.semanticvectors.Search.SearchType; import pitt.search.semanticvectors.TermTermVectorsFromLucene.PositionalMethod; import pitt.search.semanticvectors.VectorStoreUtils.VectorStoreFormat; /** * Class for representing and parsing command line flags into a configuration * instance to be passed to other components. * * Nearly all flags are configured once when an instance is created. Exceptions * are {@link #dimension()} and {#link vectortype()}, since these can be set * when a {@code VectorStore} is opened for reading. * * @author Dominic Widdows */ public class FlagConfig { private static final Logger logger = Logger.getLogger(FlagConfig.class.getCanonicalName()); private FlagConfig() { Field[] fields = FlagConfig.class.getDeclaredFields(); for (int q = 0; q < fields.length; q++) fields[q].setAccessible(true); } public String[] remainingArgs; // Add new command line flags here. By convention, please use lower case. private int dimension = 200; /** Dimension of semantic vector space, default value 200. Can be set when a {@code VectorStore} is opened. Recommended values are in the hundreds for {@link VectorType#REAL} and {@link VectorType#COMPLEX} and in the thousands for {@link VectorType#BINARY}, since binary dimensions are single bits. */ public int dimension() { return dimension; } /** Sets the {@link #dimension()}. */ public void setDimension(int dimension) { this.dimension = dimension; this.makeFlagsCompatible(); } private VectorType vectortype = VectorType.REAL; /** Ground field for vectors: real, binary or complex. Can be set when a {@code VectorStore} is opened. * Default value {@link VectorType#REAL}, corresponding to "-vectortype real". */ public VectorType vectortype() { return vectortype; } /** Sets the {@link #vectortype()}. */ public void setVectortype(VectorType vectortype) { this.vectortype = vectortype; this.makeFlagsCompatible(); } private RealBindMethod realbindmethod = RealBindMethod.CONVOLUTION; /** The binding method used for real vectors, see {@link RealVector#BIND_METHOD}. */ public RealBindMethod realbindmethod() { return realbindmethod; } private ElementalGenerationMethod elementalmethod = ElementalGenerationMethod.RANDOM; /** The method used for generating elemental vectors. */ public ElementalGenerationMethod elementalmethod() { return elementalmethod; } public int seedlength = 10; /** Number of nonzero entries in a sparse random vector, default value 10 except for * when {@link #vectortype()} is {@link VectorType#BINARY}, in which case default of * {@link #dimension()} / 2 is enforced by {@link #makeFlagsCompatible()}. */ public int seedlength() { return seedlength; } private int minfrequency = 0; /** Minimum frequency of a term for it to be indexed, default value 0. */ public int minfrequency() { return minfrequency; } private int maxfrequency = Integer.MAX_VALUE; /** Maximum frequency of a term for it to be indexed, default value {@link Integer#MAX_VALUE}. */ public int maxfrequency() { return maxfrequency; } private int maxnonalphabetchars = Integer.MAX_VALUE; /** Maximum number of nonalphabetic characters in a term for it to be indexed, default value {@link Integer#MAX_VALUE}. */ public int maxnonalphabetchars() { return maxnonalphabetchars; } private int mintermlength = 0; /** Minimum number of characters in a term */ public int mintermlength() { return mintermlength; } private boolean filteroutnumbers = false; /** If {@code true}, terms containing only numeric characters are filtered out during indexing, default value {@code true}. */ public boolean filteroutnumbers() { return filteroutnumbers; } private boolean bindnotreleasehack = false; /** !hack! bind instead of release when constructing queries **/ public boolean bindnotreleasehack() { return bindnotreleasehack; } private boolean hybridvectors = false; /** If {@code true}, the StringEdit Class will produce hybrid vectors where each term vector = orthographic vector + semantic vector (from -queryvectorfile), default value {@code false}. */ public boolean hybridvectors() { return hybridvectors; } private int numsearchresults = 20; /** Number of search results to return, default value 20. */ public int numsearchresults() { return numsearchresults; } private int treceval = -1; /** Output search results in trec_eval format, with query number = treceval**/ public int treceval() { return treceval;} private String jsonfile = ""; /** Output search results as graph representation of a connectivity matrix in JSON**/ public String jsonfile() { return jsonfile;} /** Pathfinder parameters - default q = (n-1), default r = + infinity**/ private int pathfinderQ = -1; public int pathfinderQ() { return pathfinderQ; } private double pathfinderR = Double.POSITIVE_INFINITY; public double pathfinderR() { return pathfinderR; } private double searchresultsminscore = -1.0; /** Search results with similarity scores below this value will not be included in search results, default value -1. */ public double searchresultsminscore() { return searchresultsminscore; } private int numclusters = 10; /** Number of clusters used in {@link ClusterResults} and {@link ClusterVectorStore}, default value 10. */ public int numclusters() { return numclusters; } private int trainingcycles = 0; /** Number of training cycles used for Reflective Random Indexing in {@link BuildIndex}. */ public int trainingcycles() { return trainingcycles; } private int windowradius = 5; /** Window radius used in {@link BuildPositionalIndex}, default value 5. */ public int windowradius() { return windowradius; } private SearchType searchtype = SearchType.SUM; /** Method used for combining and searching vectors, * default value {@link SearchType#SUM} corresponding to "-searchtype sum". */ public SearchType searchtype() { return searchtype; } private boolean fieldweight = false; /** Set to true if you want document vectors built from multiple fields to emphasize terms from shorter fields, default value {@code false}. */ public boolean fieldweight() { return fieldweight; } private TermWeight termweight = TermWeight.NONE; /** Term weighting used when constructing document vectors, default value {@link TermWeight#NONE} */ public LuceneUtils.TermWeight termweight() { return termweight; } private boolean porterstemmer = false; /** Tells {@link pitt.search.lucene.IndexFilePositions} to stem terms using Porter Stemmer, default value false. */ public boolean porterstemmer() { return porterstemmer; } private boolean usetermweightsinsearch = false; /** Tells search implementations to scale each comparison score by a term weight during search, default value false. */ public boolean usetermweightsinsearch() { return usetermweightsinsearch; } private boolean stdev = false; /** Score search results according to number of SDs above the mean across all search vectors, default false. */ public boolean stdev() { return stdev; } private boolean expandsearchspace = false; /** Generate bound products from each pairwise element of the search space, default false. * Expands the size of the space to n-squared. */ public boolean expandsearchspace() { return expandsearchspace; } private VectorStoreFormat indexfileformat = VectorStoreFormat.LUCENE; /** Format used for serializing / deserializing vectors from disk, default lucene. */ VectorStoreFormat indexfileformat() { return indexfileformat; } private String termvectorsfile = "termvectors"; /** File to which termvectors are written during indexing. */ public String termvectorsfile() { return termvectorsfile; } private String docvectorsfile = "docvectors"; /** File to which docvectors are written during indexing. */ public String docvectorsfile() { return docvectorsfile; } private String termtermvectorsfile = "termtermvectors"; /** File to which docvectors are written during indexing. */ public String termtermvectorsfile() { return termtermvectorsfile; } private String queryvectorfile = "termvectors"; /** Principal vector store for finding query vectors, default termvectors.bin. */ public String queryvectorfile() { return queryvectorfile; } private String searchvectorfile = ""; /** Vector store for searching. Defaults to being the same as {@link #queryvectorfile}. May be different from queryvectorfile e.g., when using terms to search for documents. */ public String searchvectorfile() { return searchvectorfile; } private String boundvectorfile = ""; /** Auxiliary vector store used when searching for boundproducts. Used only in some searchtypes. */ public String boundvectorfile() { return boundvectorfile; } private String elementalvectorfile = "elementalvectors"; /** Random elemental vectors, sometimes written out, and used (e.g.) in conjunction with permuted vector file. */ public String elementalvectorfile() { return elementalvectorfile; } private String semanticvectorfile = "semanticvectors"; /** Semantic vectors; used so far as a name in PSI. */ public String semanticvectorfile() { return semanticvectorfile; } private String predicatevectorfile = "predicatevectors"; /** Vectors used to represent predicates in PSI. */ public String predicatevectorfile() { return predicatevectorfile; } private String permutedvectorfile = "permtermvectors"; /** "Permuted term vectors, output by -positionalmethod permutation. */ public String permutedvectorfile() { return permutedvectorfile; } private String proximityvectorfile = "proxtermvectors"; /** "Permuted term vectors, output by -positionalmethod permutation. */ public String proximityvectorfile() { return proximityvectorfile; } private String directionalvectorfile ="drxntermvectors"; /** Permuted term vectors, output by -positionalmethod directional. */ public String directionalvectorfile() { return directionalvectorfile; } private String permplustermvectorfile ="permplustermvectors"; /** "Permuted term vectors, output by -positionalmethod permutationplusbasic. */ public String permplustermvectorfile() { return permplustermvectorfile; } private PositionalMethod positionalmethod = PositionalMethod.BASIC; /** Method used for positional indexing. */ public PositionalMethod positionalmethod() { return positionalmethod; } private String stoplistfile = ""; /** Path to file containing stopwords, one word per line, no default value. */ public String stoplistfile() { return stoplistfile; } private String startlistfile = ""; /** Path to file containing startwords, to be indexed always, no default value. */ public String getStartlistfile() { return startlistfile; } private String luceneindexpath = ""; /** Path to a Lucene index. Must contain term position information for positional applications, * See {@link BuildPositionalIndex}. */ public String luceneindexpath() { return luceneindexpath; } private String initialtermvectors = ""; /** If set, use the vectors in this file for initialization instead of new random vectors. */ public String initialtermvectors() { return initialtermvectors; } private String initialdocumentvectors = ""; /** If set, use the vectors in this file for initialization instead of new random vectors. */ public String initialdocumentvectors() { return initialdocumentvectors; } private DocIndexingStrategy docindexing = DocIndexingStrategy.INMEMORY; /** Memory management method used for indexing documents. */ public DocIndexingStrategy docindexing() { return docindexing; } private VectorLookupSyntax vectorlookupsyntax = VectorLookupSyntax.EXACTMATCH; /** Method used for looking up vectors in a vector store, default value {@link VectorLookupSyntax#EXACTMATCH}. */ public VectorLookupSyntax vectorlookupsyntax() { return vectorlookupsyntax; } private boolean matchcase = false; /** If true, matching of query terms is case-sensitive; otherwise case-insensitive, default false. */ public boolean matchcase() { return matchcase; } private String batchcompareseparator = "\\|"; /** Separator for documents on a single line in batch comparison mode, default '\\|' (as a regular expression for '|'). */ public String batchcompareseparator() { return batchcompareseparator; } private boolean suppressnegatedqueries = false; /** If true, suppress checking for the query negation token which indicates subsequent terms are to be negated when comparing terms, default false. * If this is set to {@code true}, all terms are treated as positive. */ public boolean suppressnegatedqueries() { return suppressnegatedqueries; } private String[] contentsfields = {"contents"}; /** Fields to be indexed for their contents, e.g., "title,description,notes", default "contents". */ public String[] contentsfields() { return contentsfields; } /** Set contentsfields (e.g. to specify for TermFilter **/ public void setContentsfields(String[] contentsfields) { this.contentsfields = contentsfields; } private String docidfield = "path"; /** Field used by Lucene to record the identifier for each document, default "path". */ public String docidfield() { return docidfield; } /** * Parse flags from a single string. Presumes that string contains only command line flags. */ public static FlagConfig parseFlagsFromString(String header) { String[] args = header.split("\\s"); return getFlagConfig(args); } /** * Parse command line flags and create public data structures for accessing them. * @param args * @return trimmed list of arguments with command line flags consumed */ // This implementation is linear in the number of flags available // and the number of command line arguments given. This is quadratic // and so inefficient, but in practice we only have to do it once // per command so it's probably negligible. public static FlagConfig getFlagConfig(String[] args) throws IllegalArgumentException { FlagConfig flagConfig = new FlagConfig(); if (args == null || args.length == 0) { flagConfig.remainingArgs = new String[0]; return flagConfig; } int argc = 0; while (args[argc].charAt(0) == '-') { String flagName = args[argc]; // Ignore trivial flags (without raising an error). if (flagName.equals("-")) continue; // Strip off initial "-" repeatedly to get desired flag name. while (flagName.charAt(0) == '-') { flagName = flagName.substring(1, flagName.length()); } try { Field field = FlagConfig.class.getDeclaredField(flagName); // Parse String arguments. if (field.getType().getName().equals("java.lang.String")) { String flagValue; try { flagValue = args[argc + 1]; } catch (ArrayIndexOutOfBoundsException e) { throw new IllegalArgumentException("option -" + flagName + " requires an argument"); } field.set(flagConfig, flagValue); argc += 2; // Parse String[] arguments, presuming they are comma-separated. // String[] arguments do not currently support fixed Value lists. } else if (field.getType().getName().equals("[Ljava.lang.String;")) { // All string values are lowercased. String flagValue; try { flagValue = args[argc + 1].toLowerCase(); } catch (ArrayIndexOutOfBoundsException e) { throw new IllegalArgumentException("option -" + flagName + " requires an argument"); } field.set(flagConfig, flagValue.split(",")); argc += 2; } else if (field.getType().getName().equals("int")) { // Parse int arguments. try { field.setInt(flagConfig, Integer.parseInt(args[argc + 1])); } catch (ArrayIndexOutOfBoundsException e) { throw new IllegalArgumentException("option -" + flagName + " requires an argument"); } argc += 2; } else if (field.getType().getName().equals("double")) { // Parse double arguments. try { field.setDouble(flagConfig, Double.parseDouble(args[argc + 1])); } catch (ArrayIndexOutOfBoundsException e) { throw new IllegalArgumentException("option -" + flagName + " requires an argument"); } argc += 2; } else if (field.getType().isEnum()) { // Parse enum arguments. try { @SuppressWarnings({ "rawtypes", "unchecked" }) Class<Enum> className = (Class<Enum>) field.getType(); try { field.set(flagConfig, Enum.valueOf(className, args[argc + 1].toUpperCase())); } catch (IllegalArgumentException e) { throw new IllegalArgumentException(String.format( e.getMessage() + "\nAccepted values for '-%s' are:\n%s%n", field.getName(), Arrays.asList(className.getEnumConstants()), e)); } } catch (ArrayIndexOutOfBoundsException e) { throw new IllegalArgumentException("option -" + flagName + " requires an argument"); } argc += 2; } else if (field.getType().getName().equals("boolean")) { // Parse boolean arguments. field.setBoolean(flagConfig, true); ++argc; } else { logger.warning("No support for fields of type: " + field.getType().getName()); argc += 2; } } catch (NoSuchFieldException e) { throw new IllegalArgumentException("Command line flag not defined: " + flagName); } catch (IllegalAccessException e) { logger.warning("Must be able to access all fields publicly, including: " + flagName); e.printStackTrace(); } if (argc >= args.length) { logger.fine("Consumed all command line input while parsing flags"); flagConfig.makeFlagsCompatible(); return flagConfig; } } // Enforce constraints between flags. flagConfig.makeFlagsCompatible(); // No more command line flags to parse. Trim args[] list and return. flagConfig.remainingArgs = new String[args.length - argc]; for (int i = 0; i < args.length - argc; ++i) { flagConfig.remainingArgs[i] = args[argc + i]; } return flagConfig; } public static void mergeWriteableFlagsFromString(String source, FlagConfig target) { FlagConfig sourceConfig = FlagConfig.parseFlagsFromString(source); mergeWriteableFlags(sourceConfig, target); } /** * Sets dimension and vectortype of target to be the same as that of source. */ public static void mergeWriteableFlags(FlagConfig source, FlagConfig target) { if (target.dimension != source.dimension) { VerbatimLogger.info("Setting dimension of target config to: " + source.dimension + "\n"); target.dimension = source.dimension; } if (target.vectortype != source.vectortype) { VerbatimLogger.info("Setting vectortype of target config to: " + source.vectortype + "\n"); target.vectortype = source.vectortype; } target.makeFlagsCompatible(); } /** * Checks some interaction between flags, and fixes them up to make them compatible. * * <br/> * In practice, this means: * <ul><li>If {@link #vectortype()} is {@code binary}, {@link #dimension()} is a multiple of 64, * or is increased to be become a multiple of 64. {@link #seedlength()} is set to be half this * number.</li> * <li>Setting {@link #searchvectorfile()} to {@link #queryvectorfile()} unless explicitly set otherwise.</li> * <li>Setting {@link RealVector#setBindType} if directed (this is something of a hack).</li> * </ul> */ private void makeFlagsCompatible() { if (vectortype == VectorType.BINARY) { // Impose "multiple-of-64" constraint, to facilitate permutation of 64-bit chunks. if (dimension % 64 != 0) { dimension = (1 + (dimension / 64)) * 64; logger.fine("For performance reasons, dimensions for binary vectors must be a mutliple " + "of 64. Flags.dimension set to: " + dimension + "."); } // Impose "balanced binary vectors" constraint, to facilitate reasonable voting. if (seedlength != dimension / 2) { seedlength = dimension / 2; logger.fine("Binary vectors must be generated with a balanced number of zeros and ones." + " FlagConfig.seedlength set to: " + seedlength + "."); } } if (searchvectorfile.isEmpty()) searchvectorfile = queryvectorfile; // This is a potentially dangerous pattern! An alternative would be to make this setting // part of each real vector, as with complex Modes. But they aren't so nice either. // Let's avoid getting too committed to either approach and refactor at will. // dwiddows, 2013-09-27. if (vectortype == VectorType.REAL && realbindmethod == RealVector.RealBindMethod.PERMUTATION) { RealVector.setBindType(RealVector.RealBindMethod.PERMUTATION); } } }
Utility method added to allow other classes to change the ExpandSearchSpace option in a FlagConfig without reconfiguring it entirely git-svn-id: 08ea2b8556b98ff0c759f891b20f299445ddff2f@1151 483481f0-a63c-0410-a8a8-396719eec1a4
src/main/java/pitt/search/semanticvectors/FlagConfig.java
Utility method added to allow other classes to change the ExpandSearchSpace option in a FlagConfig without reconfiguring it entirely
Java
mit
b42e1318d14fdf61c9ce5b58febf30b6af7661c3
0
davidfialho14/bgp-simulator
package simulators; import core.Link; import core.Router; import io.reporters.Reporter; import java.io.IOException; /** * A simulator is used to do the actual simulation. It is a template class that takes a simulation setup * and executes teh necessary steps to start a simulation: setup, start, and cleanup. */ public class Simulator { private Setup setup; // setup of the simulation /** * Creates a simulator and assigns it an initial setup. * * @param setup setup to assign to the new simulator. */ public Simulator(Setup setup) { this.setup = setup; } /** * Returns the simulation setup. * * @return the simulation setup. */ public Setup getSetup() { return setup; } /** * Sets a simulation setup for the simulator. * * @param setup setup to set. */ public void setSetup(Setup setup) { this.setup = setup; } /** * Entry point to start the simulations. */ public void simulate() { setup.setup(); setup.start(); setup.cleanup(); // reset the routers for (Router router : setup.getTopology().getRouters()) { router.getTable().reset(); router.getMRAITimer().clear(); // reset router's links for (Link link : router.getInLinks()) { link.setTurnedOff(false); link.setLastArrivalTime(0); } } // guarantee the arrival times of the destination's in-links are reset to 0 for (Link link : setup.destination.getInLinks()) { link.setLastArrivalTime(0); } } /** * Reports the results of the last simulation. * * @param reporter reporter implementation to report data. * @param simulationNumber number of the simulation being reported. * @throws IOException if there is an IO error while reporting. */ public void report(Reporter reporter, int simulationNumber) throws IOException { setup.getDataCollector().report(reporter, simulationNumber); } }
src/simulators/Simulator.java
package simulators; import core.Link; import core.Router; import io.reporters.Reporter; import java.io.IOException; /** * A simulator is used to do the actual simulation. It is a template class that takes a simulation setup * and executes teh necessary steps to start a simulation: setup, start, and cleanup. */ public class Simulator { private Setup setup; // setup of the simulation /** * Creates a simulator and assigns it an initial setup. * * @param setup setup to assign to the new simulator. */ public Simulator(Setup setup) { this.setup = setup; } /** * Returns the simulation setup. * * @return the simulation setup. */ public Setup getSetup() { return setup; } /** * Sets a simulation setup for the simulator. * * @param setup setup to set. */ public void setSetup(Setup setup) { this.setup = setup; } /** * Entry point to start the simulations. */ public void simulate() { setup.setup(); setup.start(); setup.cleanup(); // reset the routers for (Router router : setup.getTopology().getRouters()) { router.getTable().reset(); router.getMRAITimer().clear(); // reset router's links for (Link link : router.getInLinks()) { link.setTurnedOff(false); link.setLastArrivalTime(0); } } } /** * Reports the results of the last simulation. * * @param reporter reporter implementation to report data. * @param simulationNumber number of the simulation being reported. * @throws IOException if there is an IO error while reporting. */ public void report(Reporter reporter, int simulationNumber) throws IOException { setup.getDataCollector().report(reporter, simulationNumber); } }
Fixed bug: there was a difference of times when the destination was a stub
src/simulators/Simulator.java
Fixed bug: there was a difference of times when the destination was a stub
Java
mit
356237bd60e8072b53cefe3a6891d51fcdcabcd8
0
mopsalarm/Pr0,mopsalarm/Pr0,mopsalarm/Pr0
package com.pr0gramm.app.ui; import android.view.MotionEvent; import android.view.View; import rx.functions.Action0; /** * Detects single taps. */ public class DetectTapTouchListener implements View.OnTouchListener { private final Action0 consumer; private boolean moveOccurred; private float firstX; private float firstY; private DetectTapTouchListener(Action0 consumer) { this.consumer = consumer; } @Override public boolean onTouch(View v, MotionEvent event) { if (event.getActionIndex() == 0) { if (event.getAction() == MotionEvent.ACTION_DOWN) { moveOccurred = false; firstX = event.getX(); firstY = event.getY(); } if (event.getAction() == MotionEvent.ACTION_MOVE) { moveOccurred = moveOccurred || Math.abs(event.getX() - firstX) > 32 || Math.abs(event.getY() - firstY) > 32; } if (event.getAction() == MotionEvent.ACTION_UP) { if (!moveOccurred) { consumer.call(); return true; } } } return false; } public static DetectTapTouchListener withConsumer(Action0 consumer) { return new DetectTapTouchListener(consumer); } }
app/src/main/java/com/pr0gramm/app/ui/DetectTapTouchListener.java
package com.pr0gramm.app.ui; import android.view.MotionEvent; import android.view.View; import rx.functions.Action0; /** * Detects single taps. */ public class DetectTapTouchListener implements View.OnTouchListener { private final Action0 consumer; private boolean moveOccurred; private DetectTapTouchListener(Action0 consumer) { this.consumer = consumer; } @Override public boolean onTouch(View v, MotionEvent event) { if (event.getActionIndex() == 0) { if (event.getAction() == MotionEvent.ACTION_DOWN) { moveOccurred = false; } if (event.getAction() == MotionEvent.ACTION_MOVE) { moveOccurred = true; } if (event.getAction() == MotionEvent.ACTION_UP) { if (!moveOccurred) { consumer.call(); return true; } moveOccurred = false; } } return false; } public static DetectTapTouchListener withConsumer(Action0 consumer) { return new DetectTapTouchListener(consumer); } }
Improve tap detection
app/src/main/java/com/pr0gramm/app/ui/DetectTapTouchListener.java
Improve tap detection
Java
mit
43a59b966a8ca2c0de7373699bbaff005caa0dd9
0
beepscore/Sunshine
package com.beepscore.android.sunshine; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.support.v4.app.Fragment; import android.os.Bundle; import android.support.v4.app.LoaderManager; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.ListView; import android.widget.TextView; import com.beepscore.android.sunshine.data.WeatherContract; /** * A placeholder fragment containing a simple view. */ public class ForecastFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> { private final static int LOADER_ID = 1; // public empty constructor public ForecastFragment() { } ForecastAdapter mForecastAdapter = null; @Override // onCreate is called before onCreateView public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); // Prepare the loader. // Either re-connect with an existing one or start a new one. // http://developer.android.com/guide/components/loaders.html // http://android-developer-tutorials.blogspot.com/2013/03/using-cursorloader-in-android.html getLoaderManager().initLoader(LOADER_ID, null, this); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { String locationSetting = Utility.getPreferredLocation(getActivity()); // Sort order: Ascending, by date. String sortOrder = WeatherContract.WeatherEntry.COLUMN_DATE + " ASC"; Uri weatherForLocationUri = WeatherContract.WeatherEntry.buildWeatherLocationWithStartDate( locationSetting, System.currentTimeMillis()); Cursor cur = getActivity().getContentResolver().query(weatherForLocationUri, null, null, null, sortOrder); // The CursorAdapter will take data from our cursor and populate the ListView // However, we cannot use FLAG_AUTO_REQUERY since it is deprecated, so we will end // up with an empty list the first time we run. mForecastAdapter = new ForecastAdapter(getActivity(), cur, 0); View fragmentForecastView = inflater.inflate(R.layout.fragment_forecast, container, false); ListView listView = (ListView)fragmentForecastView.findViewById(R.id.listview_forecast); listView.setAdapter(mForecastAdapter); return fragmentForecastView; } @Override public void onStart() { super.onStart(); updateWeather(); } private void updateWeather() { FetchWeatherTask weatherTask = new FetchWeatherTask(getActivity()); String location = Utility.getPreferredLocation(getActivity()); weatherTask.execute(location); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { // Inflate the menu; this adds items to the action bar if it is present. // http://stackoverflow.com/questions/15653737/oncreateoptionsmenu-inside-fragments inflater.inflate(R.menu.forecastfragment, menu); super.onCreateOptionsMenu(menu, inflater); } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.action_refresh) { // delete old forecasts Uri weatherUri = WeatherContract.WeatherEntry.CONTENT_URI; int numberOfRowsDeleted = getActivity().getContentResolver().delete(weatherUri, null, null); // get new forecasts updateWeather(); return true; } if (id == R.id.action_settings) { Intent intent = new Intent(getActivity(), SettingsActivity.class); startActivity(intent); return true; } return super.onOptionsItemSelected(item); } //////////////////////////////////////////////////////////////////////////// // LoaderManager.LoaderCallbacks<Cursor> @Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { // Called when a new Loader needs to be created. // This sample only has one Loader, so we don't care about the ID. // e.g. "content://com.beepscore.android.sunshine/weather" Uri baseUri = WeatherContract.WeatherEntry.CONTENT_URI; return new CursorLoader(getActivity(), baseUri, null, null, null, null); } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { TextView textView = (TextView)getActivity().findViewById(R.id.list_item_forecast_textview); if (mForecastAdapter != null && data != null && data.moveToFirst() && textView != null) { // Swap the new cursor in. // The framework will take care of closing the old cursor once we return. mForecastAdapter.swapCursor(data); } } @Override public void onLoaderReset(Loader<Cursor> loader) { // called when the last Cursor provided to onLoadFinished() is about to be closed. // We need to make sure we are no longer using it. mForecastAdapter.swapCursor(null); } //////////////////////////////////////////////////////////////////////////// }
app/src/main/java/com/beepscore/android/sunshine/ForecastFragment.java
package com.beepscore.android.sunshine; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.support.v4.app.Fragment; import android.os.Bundle; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.ListView; import com.beepscore.android.sunshine.Utility; import com.beepscore.android.sunshine.data.WeatherContract; /** * A placeholder fragment containing a simple view. */ public class ForecastFragment extends Fragment { // public empty constructor public ForecastFragment() { } ForecastAdapter mForecastAdapter = null; @Override // onCreate is called before onCreateView public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { String locationSetting = Utility.getPreferredLocation(getActivity()); // Sort order: Ascending, by date. String sortOrder = WeatherContract.WeatherEntry.COLUMN_DATE + " ASC"; Uri weatherForLocationUri = WeatherContract.WeatherEntry.buildWeatherLocationWithStartDate( locationSetting, System.currentTimeMillis()); Cursor cur = getActivity().getContentResolver().query(weatherForLocationUri, null, null, null, sortOrder); // The CursorAdapter will take data from our cursor and populate the ListView // However, we cannot use FLAG_AUTO_REQUERY since it is deprecated, so we will end // up with an empty list the first time we run. mForecastAdapter = new ForecastAdapter(getActivity(), cur, 0); View fragmentForecastView = inflater.inflate(R.layout.fragment_forecast, container, false); ListView listView = (ListView)fragmentForecastView.findViewById(R.id.listview_forecast); listView.setAdapter(mForecastAdapter); return fragmentForecastView; } @Override public void onStart() { super.onStart(); updateWeather(); } private void updateWeather() { FetchWeatherTask weatherTask = new FetchWeatherTask(getActivity()); String location = Utility.getPreferredLocation(getActivity()); weatherTask.execute(location); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { // Inflate the menu; this adds items to the action bar if it is present. // http://stackoverflow.com/questions/15653737/oncreateoptionsmenu-inside-fragments inflater.inflate(R.menu.forecastfragment, menu); super.onCreateOptionsMenu(menu, inflater); } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.action_refresh) { updateWeather(); return true; } if (id == R.id.action_settings) { Intent intent = new Intent(getActivity(), SettingsActivity.class); startActivity(intent); return true; } return super.onOptionsItemSelected(item); } }
In ForecastFragment initLoader with LOADER_ID, implement LoaderCallbacks. In onOptionsItemSelected refresh delete old forecasts.
app/src/main/java/com/beepscore/android/sunshine/ForecastFragment.java
In ForecastFragment initLoader with LOADER_ID, implement LoaderCallbacks.
Java
mit
63e0fd233e9595c9d7bee1d7bf71294b1745de74
0
netdxy/java-sdk,dennisit/java-sdk,airingursb/java-sdk,sxci/java-sdk,qiniu/java-sdk,simon-liubin/java-sdk,lhcpig/java-sdk
package com.qiniu.storage; import com.qiniu.common.Config; import com.qiniu.common.QiniuException; import com.qiniu.http.Client; import com.qiniu.http.Response; import com.qiniu.util.StringMap; import java.io.File; /** * 七牛文件上传管理器 * <p/> * 一般默认可以使用这个类的方法来上传数据和文件。这个类自动检测文件的大小, * 只要超过了{@link com.qiniu.common.Config#PUT_THRESHOLD} */ public final class UploadManager { private final Client client; public UploadManager() { client = new Client(); } private static void checkArgs(final String key, byte[] data, File f, String token) { String message = null; if (f == null && data == null) { message = "no input data"; } else if (token == null || token.equals("")) { message = "no token"; } if (message != null) { throw new IllegalArgumentException(message); } } /** * 过滤用户自定义参数,只有参数名以<code>x:</code>开头的参数才会被使用 * * @param params 待过滤的用户自定义参数 * @return 过滤后的用户自定义参数 */ private static StringMap filterParam(StringMap params) { final StringMap ret = new StringMap(); if (params == null) { return ret; } params.forEach(new StringMap.Consumer() { @Override public void accept(String key, Object value) { if (value == null) { return; } String val = value.toString(); if (key.startsWith("x:") && !val.equals("")) { ret.put(key, val); } } }); return ret; } /** * 上传数据 * * @param data 上传的数据 * @param key 上传数据保存的文件名 * @param token 上传凭证 */ public Response put(final byte[] data, final String key, final String token) throws QiniuException { return put(data, key, token, null, null, false); } /** * 上传数据 * * @param data 上传的数据 * @param key 上传数据保存的文件名 * @param token 上传凭证 */ public Response put(final byte[] data, final String key, final String token, StringMap params, String mime, boolean checkCrc) throws QiniuException { checkArgs(key, data, null, token); if (mime == null) { mime = Client.DefaultMime; } params = filterParam(params); return new FormUploader(client, token, key, data, params, mime, checkCrc).upload(); } /** * 上传文件 * * @param filePath 上传的文件路径 * @param key 上传文件保存的文件名 * @param token 上传凭证 */ public Response put(String filePath, String key, String token) throws QiniuException { return put(filePath, key, token, null, null, false); } /** * 上传文件 * * @param filePath 上传的文件路径 * @param key 上传文件保存的文件名 * @param token 上传凭证 */ public Response put(String filePath, String key, String token, StringMap params, String mime, boolean checkCrc) throws QiniuException { return put(new File(filePath), key, token, params, mime, checkCrc); } /** * 上传文件 * * @param file 上传的文件对象 * @param key 上传文件保存的文件名 * @param token 上传凭证 */ public Response put(File file, String key, String token) throws QiniuException { return put(file, key, token, null, null, false); } /** * 上传文件 * * @param file 上传的文件对象 * @param key 上传文件保存的文件名 * @param token 上传凭证 */ public Response put(File file, String key, String token, StringMap params, String mime, boolean checkCrc) throws QiniuException { checkArgs(key, null, file, token); if (mime == null) { mime = Client.DefaultMime; } params = filterParam(params); long size = file.length(); if (size <= Config.PUT_THRESHOLD) { return new FormUploader(client, token, key, file, params, mime, checkCrc).upload(); } ResumeUploader uploader = new ResumeUploader(client, token, key, file, params, mime); return uploader.upload(); } }
src/main/java/com/qiniu/storage/UploadManager.java
package com.qiniu.storage; import com.qiniu.common.Config; import com.qiniu.common.QiniuException; import com.qiniu.http.Client; import com.qiniu.http.Response; import com.qiniu.util.StringMap; import java.io.File; /** * 七牛文件上传管理器 * <p/> * 一般默认可以使用这个类的方法来上传数据和文件。这个类自动检测文件的大小, * 只要超过了{@link com.qiniu.common.Config#PUT_THRESHOLD} */ public final class UploadManager { private final Client client; public UploadManager() { client = new Client(); } private static void checkArgs(final String key, byte[] data, File f, String token) { String message = null; if (f == null && data == null) { message = "no input data"; } else if (token == null || token.equals("")) { message = "no token"; } if (message != null) { throw new IllegalArgumentException(message); } } /** * 过滤用户自定义参数,只有参数名以<code>x:</code>开头的参数才会被使用 * * @param params 待过滤的用户自定义参数 * @return 过滤后的用户自定义参数 */ private static StringMap filterParam(StringMap params) { final StringMap ret = new StringMap(); if (params == null) { return ret; } ret.forEach(new StringMap.Consumer() { @Override public void accept(String key, Object value) { if (value == null) { return; } String val = value.toString(); if (key.startsWith("x:") && !val.equals("")) { ret.put(key, val); } } }); return ret; } /** * 上传数据 * * @param data 上传的数据 * @param key 上传数据保存的文件名 * @param token 上传凭证 */ public Response put(final byte[] data, final String key, final String token) throws QiniuException { return put(data, key, token, null, null, false); } /** * 上传数据 * * @param data 上传的数据 * @param key 上传数据保存的文件名 * @param token 上传凭证 */ public Response put(final byte[] data, final String key, final String token, StringMap params, String mime, boolean checkCrc) throws QiniuException { checkArgs(key, data, null, token); if (mime == null) { mime = Client.DefaultMime; } params = filterParam(params); return new FormUploader(client, token, key, data, params, mime, checkCrc).upload(); } /** * 上传文件 * * @param filePath 上传的文件路径 * @param key 上传文件保存的文件名 * @param token 上传凭证 */ public Response put(String filePath, String key, String token) throws QiniuException { return put(filePath, key, token, null, null, false); } /** * 上传文件 * * @param filePath 上传的文件路径 * @param key 上传文件保存的文件名 * @param token 上传凭证 */ public Response put(String filePath, String key, String token, StringMap params, String mime, boolean checkCrc) throws QiniuException { return put(new File(filePath), key, token, params, mime, checkCrc); } /** * 上传文件 * * @param file 上传的文件对象 * @param key 上传文件保存的文件名 * @param token 上传凭证 */ public Response put(File file, String key, String token) throws QiniuException { return put(file, key, token, null, null, false); } /** * 上传文件 * * @param file 上传的文件对象 * @param key 上传文件保存的文件名 * @param token 上传凭证 */ public Response put(File file, String key, String token, StringMap params, String mime, boolean checkCrc) throws QiniuException { checkArgs(key, null, file, token); if (mime == null) { mime = Client.DefaultMime; } params = filterParam(params); long size = file.length(); if (size <= Config.PUT_THRESHOLD) { return new FormUploader(client, token, key, file, params, mime, checkCrc).upload(); } ResumeUploader uploader = new ResumeUploader(client, token, key, file, params, mime); return uploader.upload(); } }
fixed param put
src/main/java/com/qiniu/storage/UploadManager.java
fixed param put
Java
mit
cab67e0dae8d90765217790dc18e9e548093987a
0
vincentzhang96/VahrhedralBot
package co.phoenixlab.discord.api; import co.phoenixlab.common.lang.SafeNav; import co.phoenixlab.discord.api.entities.*; import co.phoenixlab.discord.api.event.LogInEvent; import co.phoenixlab.discord.api.event.UserUpdateEvent; import co.phoenixlab.discord.api.event.WebSocketCloseEvent; import co.phoenixlab.discord.cfg.DiscordApiClientConfig; import co.phoenixlab.discord.cfg.InfluxDbConfig; import co.phoenixlab.discord.util.TryingScheduledExecutor; import com.codahale.metrics.Meter; import com.codahale.metrics.MetricFilter; import com.codahale.metrics.MetricRegistry; import com.codahale.metrics.ScheduledReporter; import com.google.common.eventbus.EventBus; import com.google.common.eventbus.Subscribe; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.mashape.unirest.http.HttpResponse; import com.mashape.unirest.http.JsonNode; import com.mashape.unirest.http.Unirest; import com.mashape.unirest.http.exceptions.UnirestException; import metrics_influxdb.HttpInfluxdbProtocol; import metrics_influxdb.InfluxdbReporter; import metrics_influxdb.api.measurements.CategoriesMetricMeasurementTransformer; import org.apache.http.HttpHeaders; import org.apache.http.entity.ContentType; import org.java_websocket.client.DefaultSSLWebSocketClientFactory; import org.json.JSONArray; import org.json.simple.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.net.ssl.SSLContext; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URI; import java.net.URISyntaxException; import java.net.UnknownHostException; import java.util.*; import java.util.concurrent.ExecutionException; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.atomic.LongAdder; import java.util.function.Function; import java.util.regex.Pattern; import java.util.stream.Collectors; import static co.phoenixlab.discord.VahrhedralBot.getFeatureToggleConfig; import static java.util.concurrent.TimeUnit.MILLISECONDS; import static java.util.concurrent.TimeUnit.SECONDS; public class DiscordApiClient { public static final Server NO_SERVER = new Server("NO_SERVER"); public static final Channel NO_CHANNEL = new Channel("", "NO_CHANNEL"); public static final User NO_USER = new User("NO_USER", "NO_USER", "NO_USER", null); public static final Member NO_MEMBER = new Member(NO_USER, Collections.emptyList(), "", null); public static final Role NO_ROLE = new Role(0, 0, "NO_ROLE", false, "", false, 0); public static final String[] EMPTY_STR_ARRAY = new String[0]; public static final Pattern USER_ID_REGEX = Pattern.compile("[0-9]+"); private static final Logger LOGGER = LoggerFactory.getLogger("DiscordApiClient"); public static final String TOGGLE_API_FUZZY_NICK = "api.fuzzy.nick"; private final Map<String, EndpointStats> endpointStats = new HashMap<>(); static { NO_CHANNEL.setParent(NO_SERVER); } private final ScheduledExecutorService executorService; private final AtomicReference<String> sessionId; private final AtomicReference<User> clientUser; private final List<Server> servers; private final Map<String, Server> serverMap; private final EventBus eventBus; private final Gson gson; private final Map<String, Channel> privateChannels; private final Map<User, Channel> privateChannelsByUser; private final AtomicBoolean active; private final Statistics statistics; private final Map<String, Presence> userPresences; private final Map<String, String> userGames; private String email; private String password; private String token; private DiscordWebSocketClient webSocketClient; private DiscordApiClientConfig apiClientConfig; private MetricRegistry endpointMetricRegistry; private ScheduledReporter endpointMetricReporter; private ScheduledExecutorService metricExecutorService; public DiscordApiClient(DiscordApiClientConfig config) { apiClientConfig = config; statistics = new Statistics(); sessionId = new AtomicReference<>(); clientUser = new AtomicReference<>(); executorService = new TryingScheduledExecutor(Executors.newScheduledThreadPool(4), LOGGER); servers = new ArrayList<>(); serverMap = new HashMap<>(); privateChannels = new HashMap<>(); privateChannelsByUser = new HashMap<>(); userPresences = new HashMap<>(); userGames = new HashMap<>(); active = new AtomicBoolean(); eventBus = new EventBus((e, c) -> { LOGGER.warn("Error while handling event {} when calling {}", c.getEvent(), c.getSubscriberMethod().toGenericString()); LOGGER.warn("EventBus dispatch exception", e); statistics.eventDispatchErrorCount.increment(); }); gson = new GsonBuilder().serializeNulls().create(); eventBus.register(this); endpointMetricRegistry = new MetricRegistry(); if (config.isEnableMetrics() && config.getReportingIntervalMsec() > 0) { metricExecutorService = new TryingScheduledExecutor(Executors.newScheduledThreadPool(1), LOGGER); InfluxDbConfig idbc = config.getApiClientInfluxConfig(); HttpInfluxdbProtocol protocol = idbc.toInfluxDbProtocolConfig(); LOGGER.info("Will be connecting to InfluxDB at {}", gson.toJson(protocol)); endpointMetricReporter = InfluxdbReporter.forRegistry(endpointMetricRegistry) .protocol(protocol) .convertDurationsTo(MILLISECONDS) .convertRatesTo(SECONDS) .filter(MetricFilter.ALL) .skipIdleMetrics(true) .transformer(new CategoriesMetricMeasurementTransformer("endpoint", "stat")) .withScheduler(metricExecutorService) .build(); endpointMetricReporter.start(config.getReportingIntervalMsec(), MILLISECONDS); } } @Subscribe public void countEvent(Object object) { statistics.eventCount.increment(); } public void logIn(String token) throws IOException { this.token = token; LOGGER.info("Using provided token {}", token); openWebSocket(); } public void logIn(String email, String password) throws IOException { LOGGER.info("Attempting to log in as {}...", email); this.email = email; this.password = password; Map<String, String> authObj = new HashMap<>(); authObj.put("email", email); authObj.put("password", password); JSONObject auth = new JSONObject(authObj); HttpResponse<JsonNode> response; try { response = Unirest.post(ApiConst.LOGIN_ENDPOINT). header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.getMimeType()). body(auth.toJSONString()). asJson(); } catch (UnirestException e) { statistics.restErrorCount.increment(); throw new IOException("Unable to log in", e); } int status = response.getStatus(); if (status != HttpURLConnection.HTTP_OK) { if (status == HttpURLConnection.HTTP_FORBIDDEN) { // Servers return FORBIDDEN for bad credentials LOGGER.warn("Unable to log in with given credentials: ", response.getStatusText()); } else { LOGGER.warn("Unable to log in, Discord may be having issues"); } statistics.restErrorCount.increment(); throw new IOException("Unable to log in: HTTP " + response.getStatus() + ": " + response.getStatusText()); } token = response.getBody().getObject().getString("token"); LOGGER.info("Successfully logged in, token is {}", token); openWebSocket(); } private void openWebSocket() throws IOException { try { int retryTimeSec = 0; do { try { final String gateway = getWebSocketGateway(); final URI gatewayUri = new URI(gateway); webSocketClient = new DiscordWebSocketClient(this, gatewayUri, apiClientConfig); SSLContext context = SSLContext.getInstance("TLS"); context.init(null, null, null); webSocketClient.setWebSocketFactory(new DefaultSSLWebSocketClientFactory(context)); } catch (URISyntaxException e) { LOGGER.warn("Bad gateway", e); throw new IOException(e); } catch (UnknownHostException ukhe) { LOGGER.warn("Unable to reach DNS server, retrying in {}s...", retryTimeSec); Thread.sleep(MILLISECONDS.convert(retryTimeSec, SECONDS)); retryTimeSec = Math.min(retryTimeSec + 2, 30); // Cap at 30 interval continue; } catch (Exception e) { LOGGER.warn("Unexpected error", e); throw new IOException(e); } statistics.connectAttemptCount.increment(); active.set(webSocketClient.connectBlocking()); if (!active.get()) { LOGGER.warn("Unable to connect, retrying in {}s...", retryTimeSec); Thread.sleep(MILLISECONDS.convert(retryTimeSec, SECONDS)); retryTimeSec = Math.min(retryTimeSec + 2, 30); // Cap at 30 interval } } while (!active.get()); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } private String getWebSocketGateway() throws IOException { boolean ok = false; try { HttpResponse<JsonNode> response; try { response = Unirest.get(ApiConst.WEBSOCKET_GATEWAY). header("authorization", token). asJson(); } catch (UnirestException e) { statistics.restErrorCount.increment(); if (e.getCause() instanceof UnknownHostException) { throw (UnknownHostException) e.getCause(); } throw new IOException("Unable to retrieve websocket gateway", e); } int status = response.getStatus(); if (status != HttpURLConnection.HTTP_OK) { statistics.restErrorCount.increment(); LOGGER.warn("Unable to retrieve websocket gateway: HTTP {}: {}", status, response.getStatusText()); throw new IOException("Unable to retrieve websocket : HTTP " + status + ": " + response.getStatusText()); } String gateway = response.getBody().getObject().getString("url"); LOGGER.info("Found WebSocket gateway at {}", gateway); ok = true; return gateway; } finally { update("get_gateway").forBool(ok); } } void onLogInEvent(LogInEvent event) { ReadyMessage readyMessage = event.getReadyMessage(); setSessionId(readyMessage.getSessionId()); LOGGER.info("Using sessionId {}", getSessionId()); User user = readyMessage.getUser(); setClientUser(user); LOGGER.info("Logged in as {}#{} ID {}", user.getUsername(), user.getDiscriminator(), user.getId()); LOGGER.info("Connected to {} servers", readyMessage.getServers().length); // We don't bother populating channel messages since we only care about new messages coming in servers.clear(); Collections.addAll(servers, readyMessage.getServers()); remapServers(); // Update presences Arrays.stream(readyMessage.getServers()). filter(Server::isAvailable). map(ReadyServer::getPresences). flatMap(Arrays::stream). forEach(p -> { String id = p.getUser().getId(); userPresences.put(id, p.getStatus()); userGames.put(id, SafeNav.of(p.getGame()).next(Game::getName).orElse("[misc.nothing]")); }); // Request to populate the large servers servers.stream().filter(Server::isLarge). forEach(this::requestLargerServerUsers); LOGGER.info("Holding {} private conversations", readyMessage.getPrivateChannels().length); for (Channel privateChannel : readyMessage.getPrivateChannels()) { privateChannels.put(privateChannel.getId(), privateChannel); privateChannelsByUser.put(privateChannel.getRecipient(), privateChannel); } } public void requestLargerServerUsers(Server server) { org.json.JSONObject object = new org.json.JSONObject(); object.put("op", 8); org.json.JSONObject requestBody = new org.json.JSONObject(); requestBody.put("guild_id", server.getId()); requestBody.put("query", ""); requestBody.put("limit", 0); object.put("d", requestBody); webSocketClient.send(object.toString()); } @Subscribe public void onUserUpdate(UserUpdateEvent event) { UserUpdate update = event.getUpdate(); User oldUser = clientUser.get(); if (!oldUser.getId().equals(update.getId())) { throw new IllegalStateException("User ID should not be able to be updated!"); } String oldEmail = email; email = update.getEmail(); User newUser = new User(update.getUsername(), update.getId(), update.getDiscriminator(), update.getAvatar()); clientUser.set(newUser); if (!oldUser.getUsername().equals(update.getUsername())) { LOGGER.info("Username changed from '{}' to '{}'", oldUser.getUsername(), update.getUsername()); } if (!oldUser.getDiscriminator().equals(update.getDiscriminator())) { LOGGER.info("Discriminator changed from '{}' to '{}'", oldUser.getDiscriminator(), update.getDiscriminator()); } if (!oldUser.getAvatar().equals(update.getAvatar())) { LOGGER.info("Avatar changed from '{}' to '{}'", oldUser.getAvatar(), update.getAvatar()); } if ((oldEmail == null) || !oldEmail.equals(email)) { LOGGER.info("Email changed from '{}' to '{}'", oldEmail, email); } // Fire off a change to ourself across all servers as well for (Server server : servers) { server.getMembers().stream(). map(Member::getUser). filter(u -> u.equals(newUser)). findFirst().ifPresent(u -> { u.setAvatar(update.getAvatar()); u.setUsername(update.getUsername()); u.setDiscriminator(update.getDiscriminator()); }); } } public Future<Message> sendMessage(String body, String channelId) { return sendMessage(body, channelId, EMPTY_STR_ARRAY, true); } public Future<Message> sendMessage(String body, Channel channel) { return sendMessage(body, channel, EMPTY_STR_ARRAY, true); } public Future<Message> sendMessage(String body, String channelId, Embed embed) { return sendMessage(body, channelId, EMPTY_STR_ARRAY, true, embed); } public Future<Message> sendMessage(String body, Channel channel, Embed embed) { return sendMessage(body, channel, EMPTY_STR_ARRAY, true, embed); } public Future<Message> sendMessage(String body, String channelId, boolean async) { return sendMessage(body, channelId, EMPTY_STR_ARRAY, async); } public Future<Message> sendMessage(String body, Channel channel, boolean async) { return sendMessage(body, channel, EMPTY_STR_ARRAY, async); } public Future<Message> sendMessage(String body, String channelId, boolean async, Embed embed) { return sendMessage(body, channelId, EMPTY_STR_ARRAY, async, embed); } public Future<Message> sendMessage(String body, Channel channel, boolean async, Embed embed) { return sendMessage(body, channel, EMPTY_STR_ARRAY, async, embed); } public Future<Message> sendMessage(String body, Channel channel, String[] mentions) { return sendMessage(body, channel.getId(), mentions); } public Future<Message> sendMessage(String body, String channelId, String[] mentions) { return sendMessage(body, channelId, mentions, true); } public Future<Message> sendMessage(String body, Channel channel, String[] mentions, Embed embed) { return sendMessage(body, channel.getId(), mentions, embed); } public Future<Message> sendMessage(String body, String channelId, String[] mentions, Embed embed) { return sendMessage(body, channelId, mentions, true, embed); } public Future<Message> sendMessage(String body, Channel channel, String[] mentions, boolean async) { return sendMessage(body, channel.getId(), mentions, async); } public Future<Message> sendMessage(String body, Channel channel, String[] mentions, boolean async, Embed embed) { return sendMessage(body, channel.getId(), mentions, async, embed); } public Future<Message> sendMessage(String body, String channelId, String[] mentions, boolean async) { return sendMessage(body, channelId, mentions, async, null); } public Future<Message> sendMessage(String body, String channelId, String[] mentions, boolean async, Embed embed) { if (body == null || channelId == null || mentions == null) { throw new IllegalArgumentException("Arguments may not be null"); } Future<Message> future = executorService.submit(() -> sendMessageInternal(body, channelId, mentions, embed)); if (!async) { try { future.get(); } catch (InterruptedException | ExecutionException e) { LOGGER.warn("Exception while waiting for sendMessage result", e); } } return future; } private Message sendMessageInternal(String body, String channelId, String[] mentions, Embed embed) { Gson g = new GsonBuilder().create(); // April fools. // String[] splitBody = body.split("\n"); // StringJoiner joiner = new StringJoiner("\n"); // for (String s : splitBody) { // joiner.add(reverseLine(s)); // } // body = joiner.toString(); boolean ok = false; try { OutboundMessage outboundMessage = new OutboundMessage(body, false, mentions, embed); String content = g.toJson(outboundMessage); HttpResponse<String> response; Map<String, String> headers = new HashMap<>(); headers.put(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.getMimeType()); headers.put(HttpHeaders.AUTHORIZATION, token); try { response = Unirest.post(ApiConst.CHANNELS_ENDPOINT + channelId + "/messages"). headers(headers). body(content). asString(); } catch (UnirestException e) { statistics.restErrorCount.increment(); LOGGER.warn("Unable to send message", e); return null; } int status = response.getStatus(); if (status != 200) { statistics.restErrorCount.increment(); LOGGER.warn("Unable to send message: HTTP {}: {}", status, response.getStatusText()); return null; } Message message = g.fromJson(response.getBody(), Message.class); ok = true; return message; } finally { update("send_message").forBool(ok); } } private String reverseLine(String s) { if (s.startsWith("NOFLIP")) { return s.substring("NOFLIP".length()); } String[] tokens = s.split(" "); StringJoiner joiner = new StringJoiner(" "); String[] outArray = new String[tokens.length]; for (int i = 0, tokensLength = tokens.length; i < tokensLength; i++) { String token = tokens[i]; if (!token.startsWith("http://") && !token.startsWith("https://")) { token = reverse(token); } outArray[outArray.length - i - 1] = token; } for(String s1 : outArray) { joiner.add(s1); } return joiner.toString(); } private String reverse(String s) { char[] chars = s.toCharArray(); char c; int length = chars.length; for (int i = 0; i < length / 2; i++) { c = chars[length - i - 1]; chars[length - i - 1] = flip(chars[i]); chars[i] = flip(c); } return new String(chars); } private char flip(char c) { switch (c) { case ')': return '('; case '(': return ')'; case '[': return ']'; case ']': return '['; case '{': return '}'; case '}': return '{'; default: return c; } } public void deleteMessage(String channelId, String messageId) { deleteMessage(channelId, messageId, true); } public void deleteMessage(String channelId, String messageId, boolean async) { if (channelId == null || messageId == null) { return; } if (async) { executorService.submit(() -> deleteMessage(channelId, messageId, false)); return; } boolean ok = false; try { HttpResponse<String> response; Map<String, String> headers = new HashMap<>(); headers.put(HttpHeaders.AUTHORIZATION, token); try { response = Unirest.delete(ApiConst.CHANNELS_ENDPOINT + channelId + "/messages/" + messageId). headers(headers). asString(); } catch (UnirestException e) { statistics.restErrorCount.increment(); LOGGER.warn("Unable to delete message", e); return; } int status = response.getStatus(); if (status != 204) { statistics.restErrorCount.increment(); LOGGER.warn("Unable to delete message: HTTP {}: {}", status, response.getStatusText()); return; } ok = true; } finally { update("delete_message").forBool(ok); } } public void bulkDeleteMessages(String channelId, String[] messageIds) { bulkDeleteMessages(channelId, messageIds, true); } public void bulkDeleteMessages(String channelId, String[] messageIds, boolean async) { if (channelId == null || messageIds == null) { return; } if (async) { executorService.submit(() -> bulkDeleteMessages(channelId, messageIds, false)); return; } boolean ok = false; try { HttpResponse<String> response; Map<String, String> headers = new HashMap<>(); headers.put(HttpHeaders.AUTHORIZATION, token); headers.put(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.getMimeType()); org.json.JSONObject body = new org.json.JSONObject(); body.put("messages", new JSONArray(messageIds)); try { String url = ApiConst.CHANNELS_ENDPOINT + channelId + "/messages/bulk-delete"; System.out.println(url); response = Unirest.post(url). headers(headers). body(body.toString()). asString(); } catch (UnirestException e) { statistics.restErrorCount.increment(); LOGGER.warn("Unable to delete messages", e); return; } int status = response.getStatus(); if (status != 204) { statistics.restErrorCount.increment(); LOGGER.warn("Unable to delete messages: HTTP {}: {}: {}", status, response.getStatusText(), response.getBody()); } else { LOGGER.info("Bulk deleted {} messages", messageIds.length); ok = true; } } finally { update("bulk_delete").forBool(ok); } } public void editMessage(String channelId, String messageId, String content) { editMessage(channelId, messageId, content, null); } public void editMessage(String channelId, String messageId, String content, boolean async) { editMessage(channelId, messageId, content, null, async); } public void editMessage(String channelId, String messageId, String content, String[] mentions) { editMessage(channelId, messageId, content, mentions, true); } public void editMessage(String channelId, String messageId, String content, String[] mentions, boolean async) { if (channelId == null || messageId == null || content == null) { return; } if (async) { executorService.submit(() -> editMessage(channelId, messageId, content, mentions, false)); return; } boolean ok = false; try { // TODO Add support for mention changes Map<String, Object> ret = new HashMap<>(); ret.put("content", content); JSONObject object = new JSONObject(ret); HttpResponse<JsonNode> response; Map<String, String> headers = new HashMap<>(); headers.put(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.getMimeType()); headers.put(HttpHeaders.AUTHORIZATION, token); try { response = Unirest.patch(ApiConst.CHANNELS_ENDPOINT + channelId + "/messages/" + messageId). headers(headers). body(object.toJSONString()). asJson(); } catch (UnirestException e) { statistics.restErrorCount.increment(); LOGGER.warn("Unable to edit message", e); return; } int status = response.getStatus(); if (status != 200) { statistics.restErrorCount.increment(); LOGGER.warn("Unable to edit message: HTTP {}: {}", status, response.getStatusText()); return; } ok = true; } finally { update("edit_message").forBool(ok); } } // public Future<Message[]> getChannelHistory(String channelId, String before, int limit) { // // } // Message[] getChannelHistoryInternal(String channelId, String before, int limit) { // try { // Map<String, String> headers = new HashMap<>(); // headers.put(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.getMimeType()); // headers.put(HttpHeaders.AUTHORIZATION, token); // Map<String, Object> queryParams = new HashMap<>(); // queryParams.put("limit", Math.max(1, Math.min(limit, 50))); // if (before != null) { // queryParams.put("before", before); // } // HttpResponse<JsonNode> response = Unirest.get(ApiConst.CHANNELS_ENDPOINT + // channelId + "/messages"). // headers(headers). // queryString(queryParams). // asJson(); // int status = response.getStatus(); // if (status != 200) { // statistics.restErrorCount.increment(); // LOGGER.warn("Unable to retrieve message: HTTP {}: {}", status, response.getStatusText()); // return null; // } // JSONArray ret = response.getBody().getArray(); // // // } catch (UnirestException e) { // statistics.restErrorCount.increment(); // LOGGER.warn("Unable to retrieve message"); // return null; // } // } public void updateNowPlaying(String message) { webSocketClient.sendNowPlayingUpdate(message); } public void updateRolesByObj(User user, Server server, Collection<Role> roles) { updateRolesByObj(user, server, roles, true); } public void updateRolesByObj(User user, Server server, Collection<Role> roles, boolean async) { List<String> r = roles.stream().map(Role::getId).collect(Collectors.toList()); updateRoles(user, server, r, async); } public void updateRoles(User user, Server server, Collection<String> roles) { updateRoles(user, server, roles, true); } public void updateRoles(User user, Server server, Collection<String> roles, boolean async) { if (async) { executorService.submit(() -> updateRoles(user, server, roles, false)); return; } boolean ok = false; try { Map<String, String> headers = new HashMap<>(); headers.put(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.getMimeType()); headers.put(HttpHeaders.AUTHORIZATION, token); org.json.JSONObject object = new org.json.JSONObject(); object.put("roles", roles); HttpResponse<JsonNode> r = Unirest.patch(ApiConst.SERVERS_ENDPOINT + server.getId() + "/members/" + user.getId()). headers(headers). body(object.toString()). asJson(); int status = r.getStatus(); if (status < 200 || status >= 300) { statistics.restErrorCount.increment(); LOGGER.warn("Unable to update member {} ({}) roles in {} ({}): HTTP {}: {}", user.getUsername(), user.getId(), server.getName(), server.getId(), status, r.getStatusText()); return; } ok = true; } catch (UnirestException e) { statistics.restErrorCount.increment(); LOGGER.warn("Unable to update member {} ({}) roles in {} ({})", user.getUsername(), user.getId(), server.getName(), server.getId()); LOGGER.warn("Unable to update member roles", e); return; } finally { update("update_roles").forBool(ok); } } public String getToken() { return token; } public String getSessionId() { return sessionId.get(); } public void setSessionId(String sessionId) { this.sessionId.set(sessionId); } public User getClientUser() { return clientUser.get(); } public void setClientUser(User user) { clientUser.set(user); } public List<Server> getServers() { return servers; } public Map<String, Server> getServerMap() { return serverMap; } public Server getServerByID(String id) { Server server = serverMap.get(id); if (server == null) { server = NO_SERVER; } return server; } public Map<String, Channel> getPrivateChannels() { return privateChannels; } public Map<User, Channel> getPrivateChannelsByUserMap() { return privateChannelsByUser; } public Channel getPrivateChannelById(String id) { return privateChannels.get(id); } public Channel getPrivateChannelByUser(User user) { return privateChannelsByUser.get(user); } public void remapServers() { serverMap.clear(); serverMap.putAll(servers.stream().collect(Collectors.toMap(Server::getId, Function.identity()))); servers.stream(). filter(Server::isAvailable). forEach(server -> server.getChannels().forEach(channel -> channel.setParent(server))); } public Channel getChannelById(String id) { if (id == null) { return NO_CHANNEL; } return servers.stream(). filter(Server::isAvailable). map(Server::getChannels). flatMap(Set::stream). filter(c -> id.equals(c.getId())). findFirst().orElse(getPrivateChannelByIdAsChannel(id)); } public Channel getPrivateChannelByIdAsChannel(String id) { Channel privateChannel = getPrivateChannelById(id); if (privateChannel != null) { return privateChannel; } return NO_CHANNEL; } public Channel getChannelById(String id, Server server) { if (id == null) { return NO_CHANNEL; } if (server == null || server == NO_SERVER) { return getChannelById(id); } return server.getChannels().stream(). filter(c -> id.equals(c.getId())). findFirst().orElse(NO_CHANNEL); } public User findUser(String username) { if (username == null) { return NO_USER; } username = username.toLowerCase(); for (Server server : servers) { User user = findUser(username, server); if (user != NO_USER) { return user; } } return NO_USER; } public User findUser(String username, Server server) { if (username == null) { return NO_USER; } if (server == null || server == NO_SERVER) { return findUser(username); } username = username.toLowerCase(); if (getFeatureToggleConfig().getToggle(TOGGLE_API_FUZZY_NICK).use(server.getId())) { // Search by nickname first, then we can try usernames for (Member member : server.getMembers()) { if (username.equalsIgnoreCase(member.getNickOrUsername())) { return member.getUser(); } } Member temp = null; // No match? Try matching start for (Member member : server.getMembers()) { if (member.getNickOrUsername().toLowerCase().startsWith(username)) { if (temp == null || member.getNickOrUsername().length() <= temp.getNickOrUsername().length()) { temp = member; } } } if (temp != null) { return temp.getUser(); } } for (Member member : server.getMembers()) { User user = member.getUser(); if (username.equalsIgnoreCase(user.getUsername())) { return user; } } Member temp = null; // No match? Try matching start for (Member member : server.getMembers()) { User user = member.getUser(); if (user.getUsername().toLowerCase().startsWith(username)) { if (temp == null || user.getUsername().length() <= temp.getUser().getUsername().length()) { temp = member; } } } if (temp != null) { return temp.getUser(); } // ID match if (USER_ID_REGEX.matcher(username).matches()) { User tempU = getUserById(username, server); if (tempU != null) { return tempU; } } // Still no match? Try fuzzy match // TODO return NO_USER; } public User getUserById(String userId) { return getUserById(userId, true); } public User getUserById(String userId, boolean useApi) { if (userId == null || "NO_USER".equals(userId)) { return NO_USER; } for (Server server : servers) { User user = getUserById(userId, server, useApi); if (user != NO_USER) { return user; } } return NO_USER; } public User getUserById(String userId, Server server) { return getUserById(userId, server, true); } public User getUserById(String userId, Server server, boolean useApi) { if (userId == null || "NO_USER".equals(userId)) { return NO_USER; } if (server == null || server == NO_SERVER) { return getUserById(userId); } if (server.getMembers() == null) { LOGGER.warn("Server {} {} has null member list", server.getId(), server.getName()); return NO_USER; } for (Member member : server.getMembers()) { User user = member.getUser(); if (user.getId().equals(userId)) { return user; } } // Try API endpoint if (useApi) { try { Member member = getMemberHttp(server.getId(), userId); if (member != NO_MEMBER) { server.getMembers().add(member); return member.getUser(); } else { LOGGER.warn("User {} not found via HTTP", userId); } } catch (Exception e) { LOGGER.warn("Unable to get user " + userId + " via HTTP", e); } } return NO_USER; } public Member getUserMember(User user, Server server) { if (user == null || user == NO_USER) { return NO_MEMBER; } return getUserMember(user.getId(), server); } public Member getUserMember(String userId, Server server) { if (userId == null || server == null || server == NO_SERVER || "NO_USER".equals(userId)) { return NO_MEMBER; } for (Member member : server.getMembers()) { User user = member.getUser(); if (user.getId().equals(userId)) { return member; } } // Try API endpoint try { Member member = getMemberHttp(server.getId(), userId); if (member != NO_MEMBER) { server.getMembers().add(member); return member; } else { LOGGER.warn("User {} not found via HTTP", userId); } } catch (Exception e) { LOGGER.warn("Unable to get user " + userId + " via HTTP", e); } return NO_MEMBER; } public Role getRole(String roleId, Server server) { if (roleId == null || server == null || server == NO_SERVER) { return NO_ROLE; } for (Role role : server.getRoles()) { if (roleId.equals(role.getId())) { return role; } } return NO_ROLE; } public Role findRole(String roleName, Server server) { if (roleName == null || server == null || server == NO_SERVER) { return NO_ROLE; } // Exact (case insensitive) match for (Role role : server.getRoles()) { if (roleName.equalsIgnoreCase(role.getName())) { return role; } } // No match? Try matching start Role temp = null; for (Role role : server.getRoles()) { if (role.getName().toLowerCase().startsWith(roleName)) { if (temp == null || temp.getName().length() <= temp.getName().length()) { temp = role; } } } if (temp != null) { return temp; } // Fuzzy match // TODO // ID match temp = getRole(roleName, server); if (temp != null) { return temp; } return NO_ROLE; } public Set<Role> getMemberRoles(Member member, Server server) { if (member == null || server == null || server == NO_SERVER) { return Collections.emptySet(); } Set<Role> definedRoles = member.getRoles().stream(). map(r -> getRole(r, server)). collect(Collectors.toCollection(LinkedHashSet::new)); Role everyone = findRole("@everyone", server); LinkedHashSet<Role> ret = new LinkedHashSet<>(definedRoles.size() + 1); if (everyone != null) { ret.add(everyone); } ret.addAll(definedRoles); return ret; } public Member getMemberHttp(String serverId, String userId) throws UnirestException { if ("NO_USER".equals(userId)) { return NO_MEMBER; } boolean ok = false; try { Map<String, String> headers = new HashMap<>(); headers.put(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.getMimeType()); headers.put(HttpHeaders.AUTHORIZATION, token); HttpResponse<String> response = Unirest. get("https://discordapp.com/api/guilds/" + serverId + "/members/" + userId). headers(headers). asString(); int status = response.getStatus(); if (status == 500) { // Actually a not found error return NO_MEMBER; } if (status != 200) { throw new UnirestException("HTTP " + response.getStatus() + ": " + response.getStatusText()); } Member member = gson.fromJson(response.getBody(), Member.class); if (member == null) { throw new UnirestException("Invalid entity: null"); } ok = true; return member; } catch (UnirestException e) { statistics.restErrorCount.increment(); return NO_MEMBER; } finally { update("get_member").forBool(ok); } } public ScheduledExecutorService getExecutorService() { return executorService; } public EventBus getEventBus() { return eventBus; } public DiscordWebSocketClient getWebSocketClient() { return webSocketClient; } public Statistics getStatistics() { return statistics; } public boolean isActive() { return active.get(); } public Map<String, Presence> getUserPresences() { return userPresences; } public Map<String, String> getUserGames() { return userGames; } @Subscribe public void onWebSocketClose(WebSocketCloseEvent event) { if (!active.get()) { // Ignore return; } // Reconnect active.set(false); try { openWebSocket(); } catch (IOException e) { LOGGER.warn("Unable to reopen WebSocket", e); } } public void stop() { active.set(false); executorService.shutdown(); eventBus.unregister(this); webSocketClient.close(); endpointMetricReporter.stop(); } private EndpointStats update(String endpoint) { EndpointStats stats = endpointStats.get(endpoint); if (stats == null) { stats = new EndpointStats(endpoint); stats.register(endpointMetricRegistry); endpointStats.put(endpoint, stats); } return stats; } public static class Statistics { public final LongAdder eventCount = new LongAdder(); public final LongAdder eventDispatchErrorCount = new LongAdder(); public final LongAdder connectAttemptCount = new LongAdder(); public final LongAdder restErrorCount = new LongAdder(); } private static class EndpointStats { final String endpointName; final Meter apiRequestMeter = new Meter(); final Meter apiRequestErrorMeter = new Meter(); final Meter apiRequestSuccessMeter = new Meter(); EndpointStats(String endpointName) { this.endpointName = endpointName; } void register(MetricRegistry registry) { registry.register(endpointName + ".req.httpapi", apiRequestMeter); registry.register(endpointName + ".req_err.httpapi", apiRequestErrorMeter); registry.register(endpointName + ".req_ok.httpapi", apiRequestSuccessMeter); } void success() { apiRequestMeter.mark(); apiRequestSuccessMeter.mark(); } void error() { apiRequestMeter.mark(); apiRequestErrorMeter.mark(); } void forBool(boolean ok) { if (ok) { success(); } else { error(); } } } }
src/main/java/co/phoenixlab/discord/api/DiscordApiClient.java
package co.phoenixlab.discord.api; import co.phoenixlab.common.lang.SafeNav; import co.phoenixlab.discord.api.entities.*; import co.phoenixlab.discord.api.event.LogInEvent; import co.phoenixlab.discord.api.event.UserUpdateEvent; import co.phoenixlab.discord.api.event.WebSocketCloseEvent; import co.phoenixlab.discord.cfg.DiscordApiClientConfig; import co.phoenixlab.discord.cfg.InfluxDbConfig; import co.phoenixlab.discord.util.TryingScheduledExecutor; import com.codahale.metrics.Meter; import com.codahale.metrics.MetricFilter; import com.codahale.metrics.MetricRegistry; import com.codahale.metrics.ScheduledReporter; import com.google.common.eventbus.EventBus; import com.google.common.eventbus.Subscribe; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.mashape.unirest.http.HttpResponse; import com.mashape.unirest.http.JsonNode; import com.mashape.unirest.http.Unirest; import com.mashape.unirest.http.exceptions.UnirestException; import metrics_influxdb.HttpInfluxdbProtocol; import metrics_influxdb.InfluxdbReporter; import metrics_influxdb.api.measurements.CategoriesMetricMeasurementTransformer; import org.apache.http.HttpHeaders; import org.apache.http.entity.ContentType; import org.java_websocket.client.DefaultSSLWebSocketClientFactory; import org.json.JSONArray; import org.json.simple.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.net.ssl.SSLContext; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URI; import java.net.URISyntaxException; import java.net.UnknownHostException; import java.util.*; import java.util.concurrent.ExecutionException; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.atomic.LongAdder; import java.util.function.Function; import java.util.regex.Pattern; import java.util.stream.Collectors; import static co.phoenixlab.discord.VahrhedralBot.getFeatureToggleConfig; import static java.util.concurrent.TimeUnit.MILLISECONDS; import static java.util.concurrent.TimeUnit.SECONDS; public class DiscordApiClient { public static final Server NO_SERVER = new Server("NO_SERVER"); public static final Channel NO_CHANNEL = new Channel("", "NO_CHANNEL"); public static final User NO_USER = new User("NO_USER", "NO_USER", "NO_USER", null); public static final Member NO_MEMBER = new Member(NO_USER, Collections.emptyList(), "", null); public static final Role NO_ROLE = new Role(0, 0, "NO_ROLE", false, "", false, 0); public static final String[] EMPTY_STR_ARRAY = new String[0]; public static final Pattern USER_ID_REGEX = Pattern.compile("[0-9]+"); private static final Logger LOGGER = LoggerFactory.getLogger("DiscordApiClient"); public static final String TOGGLE_API_FUZZY_NICK = "api.fuzzy.nick"; private final Map<String, EndpointStats> endpointStats = new HashMap<>(); static { NO_CHANNEL.setParent(NO_SERVER); } private final ScheduledExecutorService executorService; private final AtomicReference<String> sessionId; private final AtomicReference<User> clientUser; private final List<Server> servers; private final Map<String, Server> serverMap; private final EventBus eventBus; private final Gson gson; private final Map<String, Channel> privateChannels; private final Map<User, Channel> privateChannelsByUser; private final AtomicBoolean active; private final Statistics statistics; private final Map<String, Presence> userPresences; private final Map<String, String> userGames; private String email; private String password; private String token; private DiscordWebSocketClient webSocketClient; private DiscordApiClientConfig apiClientConfig; private MetricRegistry endpointMetricRegistry; private ScheduledReporter endpointMetricReporter; private ScheduledExecutorService metricExecutorService; public DiscordApiClient(DiscordApiClientConfig config) { apiClientConfig = config; statistics = new Statistics(); sessionId = new AtomicReference<>(); clientUser = new AtomicReference<>(); executorService = new TryingScheduledExecutor(Executors.newScheduledThreadPool(4), LOGGER); servers = new ArrayList<>(); serverMap = new HashMap<>(); privateChannels = new HashMap<>(); privateChannelsByUser = new HashMap<>(); userPresences = new HashMap<>(); userGames = new HashMap<>(); active = new AtomicBoolean(); eventBus = new EventBus((e, c) -> { LOGGER.warn("Error while handling event {} when calling {}", c.getEvent(), c.getSubscriberMethod().toGenericString()); LOGGER.warn("EventBus dispatch exception", e); statistics.eventDispatchErrorCount.increment(); }); gson = new GsonBuilder().serializeNulls().create(); eventBus.register(this); endpointMetricRegistry = new MetricRegistry(); if (config.isEnableMetrics() && config.getReportingIntervalMsec() > 0) { metricExecutorService = new TryingScheduledExecutor(Executors.newScheduledThreadPool(1), LOGGER); InfluxDbConfig idbc = config.getApiClientInfluxConfig(); HttpInfluxdbProtocol protocol = idbc.toInfluxDbProtocolConfig(); LOGGER.info("Will be connecting to InfluxDB at {}", gson.toJson(protocol)); endpointMetricReporter = InfluxdbReporter.forRegistry(endpointMetricRegistry) .protocol(protocol) .convertDurationsTo(MILLISECONDS) .convertRatesTo(SECONDS) .filter(MetricFilter.ALL) .skipIdleMetrics(true) .transformer(new CategoriesMetricMeasurementTransformer("endpoint", "stat")) .withScheduler(metricExecutorService) .build(); endpointMetricReporter.start(config.getReportingIntervalMsec(), MILLISECONDS); } } @Subscribe public void countEvent(Object object) { statistics.eventCount.increment(); } public void logIn(String token) throws IOException { this.token = token; LOGGER.info("Using provided token {}", token); openWebSocket(); } public void logIn(String email, String password) throws IOException { LOGGER.info("Attempting to log in as {}...", email); this.email = email; this.password = password; Map<String, String> authObj = new HashMap<>(); authObj.put("email", email); authObj.put("password", password); JSONObject auth = new JSONObject(authObj); HttpResponse<JsonNode> response; try { response = Unirest.post(ApiConst.LOGIN_ENDPOINT). header(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.getMimeType()). body(auth.toJSONString()). asJson(); } catch (UnirestException e) { statistics.restErrorCount.increment(); throw new IOException("Unable to log in", e); } int status = response.getStatus(); if (status != HttpURLConnection.HTTP_OK) { if (status == HttpURLConnection.HTTP_FORBIDDEN) { // Servers return FORBIDDEN for bad credentials LOGGER.warn("Unable to log in with given credentials: ", response.getStatusText()); } else { LOGGER.warn("Unable to log in, Discord may be having issues"); } statistics.restErrorCount.increment(); throw new IOException("Unable to log in: HTTP " + response.getStatus() + ": " + response.getStatusText()); } token = response.getBody().getObject().getString("token"); LOGGER.info("Successfully logged in, token is {}", token); openWebSocket(); } private void openWebSocket() throws IOException { try { int retryTimeSec = 0; do { try { final String gateway = getWebSocketGateway(); final URI gatewayUri = new URI(gateway); webSocketClient = new DiscordWebSocketClient(this, gatewayUri, apiClientConfig); SSLContext context = SSLContext.getInstance("TLS"); context.init(null, null, null); webSocketClient.setWebSocketFactory(new DefaultSSLWebSocketClientFactory(context)); } catch (URISyntaxException e) { LOGGER.warn("Bad gateway", e); throw new IOException(e); } catch (UnknownHostException ukhe) { LOGGER.warn("Unable to reach DNS server, retrying in {}s...", retryTimeSec); Thread.sleep(MILLISECONDS.convert(retryTimeSec, SECONDS)); retryTimeSec = Math.min(retryTimeSec + 2, 30); // Cap at 30 interval continue; } catch (Exception e) { LOGGER.warn("Unexpected error", e); throw new IOException(e); } statistics.connectAttemptCount.increment(); active.set(webSocketClient.connectBlocking()); if (!active.get()) { LOGGER.warn("Unable to connect, retrying in {}s...", retryTimeSec); Thread.sleep(MILLISECONDS.convert(retryTimeSec, SECONDS)); retryTimeSec = Math.min(retryTimeSec + 2, 30); // Cap at 30 interval } } while (!active.get()); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } private String getWebSocketGateway() throws IOException { boolean ok = false; try { HttpResponse<JsonNode> response; try { response = Unirest.get(ApiConst.WEBSOCKET_GATEWAY). header("authorization", token). asJson(); } catch (UnirestException e) { statistics.restErrorCount.increment(); if (e.getCause() instanceof UnknownHostException) { throw (UnknownHostException) e.getCause(); } throw new IOException("Unable to retrieve websocket gateway", e); } int status = response.getStatus(); if (status != HttpURLConnection.HTTP_OK) { statistics.restErrorCount.increment(); LOGGER.warn("Unable to retrieve websocket gateway: HTTP {}: {}", status, response.getStatusText()); throw new IOException("Unable to retrieve websocket : HTTP " + status + ": " + response.getStatusText()); } String gateway = response.getBody().getObject().getString("url"); LOGGER.info("Found WebSocket gateway at {}", gateway); ok = true; return gateway; } finally { update("get_gateway").forBool(ok); } } void onLogInEvent(LogInEvent event) { ReadyMessage readyMessage = event.getReadyMessage(); setSessionId(readyMessage.getSessionId()); LOGGER.info("Using sessionId {}", getSessionId()); User user = readyMessage.getUser(); setClientUser(user); LOGGER.info("Logged in as {}#{} ID {}", user.getUsername(), user.getDiscriminator(), user.getId()); LOGGER.info("Connected to {} servers", readyMessage.getServers().length); // We don't bother populating channel messages since we only care about new messages coming in servers.clear(); Collections.addAll(servers, readyMessage.getServers()); remapServers(); // Update presences Arrays.stream(readyMessage.getServers()). filter(Server::isAvailable). map(ReadyServer::getPresences). flatMap(Arrays::stream). forEach(p -> { String id = p.getUser().getId(); userPresences.put(id, p.getStatus()); userGames.put(id, SafeNav.of(p.getGame()).next(Game::getName).orElse("[misc.nothing]")); }); // Request to populate the large servers servers.stream().filter(Server::isLarge). forEach(this::requestLargerServerUsers); LOGGER.info("Holding {} private conversations", readyMessage.getPrivateChannels().length); for (Channel privateChannel : readyMessage.getPrivateChannels()) { privateChannels.put(privateChannel.getId(), privateChannel); privateChannelsByUser.put(privateChannel.getRecipient(), privateChannel); } } public void requestLargerServerUsers(Server server) { org.json.JSONObject object = new org.json.JSONObject(); object.put("op", 8); org.json.JSONObject requestBody = new org.json.JSONObject(); requestBody.put("guild_id", server.getId()); requestBody.put("query", ""); requestBody.put("limit", 0); object.put("d", requestBody); webSocketClient.send(object.toString()); } @Subscribe public void onUserUpdate(UserUpdateEvent event) { UserUpdate update = event.getUpdate(); User oldUser = clientUser.get(); if (!oldUser.getId().equals(update.getId())) { throw new IllegalStateException("User ID should not be able to be updated!"); } String oldEmail = email; email = update.getEmail(); User newUser = new User(update.getUsername(), update.getId(), update.getDiscriminator(), update.getAvatar()); clientUser.set(newUser); if (!oldUser.getUsername().equals(update.getUsername())) { LOGGER.info("Username changed from '{}' to '{}'", oldUser.getUsername(), update.getUsername()); } if (!oldUser.getDiscriminator().equals(update.getDiscriminator())) { LOGGER.info("Discriminator changed from '{}' to '{}'", oldUser.getDiscriminator(), update.getDiscriminator()); } if (!oldUser.getAvatar().equals(update.getAvatar())) { LOGGER.info("Avatar changed from '{}' to '{}'", oldUser.getAvatar(), update.getAvatar()); } if ((oldEmail == null) || !oldEmail.equals(email)) { LOGGER.info("Email changed from '{}' to '{}'", oldEmail, email); } // Fire off a change to ourself across all servers as well for (Server server : servers) { server.getMembers().stream(). map(Member::getUser). filter(u -> u.equals(newUser)). findFirst().ifPresent(u -> { u.setAvatar(update.getAvatar()); u.setUsername(update.getUsername()); u.setDiscriminator(update.getDiscriminator()); }); } } public Future<Message> sendMessage(String body, String channelId) { return sendMessage(body, channelId, EMPTY_STR_ARRAY, true); } public Future<Message> sendMessage(String body, Channel channel) { return sendMessage(body, channel, EMPTY_STR_ARRAY, true); } public Future<Message> sendMessage(String body, String channelId, Embed embed) { return sendMessage(body, channelId, EMPTY_STR_ARRAY, true, embed); } public Future<Message> sendMessage(String body, Channel channel, Embed embed) { return sendMessage(body, channel, EMPTY_STR_ARRAY, true, embed); } public Future<Message> sendMessage(String body, String channelId, boolean async) { return sendMessage(body, channelId, EMPTY_STR_ARRAY, async); } public Future<Message> sendMessage(String body, Channel channel, boolean async) { return sendMessage(body, channel, EMPTY_STR_ARRAY, async); } public Future<Message> sendMessage(String body, String channelId, boolean async, Embed embed) { return sendMessage(body, channelId, EMPTY_STR_ARRAY, async, embed); } public Future<Message> sendMessage(String body, Channel channel, boolean async, Embed embed) { return sendMessage(body, channel, EMPTY_STR_ARRAY, async, embed); } public Future<Message> sendMessage(String body, Channel channel, String[] mentions) { return sendMessage(body, channel.getId(), mentions); } public Future<Message> sendMessage(String body, String channelId, String[] mentions) { return sendMessage(body, channelId, mentions, true); } public Future<Message> sendMessage(String body, Channel channel, String[] mentions, Embed embed) { return sendMessage(body, channel.getId(), mentions, embed); } public Future<Message> sendMessage(String body, String channelId, String[] mentions, Embed embed) { return sendMessage(body, channelId, mentions, true, embed); } public Future<Message> sendMessage(String body, Channel channel, String[] mentions, boolean async) { return sendMessage(body, channel.getId(), mentions, async); } public Future<Message> sendMessage(String body, Channel channel, String[] mentions, boolean async, Embed embed) { return sendMessage(body, channel.getId(), mentions, async, embed); } public Future<Message> sendMessage(String body, String channelId, String[] mentions, boolean async) { return sendMessage(body, channelId, mentions, async, null); } public Future<Message> sendMessage(String body, String channelId, String[] mentions, boolean async, Embed embed) { if (body == null || channelId == null || mentions == null) { throw new IllegalArgumentException("Arguments may not be null"); } Future<Message> future = executorService.submit(() -> sendMessageInternal(body, channelId, mentions, embed)); if (!async) { try { future.get(); } catch (InterruptedException | ExecutionException e) { LOGGER.warn("Exception while waiting for sendMessage result", e); } } return future; } private Message sendMessageInternal(String body, String channelId, String[] mentions, Embed embed) { Gson g = new GsonBuilder().create(); // April fools. // String[] splitBody = body.split("\n"); // StringJoiner joiner = new StringJoiner("\n"); // for (String s : splitBody) { // joiner.add(reverseLine(s)); // } // body = joiner.toString(); boolean ok = false; try { OutboundMessage outboundMessage = new OutboundMessage(body, false, mentions, embed); String content = g.toJson(outboundMessage); HttpResponse<String> response; Map<String, String> headers = new HashMap<>(); headers.put(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.getMimeType()); headers.put(HttpHeaders.AUTHORIZATION, token); try { response = Unirest.post(ApiConst.CHANNELS_ENDPOINT + channelId + "/messages"). headers(headers). body(content). asString(); } catch (UnirestException e) { statistics.restErrorCount.increment(); LOGGER.warn("Unable to send message", e); return null; } int status = response.getStatus(); if (status != 200) { statistics.restErrorCount.increment(); LOGGER.warn("Unable to send message: HTTP {}: {}", status, response.getStatusText()); return null; } Message message = g.fromJson(response.getBody(), Message.class); ok = true; return message; } finally { update("send_message").forBool(ok); } } private String reverseLine(String s) { if (s.startsWith("NOFLIP")) { return s.substring("NOFLIP".length()); } String[] tokens = s.split(" "); StringJoiner joiner = new StringJoiner(" "); String[] outArray = new String[tokens.length]; for (int i = 0, tokensLength = tokens.length; i < tokensLength; i++) { String token = tokens[i]; if (!token.startsWith("http://") && !token.startsWith("https://")) { token = reverse(token); } outArray[outArray.length - i - 1] = token; } for(String s1 : outArray) { joiner.add(s1); } return joiner.toString(); } private String reverse(String s) { char[] chars = s.toCharArray(); char c; int length = chars.length; for (int i = 0; i < length / 2; i++) { c = chars[length - i - 1]; chars[length - i - 1] = flip(chars[i]); chars[i] = flip(c); } return new String(chars); } private char flip(char c) { switch (c) { case ')': return '('; case '(': return ')'; case '[': return ']'; case ']': return '['; case '{': return '}'; case '}': return '{'; default: return c; } } public void deleteMessage(String channelId, String messageId) { deleteMessage(channelId, messageId, true); } public void deleteMessage(String channelId, String messageId, boolean async) { if (channelId == null || messageId == null) { return; } if (async) { executorService.submit(() -> deleteMessage(channelId, messageId, false)); return; } boolean ok = false; try { HttpResponse<String> response; Map<String, String> headers = new HashMap<>(); headers.put(HttpHeaders.AUTHORIZATION, token); try { response = Unirest.delete(ApiConst.CHANNELS_ENDPOINT + channelId + "/messages/" + messageId). headers(headers). asString(); } catch (UnirestException e) { statistics.restErrorCount.increment(); LOGGER.warn("Unable to delete message", e); return; } int status = response.getStatus(); if (status != 204) { statistics.restErrorCount.increment(); LOGGER.warn("Unable to delete message: HTTP {}: {}", status, response.getStatusText()); return; } ok = true; } finally { update("delete_message").forBool(ok); } } public void bulkDeleteMessages(String channelId, String[] messageIds) { bulkDeleteMessages(channelId, messageIds, true); } public void bulkDeleteMessages(String channelId, String[] messageIds, boolean async) { if (channelId == null || messageIds == null) { return; } if (async) { executorService.submit(() -> bulkDeleteMessages(channelId, messageIds, false)); return; } boolean ok = false; try { HttpResponse<String> response; Map<String, String> headers = new HashMap<>(); headers.put(HttpHeaders.AUTHORIZATION, token); headers.put(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.getMimeType()); org.json.JSONObject body = new org.json.JSONObject(); body.put("messages", new JSONArray(messageIds)); try { String url = ApiConst.CHANNELS_ENDPOINT + channelId + "/messages/bulk-delete"; System.out.println(url); response = Unirest.post(url). headers(headers). body(body.toString()). asString(); } catch (UnirestException e) { statistics.restErrorCount.increment(); LOGGER.warn("Unable to delete messages", e); return; } int status = response.getStatus(); if (status != 204) { statistics.restErrorCount.increment(); LOGGER.warn("Unable to delete messages: HTTP {}: {}: {}", status, response.getStatusText(), response.getBody()); } else { LOGGER.info("Bulk deleted {} messages", messageIds.length); ok = true; } } finally { update("bulk_delete").forBool(ok); } } public void editMessage(String channelId, String messageId, String content) { editMessage(channelId, messageId, content, null); } public void editMessage(String channelId, String messageId, String content, boolean async) { editMessage(channelId, messageId, content, null, async); } public void editMessage(String channelId, String messageId, String content, String[] mentions) { editMessage(channelId, messageId, content, mentions, true); } public void editMessage(String channelId, String messageId, String content, String[] mentions, boolean async) { if (channelId == null || messageId == null || content == null) { return; } if (async) { executorService.submit(() -> editMessage(channelId, messageId, content, mentions, false)); return; } boolean ok = false; try { // TODO Add support for mention changes Map<String, Object> ret = new HashMap<>(); ret.put("content", content); JSONObject object = new JSONObject(ret); HttpResponse<JsonNode> response; Map<String, String> headers = new HashMap<>(); headers.put(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.getMimeType()); headers.put(HttpHeaders.AUTHORIZATION, token); try { response = Unirest.patch(ApiConst.CHANNELS_ENDPOINT + channelId + "/messages/" + messageId). headers(headers). body(object.toJSONString()). asJson(); } catch (UnirestException e) { statistics.restErrorCount.increment(); LOGGER.warn("Unable to edit message", e); return; } int status = response.getStatus(); if (status != 200) { statistics.restErrorCount.increment(); LOGGER.warn("Unable to edit message: HTTP {}: {}", status, response.getStatusText()); return; } ok = true; } finally { update("edit_message").forBool(ok); } } // public Future<Message[]> getChannelHistory(String channelId, String before, int limit) { // // } // Message[] getChannelHistoryInternal(String channelId, String before, int limit) { // try { // Map<String, String> headers = new HashMap<>(); // headers.put(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.getMimeType()); // headers.put(HttpHeaders.AUTHORIZATION, token); // Map<String, Object> queryParams = new HashMap<>(); // queryParams.put("limit", Math.max(1, Math.min(limit, 50))); // if (before != null) { // queryParams.put("before", before); // } // HttpResponse<JsonNode> response = Unirest.get(ApiConst.CHANNELS_ENDPOINT + // channelId + "/messages"). // headers(headers). // queryString(queryParams). // asJson(); // int status = response.getStatus(); // if (status != 200) { // statistics.restErrorCount.increment(); // LOGGER.warn("Unable to retrieve message: HTTP {}: {}", status, response.getStatusText()); // return null; // } // JSONArray ret = response.getBody().getArray(); // // // } catch (UnirestException e) { // statistics.restErrorCount.increment(); // LOGGER.warn("Unable to retrieve message"); // return null; // } // } public void updateNowPlaying(String message) { webSocketClient.sendNowPlayingUpdate(message); } public void updateRolesByObj(User user, Server server, Collection<Role> roles) { updateRolesByObj(user, server, roles, true); } public void updateRolesByObj(User user, Server server, Collection<Role> roles, boolean async) { List<String> r = roles.stream().map(Role::getId).collect(Collectors.toList()); updateRoles(user, server, r, async); } public void updateRoles(User user, Server server, Collection<String> roles) { updateRoles(user, server, roles, true); } public void updateRoles(User user, Server server, Collection<String> roles, boolean async) { if (async) { executorService.submit(() -> updateRoles(user, server, roles, false)); return; } boolean ok = false; try { Map<String, String> headers = new HashMap<>(); headers.put(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.getMimeType()); headers.put(HttpHeaders.AUTHORIZATION, token); org.json.JSONObject object = new org.json.JSONObject(); object.put("roles", roles); HttpResponse<JsonNode> r = Unirest.patch(ApiConst.SERVERS_ENDPOINT + server.getId() + "/members/" + user.getId()). headers(headers). body(object.toString()). asJson(); int status = r.getStatus(); if (status < 200 || status >= 300) { statistics.restErrorCount.increment(); LOGGER.warn("Unable to update member {} ({}) roles in {} ({}): HTTP {}: {}", user.getUsername(), user.getId(), server.getName(), server.getId(), status, r.getStatusText()); return; } ok = true; } catch (UnirestException e) { statistics.restErrorCount.increment(); LOGGER.warn("Unable to update member {} ({}) roles in {} ({})", user.getUsername(), user.getId(), server.getName(), server.getId()); LOGGER.warn("Unable to update member roles", e); return; } finally { update("update_roles").forBool(ok); } } public String getToken() { return token; } public String getSessionId() { return sessionId.get(); } public void setSessionId(String sessionId) { this.sessionId.set(sessionId); } public User getClientUser() { return clientUser.get(); } public void setClientUser(User user) { clientUser.set(user); } public List<Server> getServers() { return servers; } public Map<String, Server> getServerMap() { return serverMap; } public Server getServerByID(String id) { Server server = serverMap.get(id); if (server == null) { server = NO_SERVER; } return server; } public Map<String, Channel> getPrivateChannels() { return privateChannels; } public Map<User, Channel> getPrivateChannelsByUserMap() { return privateChannelsByUser; } public Channel getPrivateChannelById(String id) { return privateChannels.get(id); } public Channel getPrivateChannelByUser(User user) { return privateChannelsByUser.get(user); } public void remapServers() { serverMap.clear(); serverMap.putAll(servers.stream().collect(Collectors.toMap(Server::getId, Function.identity()))); servers.stream(). filter(Server::isAvailable). forEach(server -> server.getChannels().forEach(channel -> channel.setParent(server))); } public Channel getChannelById(String id) { if (id == null) { return NO_CHANNEL; } return servers.stream(). filter(Server::isAvailable). map(Server::getChannels). flatMap(Set::stream). filter(c -> id.equals(c.getId())). findFirst().orElse(getPrivateChannelByIdAsChannel(id)); } public Channel getPrivateChannelByIdAsChannel(String id) { Channel privateChannel = getPrivateChannelById(id); if (privateChannel != null) { return privateChannel; } return NO_CHANNEL; } public Channel getChannelById(String id, Server server) { if (id == null) { return NO_CHANNEL; } if (server == null || server == NO_SERVER) { return getChannelById(id); } return server.getChannels().stream(). filter(c -> id.equals(c.getId())). findFirst().orElse(NO_CHANNEL); } public User findUser(String username) { if (username == null) { return NO_USER; } username = username.toLowerCase(); for (Server server : servers) { User user = findUser(username, server); if (user != NO_USER) { return user; } } return NO_USER; } public User findUser(String username, Server server) { if (username == null) { return NO_USER; } if (server == null || server == NO_SERVER) { return findUser(username); } username = username.toLowerCase(); if (getFeatureToggleConfig().getToggle(TOGGLE_API_FUZZY_NICK).use(server.getId())) { for (Member member : server.getMembers()) { if (username.equalsIgnoreCase(member.getNickOrUsername())) { return member.getUser(); } } Member temp = null; // No match? Try matching start for (Member member : server.getMembers()) { if (member.getNickOrUsername().toLowerCase().startsWith(username)) { if (temp == null || member.getNickOrUsername().length() <= temp.getNickOrUsername().length()) { temp = member; } } } if (temp != null) { return temp.getUser(); } } else { for (Member member : server.getMembers()) { User user = member.getUser(); if (username.equalsIgnoreCase(user.getUsername())) { return user; } } Member temp = null; // No match? Try matching start for (Member member : server.getMembers()) { User user = member.getUser(); if (user.getUsername().toLowerCase().startsWith(username)) { if (temp == null || user.getUsername().length() <= temp.getUser().getUsername().length()) { temp = member; } } } if (temp != null) { return temp.getUser(); } } // ID match if (USER_ID_REGEX.matcher(username).matches()) { User tempU = getUserById(username, server); if (tempU != null) { return tempU; } } // Still no match? Try fuzzy match // TODO return NO_USER; } public User getUserById(String userId) { return getUserById(userId, true); } public User getUserById(String userId, boolean useApi) { if (userId == null || "NO_USER".equals(userId)) { return NO_USER; } for (Server server : servers) { User user = getUserById(userId, server, useApi); if (user != NO_USER) { return user; } } return NO_USER; } public User getUserById(String userId, Server server) { return getUserById(userId, server, true); } public User getUserById(String userId, Server server, boolean useApi) { if (userId == null || "NO_USER".equals(userId)) { return NO_USER; } if (server == null || server == NO_SERVER) { return getUserById(userId); } if (server.getMembers() == null) { LOGGER.warn("Server {} {} has null member list", server.getId(), server.getName()); return NO_USER; } for (Member member : server.getMembers()) { User user = member.getUser(); if (user.getId().equals(userId)) { return user; } } // Try API endpoint if (useApi) { try { Member member = getMemberHttp(server.getId(), userId); if (member != NO_MEMBER) { server.getMembers().add(member); return member.getUser(); } else { LOGGER.warn("User {} not found via HTTP", userId); } } catch (Exception e) { LOGGER.warn("Unable to get user " + userId + " via HTTP", e); } } return NO_USER; } public Member getUserMember(User user, Server server) { if (user == null || user == NO_USER) { return NO_MEMBER; } return getUserMember(user.getId(), server); } public Member getUserMember(String userId, Server server) { if (userId == null || server == null || server == NO_SERVER || "NO_USER".equals(userId)) { return NO_MEMBER; } for (Member member : server.getMembers()) { User user = member.getUser(); if (user.getId().equals(userId)) { return member; } } // Try API endpoint try { Member member = getMemberHttp(server.getId(), userId); if (member != NO_MEMBER) { server.getMembers().add(member); return member; } else { LOGGER.warn("User {} not found via HTTP", userId); } } catch (Exception e) { LOGGER.warn("Unable to get user " + userId + " via HTTP", e); } return NO_MEMBER; } public Role getRole(String roleId, Server server) { if (roleId == null || server == null || server == NO_SERVER) { return NO_ROLE; } for (Role role : server.getRoles()) { if (roleId.equals(role.getId())) { return role; } } return NO_ROLE; } public Role findRole(String roleName, Server server) { if (roleName == null || server == null || server == NO_SERVER) { return NO_ROLE; } // Exact (case insensitive) match for (Role role : server.getRoles()) { if (roleName.equalsIgnoreCase(role.getName())) { return role; } } // No match? Try matching start Role temp = null; for (Role role : server.getRoles()) { if (role.getName().toLowerCase().startsWith(roleName)) { if (temp == null || temp.getName().length() <= temp.getName().length()) { temp = role; } } } if (temp != null) { return temp; } // Fuzzy match // TODO // ID match temp = getRole(roleName, server); if (temp != null) { return temp; } return NO_ROLE; } public Set<Role> getMemberRoles(Member member, Server server) { if (member == null || server == null || server == NO_SERVER) { return Collections.emptySet(); } Set<Role> definedRoles = member.getRoles().stream(). map(r -> getRole(r, server)). collect(Collectors.toCollection(LinkedHashSet::new)); Role everyone = findRole("@everyone", server); LinkedHashSet<Role> ret = new LinkedHashSet<>(definedRoles.size() + 1); if (everyone != null) { ret.add(everyone); } ret.addAll(definedRoles); return ret; } public Member getMemberHttp(String serverId, String userId) throws UnirestException { if ("NO_USER".equals(userId)) { return NO_MEMBER; } boolean ok = false; try { Map<String, String> headers = new HashMap<>(); headers.put(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.getMimeType()); headers.put(HttpHeaders.AUTHORIZATION, token); HttpResponse<String> response = Unirest. get("https://discordapp.com/api/guilds/" + serverId + "/members/" + userId). headers(headers). asString(); int status = response.getStatus(); if (status == 500) { // Actually a not found error return NO_MEMBER; } if (status != 200) { throw new UnirestException("HTTP " + response.getStatus() + ": " + response.getStatusText()); } Member member = gson.fromJson(response.getBody(), Member.class); if (member == null) { throw new UnirestException("Invalid entity: null"); } ok = true; return member; } catch (UnirestException e) { statistics.restErrorCount.increment(); return NO_MEMBER; } finally { update("get_member").forBool(ok); } } public ScheduledExecutorService getExecutorService() { return executorService; } public EventBus getEventBus() { return eventBus; } public DiscordWebSocketClient getWebSocketClient() { return webSocketClient; } public Statistics getStatistics() { return statistics; } public boolean isActive() { return active.get(); } public Map<String, Presence> getUserPresences() { return userPresences; } public Map<String, String> getUserGames() { return userGames; } @Subscribe public void onWebSocketClose(WebSocketCloseEvent event) { if (!active.get()) { // Ignore return; } // Reconnect active.set(false); try { openWebSocket(); } catch (IOException e) { LOGGER.warn("Unable to reopen WebSocket", e); } } public void stop() { active.set(false); executorService.shutdown(); eventBus.unregister(this); webSocketClient.close(); endpointMetricReporter.stop(); } private EndpointStats update(String endpoint) { EndpointStats stats = endpointStats.get(endpoint); if (stats == null) { stats = new EndpointStats(endpoint); stats.register(endpointMetricRegistry); endpointStats.put(endpoint, stats); } return stats; } public static class Statistics { public final LongAdder eventCount = new LongAdder(); public final LongAdder eventDispatchErrorCount = new LongAdder(); public final LongAdder connectAttemptCount = new LongAdder(); public final LongAdder restErrorCount = new LongAdder(); } private static class EndpointStats { final String endpointName; final Meter apiRequestMeter = new Meter(); final Meter apiRequestErrorMeter = new Meter(); final Meter apiRequestSuccessMeter = new Meter(); EndpointStats(String endpointName) { this.endpointName = endpointName; } void register(MetricRegistry registry) { registry.register(endpointName + ".req.httpapi", apiRequestMeter); registry.register(endpointName + ".req_err.httpapi", apiRequestErrorMeter); registry.register(endpointName + ".req_ok.httpapi", apiRequestSuccessMeter); } void success() { apiRequestMeter.mark(); apiRequestSuccessMeter.mark(); } void error() { apiRequestMeter.mark(); apiRequestErrorMeter.mark(); } void forBool(boolean ok) { if (ok) { success(); } else { error(); } } } }
Try matching username after failing nickname
src/main/java/co/phoenixlab/discord/api/DiscordApiClient.java
Try matching username after failing nickname
Java
mpl-2.0
b7b0611875ba4ed6bef7da58b8346d1cb65b640b
0
gertux/LiPaMP,gertux/LiPaMP
package be.hobbiton.maven.lipamp.deb; import be.hobbiton.maven.lipamp.common.*; import be.hobbiton.maven.lipamp.common.ArchiveEntry.ArchiveEntryType; import org.apache.commons.compress.archivers.ar.ArArchiveEntry; import org.apache.commons.compress.archivers.ar.ArArchiveOutputStream; import org.apache.commons.compress.archivers.tar.TarArchiveEntry; import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream; import org.apache.commons.compress.archivers.tar.TarConstants; import org.apache.commons.compress.compressors.CompressorException; import org.apache.commons.compress.compressors.CompressorOutputStream; import org.apache.commons.compress.compressors.CompressorStreamFactory; import org.apache.maven.plugin.logging.Log; import java.io.*; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.Collection; import java.util.stream.Collectors; import static be.hobbiton.maven.lipamp.common.ArchiveEntry.ArchiveEntryType.F; import static be.hobbiton.maven.lipamp.common.Constants.CURRENT_DIR; import static be.hobbiton.maven.lipamp.common.Constants.CURRENT_DIR_PATH; public class DebianPackage implements Packager { static final int DEFAULT_DIR_MODE = Integer.parseInt("755", 8); static final int DEFAULT_FILE_MODE = Integer.parseInt("644", 8); private static final String ROOTUSERNAME = "root"; private static final String ROOTGROUPNAME = "root"; private static final int DEFAULT_BUFFER_SIZE = 1024 * 8; private static final byte[] DEBIAN_BINARY_2_0 = "2.0\n".getBytes(); private Collection<ArchiveEntry> controlFiles; private Collection<ArchiveEntry> dataFiles; private Log logger; public DebianPackage(Collection<File> controlFiles, Collection<ArchiveEntry> dataFiles, Log logger) { this.logger = logger; setControlFiles(controlFiles); setDataArchiveEntries(dataFiles); } public DebianPackage(Log logger, Collection<Path> controlFilePaths, Collection<ArchiveEntry> dataArchiveEntries) { this.logger = logger; setControlPaths(controlFilePaths); setDataArchiveEntries(dataArchiveEntries); } public static int copy(InputStream input, OutputStream output) throws IOException { byte[] buffer = new byte[DEFAULT_BUFFER_SIZE]; int count = 0; int n = 0; while (-1 != (n = input.read(buffer))) { output.write(buffer, 0, n); count += n; } return count; } private final void setControlPaths(Collection<Path> controlPaths) { if (controlPaths != null && !controlPaths.isEmpty()) { this.controlFiles = controlPaths.stream().filter(Files::isRegularFile).map(path -> new FileArchiveEntry(CURRENT_DIR_PATH.resolve(path.getFileName ()).toString(), path.toFile(), ROOTUSERNAME, ROOTGROUPNAME, DEFAULT_FILE_MODE)).collect(Collectors.toList()); } else { throw new IllegalArgumentException("Invalid control files"); } } private final void setControlFiles(Collection<File> controlFiles) { if (controlFiles != null && !controlFiles.isEmpty()) { this.controlFiles = new ArrayList<>(); for (File controlFile : controlFiles) { if (controlFile.isFile()) { this.controlFiles.add(new ArchiveEntry(CURRENT_DIR + controlFile.getName(), controlFile, ROOTUSERNAME, ROOTGROUPNAME, DEFAULT_FILE_MODE, F)); } else { throw new IllegalArgumentException("Invalid control file: " + controlFile.getName()); } } } else { throw new IllegalArgumentException("Invalid control files"); } } private final void setDataArchiveEntries(Collection<ArchiveEntry> dataFiles) { if (dataFiles != null && !dataFiles.isEmpty()) { this.dataFiles = dataFiles; } else { throw new IllegalArgumentException("Invalid data files"); } } @Override public void write(File outputFile) { this.logger.debug("WRITING to " + outputFile.getAbsolutePath()); ArArchiveOutputStream debianArchiveOutputStream = getDebianArchiveOutputStream(outputFile); File controlFile = writeControl(); File dataFile = writeData(); writeDebianArchive(debianArchiveOutputStream, controlFile, dataFile); } private ArArchiveOutputStream getDebianArchiveOutputStream(File outputFile) { try { return new ArArchiveOutputStream(new FileOutputStream(outputFile)); } catch (FileNotFoundException e) { throw new DebianPackageException("Cannot create Debian package file " + outputFile.getPath(), e); } } private void writeDebianArchive(ArArchiveOutputStream debianArchiveOutputStream, File controlFile, File dataFile) { try { ArArchiveEntry debianBinaryArArchiveEntry = new ArArchiveEntry("debian-binary", 4); debianArchiveOutputStream.putArchiveEntry(debianBinaryArArchiveEntry); debianArchiveOutputStream.write(DEBIAN_BINARY_2_0); debianArchiveOutputStream.closeArchiveEntry(); ArArchiveEntry controlFileArArchiveEntry = new ArArchiveEntry("control.tar.gz", controlFile.length()); debianArchiveOutputStream.putArchiveEntry(controlFileArArchiveEntry); copy(new FileInputStream(controlFile), debianArchiveOutputStream); debianArchiveOutputStream.closeArchiveEntry(); deleteTempFile(controlFile); ArArchiveEntry dataFileArArchiveEntry = new ArArchiveEntry("data.tar.gz", dataFile.length()); debianArchiveOutputStream.putArchiveEntry(dataFileArArchiveEntry); copy(new FileInputStream(dataFile), debianArchiveOutputStream); debianArchiveOutputStream.closeArchiveEntry(); deleteTempFile(dataFile); } catch (IOException e) { throw new DebianPackageException("Cannot write debian archive", e); } } private void deleteTempFile(File tempFile) { try { Files.delete(tempFile.toPath()); } catch (IOException e) { this.logger.warn("Failed to delete temp file ".concat(tempFile.toString()), e); } } private File writeControl() { if (logger.isDebugEnabled()) { logger.debug("Writing control archive"); } return writeCompressedArchive(this.controlFiles); } private File writeData() { if (logger.isDebugEnabled()) { logger.debug("Writing data archive"); } return writeCompressedArchive(this.dataFiles); } private String getTarName(String path) { if (path.startsWith("/")) { return "." + path; } return path; } private File writeCompressedArchive(Collection<ArchiveEntry> archiveEntries) { File outputFile = createTempDebianFile(); try (CompressorOutputStream gzippedOutput = new CompressorStreamFactory().createCompressorOutputStream(CompressorStreamFactory.GZIP, new FileOutputStream(outputFile)); TarArchiveOutputStream tarOutput = writeTarArchive(archiveEntries, gzippedOutput)) { return outputFile; } catch (IOException e) { throw new DebianPackageException("Cannot write compressed archive", e); } catch (CompressorException e) { throw new DebianPackageException("Cannot compress archive", e); } } private File createTempDebianFile() { try { File outputFile = File.createTempFile("lipm", ".tar.gz"); outputFile.deleteOnExit(); return outputFile; } catch (IOException e) { throw new DebianPackageException("Cannot create temp file", e); } } private TarArchiveOutputStream writeTarArchive(Collection<ArchiveEntry> archiveEntries, CompressorOutputStream gzippedOutput) throws IOException { TarArchiveOutputStream tarOutput; tarOutput = new TarArchiveOutputStream(gzippedOutput); tarOutput.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU); for (ArchiveEntry fileEntry : archiveEntries) { if (logger.isDebugEnabled()) { logger.debug("Archiving ".concat(String.valueOf(fileEntry))); } TarArchiveEntry entry; if (ArchiveEntryType.S.equals(fileEntry.getType())) { entry = new TarArchiveEntry(getTarName(fileEntry.getName()), TarConstants.LF_SYMLINK); entry.setLinkName(((SymbolicLinkArchiveEntry) fileEntry).getTarget()); } else { entry = new TarArchiveEntry(getTarName(fileEntry.getName())); } if (ArchiveEntryType.F.equals(fileEntry.getType())) { checkContentsFile(fileEntry); entry.setSize(fileEntry.getFile().length()); } entry.setUserName(fileEntry.getUserName()); entry.setGroupName(fileEntry.getGroupName()); entry.setMode(fileEntry.getMode()); tarOutput.putArchiveEntry(entry); if (ArchiveEntryType.F.equals(fileEntry.getType())) { try(FileInputStream fis = new FileInputStream(fileEntry.getFile())) { copy(fis, tarOutput); } } tarOutput.closeArchiveEntry(); } return tarOutput; } private void checkContentsFile(ArchiveEntry fileEntry) { if (fileEntry.getFile() == null) { throw new DebianPackageException("Cannot write compressed archive, missing file for " + fileEntry.getName()); } } public static class DebianPackageException extends LinuxPackagingException { private static final long serialVersionUID = -6514618016610125079L; public DebianPackageException(String message) { super(message); } public DebianPackageException(String message, Throwable cause) { super(message, cause); } } }
src/main/java/be/hobbiton/maven/lipamp/deb/DebianPackage.java
package be.hobbiton.maven.lipamp.deb; import be.hobbiton.maven.lipamp.common.*; import be.hobbiton.maven.lipamp.common.ArchiveEntry.ArchiveEntryType; import org.apache.commons.compress.archivers.ar.ArArchiveEntry; import org.apache.commons.compress.archivers.ar.ArArchiveOutputStream; import org.apache.commons.compress.archivers.tar.TarArchiveEntry; import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream; import org.apache.commons.compress.archivers.tar.TarConstants; import org.apache.commons.compress.compressors.CompressorException; import org.apache.commons.compress.compressors.CompressorOutputStream; import org.apache.commons.compress.compressors.CompressorStreamFactory; import org.apache.maven.plugin.logging.Log; import java.io.*; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.Collection; import java.util.stream.Collectors; import static be.hobbiton.maven.lipamp.common.ArchiveEntry.ArchiveEntryType.F; import static be.hobbiton.maven.lipamp.common.Constants.CURRENT_DIR; import static be.hobbiton.maven.lipamp.common.Constants.CURRENT_DIR_PATH; public class DebianPackage implements Packager { static final int DEFAULT_DIR_MODE = Integer.parseInt("755", 8); static final int DEFAULT_FILE_MODE = Integer.parseInt("644", 8); private static final String ROOTUSERNAME = "root"; private static final String ROOTGROUPNAME = "root"; private static final int DEFAULT_BUFFER_SIZE = 1024 * 8; private static final byte[] DEBIAN_BINARY_2_0 = "2.0\n".getBytes(); private Collection<ArchiveEntry> controlFiles; private Collection<ArchiveEntry> dataFiles; private Log logger; public DebianPackage(Collection<File> controlFiles, Collection<ArchiveEntry> dataFiles, Log logger) { this.logger = logger; setControlFiles(controlFiles); setDataArchiveEntries(dataFiles); } public DebianPackage(Log logger, Collection<Path> controlFilePaths, Collection<ArchiveEntry> dataArchiveEntries) { this.logger = logger; setControlPaths(controlFilePaths); setDataArchiveEntries(dataArchiveEntries); } public static int copy(InputStream input, OutputStream output) throws IOException { byte[] buffer = new byte[DEFAULT_BUFFER_SIZE]; int count = 0; int n = 0; while (-1 != (n = input.read(buffer))) { output.write(buffer, 0, n); count += n; } return count; } private final void setControlPaths(Collection<Path> controlPaths) { if (controlPaths != null && !controlPaths.isEmpty()) { this.controlFiles = controlPaths.stream().filter(Files::isRegularFile).map(path -> new FileArchiveEntry(CURRENT_DIR_PATH.resolve(path.getFileName ()).toString(), path.toFile(), ROOTUSERNAME, ROOTGROUPNAME, DEFAULT_FILE_MODE)).collect(Collectors.toList()); } else { throw new IllegalArgumentException("Invalid control files"); } } private final void setControlFiles(Collection<File> controlFiles) { if (controlFiles != null && !controlFiles.isEmpty()) { this.controlFiles = new ArrayList<>(); for (File controlFile : controlFiles) { if (controlFile.isFile()) { this.controlFiles.add(new ArchiveEntry(CURRENT_DIR + controlFile.getName(), controlFile, ROOTUSERNAME, ROOTGROUPNAME, DEFAULT_FILE_MODE, F)); } else { throw new IllegalArgumentException("Invalid control file: " + controlFile.getName()); } } } else { throw new IllegalArgumentException("Invalid control files"); } } private final void setDataArchiveEntries(Collection<ArchiveEntry> dataFiles) { if (dataFiles != null && !dataFiles.isEmpty()) { this.dataFiles = dataFiles; } else { throw new IllegalArgumentException("Invalid data files"); } } @Override public void write(File outputFile) { this.logger.debug("WRITING to " + outputFile.getAbsolutePath()); ArArchiveOutputStream debianArchiveOutputStream = getDebianArchiveOutputStream(outputFile); File controlFile = writeControl(); File dataFile = writeData(); writeDebianArchive(debianArchiveOutputStream, controlFile, dataFile); } private ArArchiveOutputStream getDebianArchiveOutputStream(File outputFile) { try { return new ArArchiveOutputStream(new FileOutputStream(outputFile)); } catch (FileNotFoundException e) { throw new DebianPackageException("Cannot create Debian package file " + outputFile.getPath(), e); } } private void writeDebianArchive(ArArchiveOutputStream debianArchiveOutputStream, File controlFile, File dataFile) { try { ArArchiveEntry debianBinaryArArchiveEntry = new ArArchiveEntry("debian-binary", 4); debianArchiveOutputStream.putArchiveEntry(debianBinaryArArchiveEntry); debianArchiveOutputStream.write(DEBIAN_BINARY_2_0); debianArchiveOutputStream.closeArchiveEntry(); ArArchiveEntry controlFileArArchiveEntry = new ArArchiveEntry("control.tar.gz", controlFile.length()); debianArchiveOutputStream.putArchiveEntry(controlFileArArchiveEntry); copy(new FileInputStream(controlFile), debianArchiveOutputStream); debianArchiveOutputStream.closeArchiveEntry(); deleteTempFile(controlFile); ArArchiveEntry dataFileArArchiveEntry = new ArArchiveEntry("data.tar.gz", dataFile.length()); debianArchiveOutputStream.putArchiveEntry(dataFileArArchiveEntry); copy(new FileInputStream(dataFile), debianArchiveOutputStream); debianArchiveOutputStream.closeArchiveEntry(); deleteTempFile(dataFile); } catch (IOException e) { throw new DebianPackageException("Cannot write debian archive", e); } } private void deleteTempFile(File tempFile) { try { Files.delete(tempFile.toPath()); } catch (IOException e) { this.logger.warn("Failed to delete temp file ".concat(tempFile.toString()), e); } } private File writeControl() { if (logger.isDebugEnabled()) { logger.debug("Writing control archive"); } return writeCompressedArchive(this.controlFiles); } private File writeData() { if (logger.isDebugEnabled()) { logger.debug("Writing data archive"); } return writeCompressedArchive(this.dataFiles); } private String getTarName(String path) { if (path.startsWith("/")) { return "." + path; } return path; } private File writeCompressedArchive(Collection<ArchiveEntry> archiveEntries) { File outputFile = createTempDebianFile(); try (CompressorOutputStream gzippedOutput = new CompressorStreamFactory().createCompressorOutputStream(CompressorStreamFactory.GZIP, new FileOutputStream(outputFile)); TarArchiveOutputStream tarOutput = writeTarArchive(archiveEntries, gzippedOutput)) { return outputFile; } catch (IOException e) { throw new DebianPackageException("Cannot write compressed archive", e); } catch (CompressorException e) { throw new DebianPackageException("Cannot compress archive", e); } } private File createTempDebianFile() { try { File outputFile = File.createTempFile("lipm", ".tar.gz"); outputFile.deleteOnExit(); return outputFile; } catch (IOException e) { throw new DebianPackageException("Cannot create temp file", e); } } private TarArchiveOutputStream writeTarArchive(Collection<ArchiveEntry> archiveEntries, CompressorOutputStream gzippedOutput) throws IOException { TarArchiveOutputStream tarOutput; tarOutput = new TarArchiveOutputStream(gzippedOutput); tarOutput.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU); for (ArchiveEntry fileEntry : archiveEntries) { if (logger.isDebugEnabled()) { logger.debug("Archiving ".concat(String.valueOf(fileEntry))); } TarArchiveEntry entry; if (ArchiveEntryType.S.equals(fileEntry.getType())) { entry = new TarArchiveEntry(getTarName(fileEntry.getName()), TarConstants.LF_SYMLINK); entry.setLinkName(((SymbolicLinkArchiveEntry) fileEntry).getTarget()); } else { entry = new TarArchiveEntry(getTarName(fileEntry.getName())); } if (ArchiveEntryType.F.equals(fileEntry.getType())) { checkContentsFile(fileEntry); entry.setSize(fileEntry.getFile().length()); } entry.setUserName(fileEntry.getUserName()); entry.setGroupName(fileEntry.getGroupName()); entry.setMode(fileEntry.getMode()); tarOutput.putArchiveEntry(entry); if (ArchiveEntryType.F.equals(fileEntry.getType())) { copy(new FileInputStream(fileEntry.getFile()), tarOutput); } tarOutput.closeArchiveEntry(); } return tarOutput; } private void checkContentsFile(ArchiveEntry fileEntry) { if (fileEntry.getFile() == null) { throw new DebianPackageException("Cannot write compressed archive, missing file for " + fileEntry.getName()); } } public static class DebianPackageException extends LinuxPackagingException { private static final long serialVersionUID = -6514618016610125079L; public DebianPackageException(String message) { super(message); } public DebianPackageException(String message, Throwable cause) { super(message, cause); } } }
close files early, closes #9
src/main/java/be/hobbiton/maven/lipamp/deb/DebianPackage.java
close files early, closes #9
Java
agpl-3.0
c6071eac248c41f0004b6be8356b32968a33c6f4
0
qiuyesuifeng/sql-layer,relateiq/sql-layer,relateiq/sql-layer,qiuyesuifeng/sql-layer,shunwang/sql-layer-1,relateiq/sql-layer,relateiq/sql-layer,wfxiang08/sql-layer-1,wfxiang08/sql-layer-1,jaytaylor/sql-layer,qiuyesuifeng/sql-layer,ngaut/sql-layer,jaytaylor/sql-layer,shunwang/sql-layer-1,shunwang/sql-layer-1,wfxiang08/sql-layer-1,ngaut/sql-layer,wfxiang08/sql-layer-1,qiuyesuifeng/sql-layer,jaytaylor/sql-layer,jaytaylor/sql-layer,ngaut/sql-layer,ngaut/sql-layer,shunwang/sql-layer-1
package com.akiban.cserver.itests.bugs.bug695495; import com.akiban.ais.model.Index; import com.akiban.ais.model.IndexColumn; import com.akiban.ais.model.UserTable; import com.akiban.cserver.InvalidOperationException; import com.akiban.cserver.api.ddl.ParseException; import com.akiban.cserver.itests.ApiTestBase; import org.junit.After; import org.junit.Test; import java.util.*; import static junit.framework.Assert.*; public final class IndexNamesIT extends ApiTestBase { private static final String BASE_DDL = "CREATE TABLE t1(\n\tc1 tinyint(4) not null, c2 int(11) DEFAULT NULL, "; @After public void myTearDown() { debug("------------------------------------"); } @Test public void oneCustomNamedIndex() { UserTable userTable = createTableWithIndexes("PRIMARY KEY (c1), KEY myNamedKey(c2)"); assertIndexes(userTable, "PRIMARY", "myNamedKey"); assertIndexColumns(userTable, "PRIMARY", "c1"); assertIndexColumns(userTable, "myNamedKey", "c2"); } @Test public void oneStandardNamedIndex() { UserTable userTable = createTableWithIndexes("PRIMARY KEY (`c1`), KEY `c2` (`c2`)"); assertIndexes(userTable, "PRIMARY", "c2"); assertIndexColumns(userTable, "PRIMARY", "c1"); assertIndexColumns(userTable, "c2", "c2"); } @Test public void oneUnnamedIndex() { UserTable userTable = createTableWithIndexes("PRIMARY KEY (c1), KEY (c2)"); assertIndexes(userTable, "PRIMARY", "c2"); assertIndexColumns(userTable, "PRIMARY", "c1"); assertIndexColumns(userTable, "c2", "c2"); } @Test public void twoIndexesNoConflict() { UserTable userTable = createTableWithIndexes("PRIMARY KEY (c1), KEY (c2), KEY multiColumnIndex(c2, c1)"); assertIndexes(userTable, "PRIMARY", "c2", "multiColumnIndex"); assertIndexColumns(userTable, "PRIMARY", "c1"); assertIndexColumns(userTable, "c2", "c2"); assertIndexColumns(userTable, "multiColumnIndex", "c2", "c1"); } @Test public void twoUnnamedIndexes() { UserTable userTable = createTableWithIndexes("PRIMARY KEY (c1), KEY (c2), KEY (c2, c1)"); assertIndexes(userTable, "PRIMARY", "c2", "c2_2"); assertIndexColumns(userTable, "PRIMARY", "c1"); assertIndexColumns(userTable, "c2", "c2"); assertIndexColumns(userTable, "c2_2", "c2", "c1"); } @Test public void fkFullyNamed() { UserTable userTable = createTableWithFK("fk_constraint_1", "fk_index_1", null); assertIndexes(userTable, "PRIMARY", "fk_constraint_1"); assertIndexColumns(userTable, "PRIMARY", "c1"); assertIndexColumns(userTable, "fk_constraint_1", "c2"); } @Test public void fkOnlyConstraintNamed() { UserTable userTable = createTableWithFK("fk_constraint_1", null, null); assertIndexes(userTable, "PRIMARY", "fk_constraint_1"); assertIndexColumns(userTable, "PRIMARY", "c1"); assertIndexColumns(userTable, "fk_constraint_1", "c2"); } @Test public void fkOnlyIndexNamed() { UserTable userTable = createTableWithFK(null, "fk_index_1", null); assertIndexes(userTable, "PRIMARY", "fk_index_1"); assertIndexColumns(userTable, "PRIMARY", "c1"); assertIndexColumns(userTable, "fk_index_1", "c2"); } @Test public void fkNeitherNamed() { UserTable userTable = createTableWithFK(null, null, null); assertIndexes(userTable, "PRIMARY", "c2"); assertIndexColumns(userTable, "PRIMARY", "c1"); assertIndexColumns(userTable, "c2", "c2"); } @Test public void fkWithSingleColumnKeyUnnamed() { UserTable userTable = createTableWithFK(null, null, "key (c2)"); assertIndexes(userTable, "PRIMARY", "c2"); assertIndexColumns(userTable, "PRIMARY", "c1"); assertIndexColumns(userTable, "c2", "c2"); } @Test public void fkWithSingleColumnKeyNamed() { UserTable userTable = createTableWithFK(null, null, "key `index_2` (c2)"); assertIndexes(userTable, "PRIMARY", "index_2"); assertIndexColumns(userTable, "PRIMARY", "c1"); assertIndexColumns(userTable, "index_2", "c2"); } @Test public void fkWithTwoColumnKeyUnnamed() { UserTable userTable = createTableWithFK(null, null, "key (c2, c1)"); assertIndexes(userTable, "PRIMARY", "c2"); assertIndexColumns(userTable, "PRIMARY", "c1"); assertIndexColumns(userTable, "c2", "c2", "c1"); } @Test public void fkWithTwoColumnKeyNamed() { UserTable userTable = createTableWithFK(null, null, "key `index_twocol` (c2, c1)"); assertIndexes(userTable, "PRIMARY", "index_twocol"); assertIndexColumns(userTable, "PRIMARY", "c1"); assertIndexColumns(userTable, "index_twocol", "c2", "c1"); } @Test public void fkUsingExplicitKey() { UserTable userTable = createTableWithFK("my_constraint", "my_key", "key my_constraint(c2)"); assertIndexes(userTable, "PRIMARY", "my_constraint"); assertIndexColumns(userTable, "PRIMARY", "c1"); assertIndexColumns(userTable, "my_constraint", "c2"); } @Test(expected=ParseException.class) public void fkUsingExplicitKeyConflicting() throws InvalidOperationException { try { createTableWithFK("my_constraint", "my_key", "key my_constraint(c1)"); } catch (TestException e) { throw e.getCause(); } fail("should have failed at the above line!"); } protected static void debug(String formatter, Object... args) { if(Boolean.getBoolean("IndexNamesIT.debug")) { String[] lines = String.format(formatter, args).split("\n"); for (String line : lines) { System.out.print("\tIndexNamesIT: "); System.out.println(line); } } } protected UserTable createTableWithIndexes(String indexDDL) { String ddl = BASE_DDL + indexDDL; ddl = ddl.replaceAll(", *", ",\n\t"); ddl += "\n);"; debug(ddl); try { ddl().createTable(session, "s1", ddl); } catch (InvalidOperationException e) { throw new TestException("creating DDL: " + ddl, e); } return ddl().getAIS(session).getUserTable("s1", "t1"); } protected UserTable createTableWithFK(String constraintName, String indexName, String additionalIndexes) { try { ddl().createTable(session, "s1", "CREATE TABLE p1(parentc1 int key)"); } catch (InvalidOperationException e) { throw new TestException("CREATE TABLE p1(parentc1 int key)", e); } StringBuilder builder = new StringBuilder("PRIMARY KEY (c1), "); if (additionalIndexes != null) { builder.append(additionalIndexes).append(", "); } builder.append("CONSTRAINT "); if (constraintName != null) { builder.append(constraintName).append(' '); } builder.append("FOREIGN KEY "); if (indexName != null) { builder.append(indexName).append(' '); } builder.append("(c2) REFERENCES p1(parentc1)"); return createTableWithIndexes(builder.toString()); } protected static void assertIndexes(UserTable table, String... expectedIndexNames) { Set<String> expectedIndexesSet = new TreeSet<String>(Arrays.asList(expectedIndexNames)); debug("for table %s, expecting indexes %s", table, expectedIndexesSet); Set<String> actualIndexes = new TreeSet<String>(); for (Index index : table.getIndexes()) { String indexName = index.getIndexName().getName(); boolean added = actualIndexes.add(indexName); assertTrue("duplicate index name: " + indexName, added); } assertEquals("indexes in " + table.getName(), expectedIndexesSet, actualIndexes); } protected static void assertIndexColumns(UserTable table, String indexName, String... expectedColumns) { List<String> expectedColumnsList = Arrays.asList(expectedColumns); debug("for index %s.%s, expecting columns %s", table, indexName, expectedColumnsList); Index index = table.getIndex(indexName); assertNotNull(indexName + " was null", index); List<String> actualColumns = new ArrayList<String>(); for (IndexColumn indexColumn : index.getColumns()) { actualColumns.add(indexColumn.getColumn().getName()); } assertEquals(indexName + " columns", actualColumns, expectedColumnsList); } private static class TestException extends RuntimeException { private final InvalidOperationException cause; private TestException(String message, InvalidOperationException cause) { super(message, cause); this.cause = cause; } @Override public InvalidOperationException getCause() { assert super.getCause() == cause; return cause; } } }
src/test/java/com/akiban/cserver/itests/bugs/bug695495/IndexNamesIT.java
package com.akiban.cserver.itests.bugs.bug695495; import com.akiban.ais.model.Index; import com.akiban.ais.model.IndexColumn; import com.akiban.ais.model.UserTable; import com.akiban.cserver.InvalidOperationException; import com.akiban.cserver.api.ddl.ParseException; import com.akiban.cserver.itests.ApiTestBase; import org.junit.Test; import java.util.*; import static junit.framework.Assert.*; public final class IndexNamesIT extends ApiTestBase { private static final String BASE_DDL = "CREATE TABLE t1( c1 tinyint(4) not null, c2 int(11) DEFAULT NULL, "; @Test public void oneCustomNamedIndex() { UserTable userTable = createTableWithIndexes("PRIMARY KEY (c1), KEY myNamedKey(c2)"); assertIndexes(userTable, "PRIMARY", "myNamedKey"); assertIndexColumns(userTable, "PRIMARY", "c1"); assertIndexColumns(userTable, "myNamedKey", "c2"); } @Test public void oneStandardNamedIndex() { UserTable userTable = createTableWithIndexes("PRIMARY KEY (`c1`), KEY `c2` (`c2`)"); assertIndexes(userTable, "PRIMARY", "c2"); assertIndexColumns(userTable, "PRIMARY", "c1"); assertIndexColumns(userTable, "c2", "c2"); } @Test public void oneUnnamedIndex() { UserTable userTable = createTableWithIndexes("PRIMARY KEY (c1), KEY (c2)"); assertIndexes(userTable, "PRIMARY", "c2"); assertIndexColumns(userTable, "PRIMARY", "c1"); assertIndexColumns(userTable, "c2", "c2"); } @Test public void twoIndexesNoConflict() { UserTable userTable = createTableWithIndexes("PRIMARY KEY (c1), KEY (c2), KEY multiColumnIndex(c2, c1)"); assertIndexes(userTable, "PRIMARY", "c2", "multiColumnIndex"); assertIndexColumns(userTable, "PRIMARY", "c1"); assertIndexColumns(userTable, "c2", "c2"); assertIndexColumns(userTable, "multiColumnIndex", "c2", "c1"); } @Test public void twoUnnamedIndexes() { UserTable userTable = createTableWithIndexes("PRIMARY KEY (c1), KEY (c2), KEY (c2, c1)"); assertIndexes(userTable, "PRIMARY", "c2", "c2_2"); assertIndexColumns(userTable, "PRIMARY", "c1"); assertIndexColumns(userTable, "c2", "c2"); assertIndexColumns(userTable, "c2_2", "c2", "c1"); } @Test public void fkFullyNamed() { UserTable userTable = createTableWithFK("fk_constraint_1", "fk_index_1", null); assertIndexes(userTable, "PRIMARY", "fk_constraint_1"); assertIndexColumns(userTable, "PRIMARY", "c1"); assertIndexColumns(userTable, "fk_constraint_1", "c2"); } @Test public void fkOnlyConstraintNamed() { UserTable userTable = createTableWithFK("fk_constraint_1", null, null); assertIndexes(userTable, "PRIMARY", "fk_constraint_1"); assertIndexColumns(userTable, "PRIMARY", "c1"); assertIndexColumns(userTable, "fk_constraint_1", "c2"); } @Test public void fkOnlyIndexNamed() { UserTable userTable = createTableWithFK(null, "fk_index_1", null); assertIndexes(userTable, "PRIMARY", "fk_index_1"); assertIndexColumns(userTable, "PRIMARY", "c1"); assertIndexColumns(userTable, "fk_index_1", "c2"); } @Test public void fkNeitherNamed() { UserTable userTable = createTableWithFK(null, null, null); assertIndexes(userTable, "PRIMARY", "c2"); assertIndexColumns(userTable, "PRIMARY", "c1"); assertIndexColumns(userTable, "c2", "c2"); } @Test public void fkWithSingleColumnKeyUnnamed() { UserTable userTable = createTableWithFK(null, null, "key (c2)"); assertIndexes(userTable, "PRIMARY", "c2"); assertIndexColumns(userTable, "PRIMARY", "c1"); assertIndexColumns(userTable, "c2", "c2"); } @Test public void fkWithSingleColumnKeyNamed() { UserTable userTable = createTableWithFK(null, null, "key `index_2` (c2)"); assertIndexes(userTable, "PRIMARY", "index_2"); assertIndexColumns(userTable, "PRIMARY", "c1"); assertIndexColumns(userTable, "index_2", "c2"); } @Test public void fkWithTwoColumnKeyUnnamed() { UserTable userTable = createTableWithFK(null, null, "key (c2, c1)"); assertIndexes(userTable, "PRIMARY", "c2"); assertIndexColumns(userTable, "PRIMARY", "c1"); assertIndexColumns(userTable, "c2", "c2", "c1"); } @Test public void fkWithTwoColumnKeyNamed() { UserTable userTable = createTableWithFK(null, null, "key `index_twocol` (c2, c1)"); assertIndexes(userTable, "PRIMARY", "index_twocol"); assertIndexColumns(userTable, "PRIMARY", "c1"); assertIndexColumns(userTable, "index_twocol", "c2", "c1"); } @Test public void fkUsingExplicitKey() { UserTable userTable = createTableWithFK("my_constraint", "my_key", "key my_constraint(c2)"); assertIndexes(userTable, "PRIMARY", "my_constraint"); assertIndexColumns(userTable, "PRIMARY", "c1"); assertIndexColumns(userTable, "my_constraint", "c2"); } @Test(expected=ParseException.class) public void fkUsingExplicitKeyConflicting() throws InvalidOperationException { try { createTableWithFK("my_constraint", "my_key", "key my_constraint(c1)"); } catch (TestException e) { throw e.getCause(); } fail("should have failed at the above line!"); } protected static void debug(String formatter, Object... args) { if(Boolean.getBoolean("IndexNamesIT.debug")) { System.out.print("\tIndexNamesIT: "); System.out.println(String.format(formatter, args)); } } protected UserTable createTableWithIndexes(String indexDDL) { final String ddl = BASE_DDL + indexDDL + ");"; debug(ddl); try { ddl().createTable(session, "s1", ddl); } catch (InvalidOperationException e) { throw new TestException("creating DDL: " + ddl, e); } return ddl().getAIS(session).getUserTable("s1", "t1"); } protected UserTable createTableWithFK(String constraintName, String indexName, String additionalIndexes) { try { ddl().createTable(session, "s1", "CREATE TABLE p1(parentc1 int key)"); } catch (InvalidOperationException e) { throw new TestException("CREATE TABLE p1(parentc1 int key)", e); } StringBuilder builder = new StringBuilder("PRIMARY KEY (c1), "); if (additionalIndexes != null) { builder.append(additionalIndexes).append(", "); } builder.append("CONSTRAINT "); if (constraintName != null) { builder.append(constraintName).append(' '); } builder.append("FOREIGN KEY "); if (indexName != null) { builder.append(indexName).append(' '); } builder.append("(c2) REFERENCES p1(parentc1)"); return createTableWithIndexes(builder.toString()); } protected static void assertIndexes(UserTable table, String... expectedIndexNames) { Set<String> expectedIndexesSet = new TreeSet<String>(Arrays.asList(expectedIndexNames)); debug("for table %s, expecting indexes %s", table, expectedIndexesSet); Set<String> actualIndexes = new TreeSet<String>(); for (Index index : table.getIndexes()) { String indexName = index.getIndexName().getName(); boolean added = actualIndexes.add(indexName); assertTrue("duplicate index name: " + indexName, added); } assertEquals("indexes in " + table.getName(), expectedIndexesSet, actualIndexes); } protected static void assertIndexColumns(UserTable table, String indexName, String... expectedColumns) { List<String> expectedColumnsList = Arrays.asList(expectedColumns); debug("for index %s.%s, expecting columns %s", table, indexName, expectedColumnsList); Index index = table.getIndex(indexName); assertNotNull(indexName + " was null", index); List<String> actualColumns = new ArrayList<String>(); for (IndexColumn indexColumn : index.getColumns()) { actualColumns.add(indexColumn.getColumn().getName()); } assertEquals(indexName + " columns", actualColumns, expectedColumnsList); } private static class TestException extends RuntimeException { private final InvalidOperationException cause; private TestException(String message, InvalidOperationException cause) { super(message, cause); this.cause = cause; } @Override public InvalidOperationException getCause() { assert super.getCause() == cause; return cause; } } }
Pretty debug output.
src/test/java/com/akiban/cserver/itests/bugs/bug695495/IndexNamesIT.java
Pretty debug output.
Java
lgpl-2.1
5617713c48f5b86fd8b361060bbe257cd8ea651b
0
gallardo/opencms-core,gallardo/opencms-core,ggiudetti/opencms-core,gallardo/opencms-core,ggiudetti/opencms-core,ggiudetti/opencms-core,alkacon/opencms-core,ggiudetti/opencms-core,alkacon/opencms-core,alkacon/opencms-core,gallardo/opencms-core,alkacon/opencms-core
/* * This library is part of OpenCms - * the Open Source Content Management System * * Copyright (C) Alkacon Software (http://www.alkacon.com) * * 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. * * For further information about Alkacon Software, please see the * company website: http://www.alkacon.com * * For further information about OpenCms, please see the * project website: http://www.opencms.org * * 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 */ package org.opencms.acacia.client.entity; import org.opencms.acacia.shared.CmsEntity; import org.opencms.acacia.shared.CmsEntityAttribute; import org.opencms.acacia.shared.CmsType; import org.opencms.gwt.client.util.CmsDomUtil; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.google.gwt.core.client.JavaScriptObject; import com.google.gwt.dom.client.Document; import com.google.gwt.dom.client.Element; import com.google.gwt.dom.client.NodeList; /** * The editor data back-end.<p> */ public final class CmsEntityBackend implements I_CmsEntityBackend { /** The instance. */ private static CmsEntityBackend INSTANCE; /** CmsEntity id counter. */ private int m_count; /** The registered entities. */ private Map<String, CmsEntity> m_entities; /** The registered types. */ private Map<String, CmsType> m_types; /** * Constructor.<p> */ public CmsEntityBackend() { m_entities = new HashMap<String, CmsEntity>(); m_types = new HashMap<String, CmsType>(); } /** * Method to create an entity object from a wrapped instance.<p> * * @param entityWrapper the wrappe entity * * @return the entity */ public static CmsEntity createFromNativeWrapper(JavaScriptObject entityWrapper) { CmsEntity result = new CmsEntity(null, getEntityType(entityWrapper)); String[] simpleAttr = getSimpleAttributeNames(entityWrapper); for (int i = 0; i < simpleAttr.length; i++) { String[] simpleAttrValues = getSimpleAttributeValues(entityWrapper, simpleAttr[i]); for (int j = 0; j < simpleAttrValues.length; j++) { result.addAttributeValue(simpleAttr[i], simpleAttrValues[j]); } } String[] complexAttr = getComplexAttributeNames(entityWrapper); for (int i = 0; i < complexAttr.length; i++) { JavaScriptObject[] complexAttrValues = getComplexAttributeValues(entityWrapper, complexAttr[i]); for (int j = 0; j < complexAttrValues.length; j++) { result.addAttributeValue(complexAttr[i], createFromNativeWrapper(complexAttrValues[j])); } } return result; } /** * Returns the instance.<p> * * @return the instance */ public static CmsEntityBackend getInstance() { if (INSTANCE == null) { INSTANCE = new CmsEntityBackend(); } return INSTANCE; } /** * Returns the complex attribute names of the given entity.<p> * * @param entityWrapper the wrapped entity * * @return the complex attribute names */ private static native String[] getComplexAttributeNames(JavaScriptObject entityWrapper)/*-{ var attr = entityWrapper.getAttributes(); var result = []; for (i = 0; i < attr.length; i++) { if (!attr[i].isSimpleValue()) { result.push(attr[i].getAttributeName()); } } return result; }-*/; /** * Returns the complex attribute values of the given entity.<p> * * @param entityWrapper the wrapped entity * @param attributeName the attribute name * * @return the complex attribute values */ private static native JavaScriptObject[] getComplexAttributeValues( JavaScriptObject entityWrapper, String attributeName)/*-{ return entityWrapper.getAttribute(attributeName).getComplexValues(); }-*/; /** * Returns the entity type.<p> * * @param entityWrapper the wrapped entity * * @return the entity type name */ private static native String getEntityType(JavaScriptObject entityWrapper)/*-{ return entityWrapper.getTypeName(); }-*/; /** * Returns the simple attribute names of the given entity.<p> * * @param entityWrapper the wrapped entity * * @return the simple attribute names */ private static native String[] getSimpleAttributeNames(JavaScriptObject entityWrapper)/*-{ var attr = entityWrapper.getAttributes(); var result = []; for (i = 0; i < attr.length; i++) { if (attr[i].isSimpleValue()) { result.push(attr[i].getAttributeName()); } } return result; }-*/; /** * Returns the simple attribute values of the given entity.<p> * * @param entityWrapper the wrapped entity * @param attributeName the attribute name * * @return the simple attribute values */ private static native String[] getSimpleAttributeValues(JavaScriptObject entityWrapper, String attributeName)/*-{ return entityWrapper.getAttribute(attributeName).getSimpleValues(); }-*/; /** * @see org.opencms.acacia.client.entity.I_CmsEntityBackend#changeEntityContentValues(org.opencms.acacia.shared.CmsEntity, org.opencms.acacia.shared.CmsEntity) */ public void changeEntityContentValues(CmsEntity original, CmsEntity newContent) { clearEntityAttributes(original); for (CmsEntityAttribute attribute : newContent.getAttributes()) { if (attribute.isSimpleValue()) { for (String value : attribute.getSimpleValues()) { original.addAttributeValue(attribute.getAttributeName(), value); } } else { for (CmsEntity value : attribute.getComplexValues()) { original.addAttributeValue(attribute.getAttributeName(), registerEntity(value)); } } } } /** * @see org.opencms.acacia.client.entity.I_CmsEntityBackend#clearEntities() */ public void clearEntities() { m_entities.clear(); } /** * @see org.opencms.acacia.client.entity.I_CmsEntityBackend#createEntity(java.lang.String, java.lang.String) */ public CmsEntity createEntity(String entityId, String entityType) { if (entityId == null) { entityId = generateId(); } if (!m_types.containsKey(entityType)) { throw new IllegalArgumentException("Type " + entityType + " is not registered yet"); } if (m_entities.containsKey(entityId)) { throw new IllegalArgumentException("CmsEntity " + entityId + " is already registered"); } CmsEntity entity = new CmsEntity(entityId, entityType); m_entities.put(entityId, entity); return entity; } /** * @see org.opencms.acacia.client.entity.I_CmsEntityBackend#createType(java.lang.String) */ public CmsType createType(String id) { if (m_types.containsKey(id)) { throw new IllegalArgumentException("Type " + id + " is already registered"); } CmsType type = new CmsType(id); m_types.put(id, type); return type; } /** * @see org.opencms.acacia.client.entity.I_CmsEntityBackend#getAttributeElements(org.opencms.acacia.shared.CmsEntity, java.lang.String, com.google.gwt.dom.client.Element) */ public List<Element> getAttributeElements(CmsEntity entity, String attributeName, Element context) { return getAttributeElements(entity.getId(), attributeName, context); } /** * @see org.opencms.acacia.client.entity.I_CmsEntityBackend#getAttributeElements(java.lang.String, java.lang.String, com.google.gwt.dom.client.Element) */ public List<Element> getAttributeElements(String entityId, String attributeName, Element context) { StringBuffer select = new StringBuffer(); select.append("[about='").append(entityId).append("'][property$='").append(attributeName).append("'], "); select.append("[about='").append(entityId).append("'] [property$='").append(attributeName).append("'], "); select.append("[about='").append(entityId).append("'][property*='").append(attributeName).append("['], "); select.append("[about='").append(entityId).append("'] [property*='").append(attributeName).append("[']"); if (context == null) { context = Document.get().getDocumentElement(); } return select(select.toString(), context); } /** * @see org.opencms.acacia.client.entity.I_CmsEntityBackend#getEntity(java.lang.String) */ public CmsEntity getEntity(String entityId) { return m_entities.get(entityId); } /** * @see org.opencms.acacia.client.entity.I_CmsEntityBackend#getType(java.lang.String) */ public CmsType getType(String id) { return m_types.get(id); } /** * @see org.opencms.acacia.client.entity.I_CmsEntityBackend#registerEntity(org.opencms.acacia.shared.CmsEntity) */ public CmsEntity registerEntity(CmsEntity entity) { if (m_entities.containsKey(entity.getId())) { throw new IllegalArgumentException("CmsEntity " + entity.getId() + " is already registered"); } if (!m_types.containsKey(entity.getTypeName())) { throw new IllegalArgumentException("Type " + entity.getTypeName() + " is not registered yet"); } for (CmsEntityAttribute attr : entity.getAttributes()) { if (attr.isComplexValue()) { for (CmsEntity child : attr.getComplexValues()) { registerEntity(child); } } } entity.ensureChangeHandlers(); m_entities.put(entity.getId(), entity); return entity; } /** * @see org.opencms.acacia.client.entity.I_CmsEntityBackend#registerEntity(org.opencms.acacia.shared.CmsEntity, boolean) */ public CmsEntity registerEntity(CmsEntity entity, boolean discardIds) { if (!discardIds) { return registerEntity(entity); } else { if (!m_types.containsKey(entity.getTypeName())) { throw new IllegalArgumentException("Type " + entity.getTypeName() + " is not registered yet"); } CmsEntity result = createEntity(null, entity.getTypeName()); for (CmsEntityAttribute attr : entity.getAttributes()) { if (attr.isComplexValue()) { for (CmsEntity child : attr.getComplexValues()) { result.addAttributeValue(attr.getAttributeName(), registerEntity(child, discardIds)); } } else { for (String value : attr.getSimpleValues()) { result.addAttributeValue(attr.getAttributeName(), value); } } } result.ensureChangeHandlers(); m_entities.put(result.getId(), result); return result; } } /** * @see org.opencms.acacia.client.entity.I_CmsEntityBackend#registerTypes(org.opencms.acacia.shared.CmsType, java.util.Map) */ public void registerTypes(CmsType type, Map<String, CmsType> types) { if (!m_types.containsKey(type.getId())) { for (String attrName : type.getAttributeNames()) { String subTypeId = type.getAttributeTypeName(attrName); CmsType subType = types.get(subTypeId); if (subType == null) { throw new IllegalArgumentException("Type information for " + subTypeId + " is missing"); } registerTypes(subType, types); } m_types.put(type.getId(), type); } } /** * @see org.opencms.acacia.client.entity.I_CmsEntityBackend#removeEntity(java.lang.String) */ public void removeEntity(String entityId) { if (m_entities.containsKey(entityId)) { CmsEntity entity = m_entities.get(entityId); for (CmsEntityAttribute attr : entity.getAttributes()) { if (attr.isComplexValue()) { for (CmsEntity child : attr.getComplexValues()) { removeEntity(child.getId()); } } } m_entities.remove(entityId); } } /** * Returns a list of DOM elements matching the given selector.<p> * * @param selector the CSS selector * @param context the context element * * @return the matching elements */ protected List<Element> select(String selector, Element context) { NodeList<Element> elements = CmsDomUtil.querySelectorAll(selector, context); List<Element> result = new ArrayList<Element>(); for (int i = 0; i < elements.getLength(); i++) { result.add(elements.getItem(i)); } return result; } /** * Removes all attributes from the given entity.<p> * * @param entity the entity */ private void clearEntityAttributes(CmsEntity entity) { for (CmsEntityAttribute attribute : entity.getAttributes()) { if (attribute.isComplexValue()) { for (CmsEntity child : attribute.getComplexValues()) { clearEntityAttributes(child); removeEntity(child.getId()); } } entity.removeAttributeSilent(attribute.getAttributeName()); } } /** * Generates a new entity id.<p> * * @return the generated id */ private String generateId() { m_count++; String id = "generic_id" + m_count; while (m_entities.containsKey(id)) { m_count++; id = "generic_id" + m_count; } return id; } }
src-gwt/org/opencms/acacia/client/entity/CmsEntityBackend.java
/* * This library is part of OpenCms - * the Open Source Content Management System * * Copyright (C) Alkacon Software (http://www.alkacon.com) * * 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. * * For further information about Alkacon Software, please see the * company website: http://www.alkacon.com * * For further information about OpenCms, please see the * project website: http://www.opencms.org * * 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 */ package org.opencms.acacia.client.entity; import org.opencms.acacia.shared.CmsEntity; import org.opencms.acacia.shared.CmsEntityAttribute; import org.opencms.acacia.shared.CmsType; import org.opencms.gwt.client.util.CmsDomUtil; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.google.gwt.core.client.JavaScriptObject; import com.google.gwt.dom.client.Document; import com.google.gwt.dom.client.Element; import com.google.gwt.dom.client.NodeList; /** * The editor data back-end.<p> */ public final class CmsEntityBackend implements I_CmsEntityBackend { /** The instance. */ private static CmsEntityBackend INSTANCE; /** CmsEntity id counter. */ private int m_count; /** The registered entities. */ private Map<String, CmsEntity> m_entities; /** The registered types. */ private Map<String, CmsType> m_types; /** * Constructor.<p> */ public CmsEntityBackend() { m_entities = new HashMap<String, CmsEntity>(); m_types = new HashMap<String, CmsType>(); } /** * Method to create an entity object from a wrapped instance.<p> * * @param entityWrapper the wrappe entity * * @return the entity */ public static CmsEntity createFromNativeWrapper(JavaScriptObject entityWrapper) { CmsEntity result = new CmsEntity(null, getEntityType(entityWrapper)); String[] simpleAttr = getSimpleAttributeNames(entityWrapper); for (int i = 0; i < simpleAttr.length; i++) { String[] simpleAttrValues = getSimpleAttributeValues(entityWrapper, simpleAttr[i]); for (int j = 0; j < simpleAttrValues.length; j++) { result.addAttributeValue(simpleAttr[i], simpleAttrValues[j]); } } String[] complexAttr = getComplexAttributeNames(entityWrapper); for (int i = 0; i < complexAttr.length; i++) { JavaScriptObject[] complexAttrValues = getComplexAttributeValues(entityWrapper, complexAttr[i]); for (int j = 0; j < complexAttrValues.length; j++) { result.addAttributeValue(complexAttr[i], createFromNativeWrapper(complexAttrValues[j])); } } return result; } /** * Returns the instance.<p> * * @return the instance */ public static CmsEntityBackend getInstance() { if (INSTANCE == null) { INSTANCE = new CmsEntityBackend(); } return INSTANCE; } /** * Returns the complex attribute names of the given entity.<p> * * @param entityWrapper the wrapped entity * * @return the complex attribute names */ private static native String[] getComplexAttributeNames(JavaScriptObject entityWrapper)/*-{ var attr = entityWrapper.getAttributes(); var result = []; for (i = 0; i < attr.length; i++) { if (!attr[i].isSimpleValue()) { result.push(attr[i].getAttributeName()); } } return result; }-*/; /** * Returns the complex attribute values of the given entity.<p> * * @param entityWrapper the wrapped entity * @param attributeName the attribute name * * @return the complex attribute values */ private static native JavaScriptObject[] getComplexAttributeValues( JavaScriptObject entityWrapper, String attributeName)/*-{ return entityWrapper.getAttribute(attributeName).getComplexValues(); }-*/; /** * Returns the entity type.<p> * * @param entityWrapper the wrapped entity * * @return the entity type name */ private static native String getEntityType(JavaScriptObject entityWrapper)/*-{ return entityWrapper.getTypeName(); }-*/; /** * Returns the simple attribute names of the given entity.<p> * * @param entityWrapper the wrapped entity * * @return the simple attribute names */ private static native String[] getSimpleAttributeNames(JavaScriptObject entityWrapper)/*-{ var attr = entityWrapper.getAttributes(); var result = []; for (i = 0; i < attr.length; i++) { if (attr[i].isSimpleValue()) { result.push(attr[i].getAttributeName()); } } return result; }-*/; /** * Returns the simple attribute values of the given entity.<p> * * @param entityWrapper the wrapped entity * @param attributeName the attribute name * * @return the simple attribute values */ private static native String[] getSimpleAttributeValues(JavaScriptObject entityWrapper, String attributeName)/*-{ return entityWrapper.getAttribute(attributeName).getSimpleValues(); }-*/; /** * @see org.opencms.acacia.client.entity.I_CmsEntityBackend#changeEntityContentValues(org.opencms.acacia.shared.CmsEntity, org.opencms.acacia.shared.CmsEntity) */ public void changeEntityContentValues(CmsEntity original, CmsEntity newContent) { clearEntityAttributes(original); for (CmsEntityAttribute attribute : newContent.getAttributes()) { if (attribute.isSimpleValue()) { for (String value : attribute.getSimpleValues()) { original.addAttributeValue(attribute.getAttributeName(), value); } } else { for (CmsEntity value : attribute.getComplexValues()) { original.addAttributeValue(attribute.getAttributeName(), registerEntity(value)); } } } } /** * @see org.opencms.acacia.client.entity.I_CmsEntityBackend#clearEntities() */ public void clearEntities() { m_entities.clear(); } /** * @see org.opencms.acacia.client.entity.I_CmsEntityBackend#createEntity(java.lang.String, java.lang.String) */ public CmsEntity createEntity(String entityId, String entityType) { if (entityId == null) { entityId = generateId(); } if (!m_types.containsKey(entityType)) { throw new IllegalArgumentException("Type " + entityType + " is not registered yet"); } if (m_entities.containsKey(entityId)) { throw new IllegalArgumentException("CmsEntity " + entityId + " is already registered"); } CmsEntity entity = new CmsEntity(entityId, entityType); m_entities.put(entityId, entity); return entity; } /** * @see org.opencms.acacia.client.entity.I_CmsEntityBackend#createType(java.lang.String) */ public CmsType createType(String id) { if (m_types.containsKey(id)) { throw new IllegalArgumentException("Type " + id + " is already registered"); } CmsType type = new CmsType(id); m_types.put(id, type); return type; } /** * @see org.opencms.acacia.client.entity.I_CmsEntityBackend#getAttributeElements(org.opencms.acacia.shared.CmsEntity, java.lang.String, com.google.gwt.dom.client.Element) */ public List<Element> getAttributeElements(CmsEntity entity, String attributeName, Element context) { return getAttributeElements(entity.getId(), attributeName, context); } /** * @see org.opencms.acacia.client.entity.I_CmsEntityBackend#getAttributeElements(java.lang.String, java.lang.String, com.google.gwt.dom.client.Element) */ public List<Element> getAttributeElements(String entityId, String attributeName, Element context) { String selector = "[about='" + entityId + "'][property*='" + attributeName + "'], [about='" + entityId + "'] [property*='" + attributeName + "']"; if (context == null) { context = Document.get().getDocumentElement(); } return select(selector, context); } /** * @see org.opencms.acacia.client.entity.I_CmsEntityBackend#getEntity(java.lang.String) */ public CmsEntity getEntity(String entityId) { return m_entities.get(entityId); } /** * @see org.opencms.acacia.client.entity.I_CmsEntityBackend#getType(java.lang.String) */ public CmsType getType(String id) { return m_types.get(id); } /** * @see org.opencms.acacia.client.entity.I_CmsEntityBackend#registerEntity(org.opencms.acacia.shared.CmsEntity) */ public CmsEntity registerEntity(CmsEntity entity) { if (m_entities.containsKey(entity.getId())) { throw new IllegalArgumentException("CmsEntity " + entity.getId() + " is already registered"); } if (!m_types.containsKey(entity.getTypeName())) { throw new IllegalArgumentException("Type " + entity.getTypeName() + " is not registered yet"); } for (CmsEntityAttribute attr : entity.getAttributes()) { if (attr.isComplexValue()) { for (CmsEntity child : attr.getComplexValues()) { registerEntity(child); } } } entity.ensureChangeHandlers(); m_entities.put(entity.getId(), entity); return entity; } /** * @see org.opencms.acacia.client.entity.I_CmsEntityBackend#registerEntity(org.opencms.acacia.shared.CmsEntity, boolean) */ public CmsEntity registerEntity(CmsEntity entity, boolean discardIds) { if (!discardIds) { return registerEntity(entity); } else { if (!m_types.containsKey(entity.getTypeName())) { throw new IllegalArgumentException("Type " + entity.getTypeName() + " is not registered yet"); } CmsEntity result = createEntity(null, entity.getTypeName()); for (CmsEntityAttribute attr : entity.getAttributes()) { if (attr.isComplexValue()) { for (CmsEntity child : attr.getComplexValues()) { result.addAttributeValue(attr.getAttributeName(), registerEntity(child, discardIds)); } } else { for (String value : attr.getSimpleValues()) { result.addAttributeValue(attr.getAttributeName(), value); } } } result.ensureChangeHandlers(); m_entities.put(result.getId(), result); return result; } } /** * @see org.opencms.acacia.client.entity.I_CmsEntityBackend#registerTypes(org.opencms.acacia.shared.CmsType, java.util.Map) */ public void registerTypes(CmsType type, Map<String, CmsType> types) { if (!m_types.containsKey(type.getId())) { for (String attrName : type.getAttributeNames()) { String subTypeId = type.getAttributeTypeName(attrName); CmsType subType = types.get(subTypeId); if (subType == null) { throw new IllegalArgumentException("Type information for " + subTypeId + " is missing"); } registerTypes(subType, types); } m_types.put(type.getId(), type); } } /** * @see org.opencms.acacia.client.entity.I_CmsEntityBackend#removeEntity(java.lang.String) */ public void removeEntity(String entityId) { if (m_entities.containsKey(entityId)) { CmsEntity entity = m_entities.get(entityId); for (CmsEntityAttribute attr : entity.getAttributes()) { if (attr.isComplexValue()) { for (CmsEntity child : attr.getComplexValues()) { removeEntity(child.getId()); } } } m_entities.remove(entityId); } } /** * Returns a list of DOM elements matching the given selector.<p> * * @param selector the CSS selector * @param context the context element * * @return the matching elements */ protected List<Element> select(String selector, Element context) { NodeList<Element> elements = CmsDomUtil.querySelectorAll(selector, context); List<Element> result = new ArrayList<Element>(); for (int i = 0; i < elements.getLength(); i++) { result.add(elements.getItem(i)); } return result; } /** * Removes all attributes from the given entity.<p> * * @param entity the entity */ private void clearEntityAttributes(CmsEntity entity) { for (CmsEntityAttribute attribute : entity.getAttributes()) { if (attribute.isComplexValue()) { for (CmsEntity child : attribute.getComplexValues()) { clearEntityAttributes(child); removeEntity(child.getId()); } } entity.removeAttributeSilent(attribute.getAttributeName()); } } /** * Generates a new entity id.<p> * * @return the generated id */ private String generateId() { m_count++; String id = "generic_id" + m_count; while (m_entities.containsKey(id)) { m_count++; id = "generic_id" + m_count; } return id; } }
Improved attribute element selection.
src-gwt/org/opencms/acacia/client/entity/CmsEntityBackend.java
Improved attribute element selection.
Java
lgpl-2.1
126fe5666ee8dd4569f71a81ece803fbe9bce3d8
0
Fussel/distributed
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package distributed.dto; import com.j256.ormlite.field.DatabaseField; import com.j256.ormlite.table.DatabaseTable; import java.io.Serializable; import java.util.Objects; /** * * @author steffen */ @DatabaseTable(tableName = "private_message") public class PrivateMessage extends IMessage implements Serializable { public static final String TABLE_NAME = "private_message"; public static final String COL_NAME_RECIVER = "recivier"; @DatabaseField(columnName = COL_NAME_RECIVER) private String receiver; public PrivateMessage() { //Needed by ORMLite } public PrivateMessage(String receiver, byte[] message) { super("", message); this.receiver = receiver; //TODO Set sender Prop } public String getReceiver() { return receiver; } public void setReceiver(String receiver) { this.receiver = receiver; } @Override public int hashCode() { int hash = 7; return hash; } @Override public boolean equals(Object obj) { if(!super.equals(obj)) return false; if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final PrivateMessage other = (PrivateMessage) obj; if (!Objects.equals(this.receiver, other.receiver)) { return false; } return true; } }
Distributed/src/distributed/dto/PrivateMessage.java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package distributed.dto; import com.j256.ormlite.field.DatabaseField; import com.j256.ormlite.table.DatabaseTable; import java.io.Serializable; /** * * @author steffen */ @DatabaseTable(tableName = "private_message") public class PrivateMessage extends IMessage implements Serializable { public static final String TABLE_NAME = "private_message"; public static final String COL_NAME_RECIVER = "recivier"; @DatabaseField(columnName = COL_NAME_RECIVER) private String receiver; public PrivateMessage() { //Needed by ORMLite } public PrivateMessage(String receiver, byte[] message) { super("", message); this.receiver = receiver; //TODO Set sender Prop } public String getReceiver() { return receiver; } public void setReceiver(String receiver) { this.receiver = receiver; } }
PrivateMessage equals and hash added
Distributed/src/distributed/dto/PrivateMessage.java
PrivateMessage equals and hash added
Java
apache-2.0
b7d5d4d3dd046ab8e68634c39420182223deff35
0
getlantern/lantern-java,lqch14102/lantern,lqch14102/lantern,getlantern/lantern-java,getlantern/lantern-java,lqch14102/lantern,lqch14102/lantern,lqch14102/lantern,lqch14102/lantern,lqch14102/lantern,getlantern/lantern-java,getlantern/lantern-java,getlantern/lantern-java,getlantern/lantern-java,getlantern/lantern-java,getlantern/lantern-java,lqch14102/lantern,lqch14102/lantern
package org.lantern; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import java.util.Map; import org.apache.commons.lang.SystemUtils; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Menu; import org.eclipse.swt.widgets.MenuItem; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Tray; import org.eclipse.swt.widgets.TrayItem; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.eventbus.Subscribe; /** * Class for handling all system tray interactions. */ public class SystemTrayImpl implements SystemTray { private final Logger log = LoggerFactory.getLogger(getClass()); private Display display; private Shell shell; private TrayItem trayItem; private MenuItem updateItem; private Menu menu; private Map<String, String> updateData; /** * Creates a new system tray handler class. * * @param display The SWT display. */ public SystemTrayImpl() { LanternHub.register(this); } @Override public void createTray() { this.display = LanternHub.display(); this.shell = new Shell(display); display.asyncExec (new Runnable () { @Override public void run () { createTrayInternal(); } }); } private void createTrayInternal() { final Tray tray = display.getSystemTray (); if (tray == null) { System.out.println ("The system tray is not available"); } else { this.trayItem = new TrayItem (tray, SWT.NONE); this.trayItem.setToolTipText( I18n.tr("Lantern ")+LanternConstants.VERSION); this.trayItem.addListener (SWT.Show, new Listener () { @Override public void handleEvent (final Event event) { System.out.println("show"); } }); this.trayItem.addListener (SWT.Hide, new Listener () { @Override public void handleEvent (final Event event) { System.out.println("hide"); } }); this.menu = new Menu (shell, SWT.POP_UP); final MenuItem dashboardItem = new MenuItem(menu, SWT.PUSH); dashboardItem.setText("Open Dashboard"); // XXX i18n dashboardItem.addListener (SWT.Selection, new Listener () { @Override public void handleEvent (final Event event) { LanternHub.jettyLauncher().openBrowserWhenReady(); } }); new MenuItem(menu, SWT.SEPARATOR); final MenuItem quitItem = new MenuItem(menu, SWT.PUSH); quitItem.setText("Quit Lantern"); // XXX i18n quitItem.addListener (SWT.Selection, new Listener () { @Override public void handleEvent (final Event event) { System.out.println("Got exit call"); display.dispose(); System.exit(0); } }); trayItem.addListener (SWT.MenuDetect, new Listener () { @Override public void handleEvent (final Event event) { System.out.println("Setting menu visible"); menu.setVisible (true); } }); final String imageName; if (SystemUtils.IS_OS_MAC_OSX) { imageName = "16off.png"; } else { imageName = "16on.png"; } final Image image = newImage(imageName, 16, 16); setImage(image); } } private void setImage(final Image image) { display.asyncExec (new Runnable () { @Override public void run () { trayItem.setImage (image); } }); } private Image newImage(final String name, int width, int height) { final File iconFile; final File iconCandidate1 = new File("install/common/"+name); if (iconCandidate1.isFile()) { iconFile = iconCandidate1; } else { iconFile = new File(name); } if (!iconFile.isFile()) { log.error("Still no icon file at: " + iconFile); } InputStream is = null; try { is = new FileInputStream(iconFile); return new Image (display, is); } catch (final FileNotFoundException e) { log.error("Could not find icon file: "+iconFile, e); } return new Image (display, width, height); } @Override public void addUpdate(final Map<String, String> data) { log.info("Adding update data: {}", data); this.updateData = data; display.asyncExec (new Runnable () { @Override public void run () { if (updateItem == null) { updateItem = new MenuItem(menu, SWT.PUSH, 0); updateItem.addListener (SWT.Selection, new Listener () { @Override public void handleEvent (final Event event) { log.info("Got update call"); NativeUtils.openUri(updateData.get( LanternConstants.UPDATE_URL_KEY)); } }); } updateItem.setText(I18n.tr("Update to Lantern ")+ data.get(LanternConstants.UPDATE_VERSION_KEY)); } }); } @Subscribe public void onConnectivityStateChanged( final ConnectivityStatusChangeEvent csce) { final ConnectivityStatus cs = csce.getConnectivityStatus(); log.info("Got connectivity state changed {}", cs); switch (cs) { case DISCONNECTED: { // This could be changed to a red icon. changeIcon("16off.png"); break; } case CONNECTING: { // This could be changed to yellow. changeIcon("16off.png"); break; } case CONNECTED: { changeIcon("16on.png"); break; } case DISCONNECTING: // This could be changed to yellow? changeIcon("16off.png"); break; } } private void changeIcon(final String fileName) { display.asyncExec (new Runnable () { @Override public void run () { if (SystemUtils.IS_OS_MAC_OSX) { log.info("Customizing image on OSX..."); final Image image = newImage(fileName, 16, 16); setImage(image); } } }); } }
src/main/java/org/lantern/SystemTrayImpl.java
package org.lantern; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import java.util.Map; import org.apache.commons.lang.SystemUtils; import org.eclipse.swt.SWT; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.Menu; import org.eclipse.swt.widgets.MenuItem; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Tray; import org.eclipse.swt.widgets.TrayItem; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.eventbus.Subscribe; /** * Class for handling all system tray interactions. */ public class SystemTrayImpl implements SystemTray { private final Logger log = LoggerFactory.getLogger(getClass()); private Display display; private Shell shell; private TrayItem trayItem; private MenuItem updateItem; private Menu menu; private Map<String, String> updateData; /** * Creates a new system tray handler class. * * @param display The SWT display. */ public SystemTrayImpl() { LanternHub.register(this); } @Override public void createTray() { this.display = LanternHub.display(); this.shell = new Shell(display); display.asyncExec (new Runnable () { @Override public void run () { createTrayInternal(); } }); } private void createTrayInternal() { final Tray tray = display.getSystemTray (); if (tray == null) { System.out.println ("The system tray is not available"); } else { this.trayItem = new TrayItem (tray, SWT.NONE); this.trayItem.setToolTipText( I18n.tr("Lantern ")+LanternConstants.VERSION); this.trayItem.addListener (SWT.Show, new Listener () { @Override public void handleEvent (final Event event) { System.out.println("show"); } }); this.trayItem.addListener (SWT.Hide, new Listener () { @Override public void handleEvent (final Event event) { System.out.println("hide"); } }); this.menu = new Menu (shell, SWT.POP_UP); final MenuItem dashboardItem = new MenuItem(menu, SWT.PUSH); dashboardItem.setText("Open Dashboard"); dashboardItem.addListener (SWT.Selection, new Listener () { @Override public void handleEvent (final Event event) { LanternHub.jettyLauncher().openBrowserWhenReady(); } }); new MenuItem(menu, SWT.SEPARATOR); final MenuItem quitItem = new MenuItem(menu, SWT.PUSH); quitItem.setText(I18n.tr("Quit")); quitItem.addListener (SWT.Selection, new Listener () { @Override public void handleEvent (final Event event) { System.out.println("Got exit call"); display.dispose(); System.exit(0); } }); trayItem.addListener (SWT.MenuDetect, new Listener () { @Override public void handleEvent (final Event event) { System.out.println("Setting menu visible"); menu.setVisible (true); } }); final String imageName; if (SystemUtils.IS_OS_MAC_OSX) { imageName = "16off.png"; } else { imageName = "16on.png"; } final Image image = newImage(imageName, 16, 16); setImage(image); } } private void setImage(final Image image) { display.asyncExec (new Runnable () { @Override public void run () { trayItem.setImage (image); } }); } private Image newImage(final String name, int width, int height) { final File iconFile; final File iconCandidate1 = new File("install/common/"+name); if (iconCandidate1.isFile()) { iconFile = iconCandidate1; } else { iconFile = new File(name); } if (!iconFile.isFile()) { log.error("Still no icon file at: " + iconFile); } InputStream is = null; try { is = new FileInputStream(iconFile); return new Image (display, is); } catch (final FileNotFoundException e) { log.error("Could not find icon file: "+iconFile, e); } return new Image (display, width, height); } @Override public void addUpdate(final Map<String, String> data) { log.info("Adding update data: {}", data); this.updateData = data; display.asyncExec (new Runnable () { @Override public void run () { if (updateItem == null) { updateItem = new MenuItem(menu, SWT.PUSH, 0); updateItem.addListener (SWT.Selection, new Listener () { @Override public void handleEvent (final Event event) { log.info("Got update call"); NativeUtils.openUri(updateData.get( LanternConstants.UPDATE_URL_KEY)); } }); } updateItem.setText(I18n.tr("Update to Lantern ")+ data.get(LanternConstants.UPDATE_VERSION_KEY)); } }); } @Subscribe public void onConnectivityStateChanged( final ConnectivityStatusChangeEvent csce) { final ConnectivityStatus cs = csce.getConnectivityStatus(); log.info("Got connectivity state changed {}", cs); switch (cs) { case DISCONNECTED: { // This could be changed to a red icon. changeIcon("16off.png"); break; } case CONNECTING: { // This could be changed to yellow. changeIcon("16off.png"); break; } case CONNECTED: { changeIcon("16on.png"); break; } case DISCONNECTING: // This could be changed to yellow? changeIcon("16off.png"); break; } } private void changeIcon(final String fileName) { display.asyncExec (new Runnable () { @Override public void run () { if (SystemUtils.IS_OS_MAC_OSX) { log.info("Customizing image on OSX..."); final Image image = newImage(fileName, 16, 16); setImage(image); } } }); } }
Change wording of quit item to "Quit Lantern" #134
src/main/java/org/lantern/SystemTrayImpl.java
Change wording of quit item to "Quit Lantern" #134
Java
apache-2.0
27d37382c4a8e570d502d2721f72d4ad212a3f35
0
au-research/ANDS-RIFCS-API
/** * Date Modified: $Date: 2012-04-04 12:13:39 +1000 (Wed, 04 Apr 2012) $ * Version: $Revision: 1695 $ * * Copyright 2009 The Australian National University (ANU) * * 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.ands.rifcs.base; import java.util.ArrayList; import java.util.List; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; /** * Class representing registry object related information. * * @author Scott Yeadon * */ public class CitationMetadata extends RIFCSElement { /** The Identifier for this CitationMetadata. */ private Identifier identifier = null; /** List of Contributor nodes. */ private List<Contributor> names = new ArrayList<Contributor>(); /** List of CitationDate nodes. */ private List<CitationDate> dates = new ArrayList<CitationDate>(); /** * Construct a CitationMetadata object. * * @param n * A w3c Node, typically an Element * * @throws RIFCSException A RIFCSException */ protected CitationMetadata(final Node n) throws RIFCSException { super(n, Constants.ELEMENT_CITATION_METADATA); initStructures(); } /** * Create and return an empty Contributor object. * * The returned object has no properties or content and is not part * of the RIF-CS document, it is essentially a constructor of an object * owned by the RIF-CS document. The returned object needs to be * "filled out" (e.g. with properties, additional sub-elements, etc) * before being added to the RIF-CS document. * * @return the new Contributor object * * @throws RIFCSException A RIFCSException * */ public final Contributor newContributor() throws RIFCSException { return new Contributor(this.newElement(Constants.ELEMENT_CONTRIBUTOR)); } /** * Create and return an empty CitationDate object. * * The returned object has no properties or content and is not part * of the RIF-CS document, it is essentially a constructor of an object * owned by the RIF-CS document. The returned object needs to be * "filled out" (e.g. with properties, additional sub-elements, etc) * before being added to the RIF-CS document. * * @return the new CitationDate object * * @throws RIFCSException A RIFCSException * */ public final CitationDate newCitationDate() throws RIFCSException { return new CitationDate(this.newElement(Constants.ELEMENT_DATE)); } /** * Create and return an empty Identifier object. * * The returned object has no properties or content and is not part * of the RIF-CS document, it is essentially a constructor of an object * owned by the RIF-CS document. The returned object needs to be * "filled out" (e.g. with properties, additional sub-elements, etc) * before being added to the RIF-CS document. * * @return the new Identifier object * * @throws RIFCSException A RIFCSException * */ public final Identifier newIdentifier() throws RIFCSException { return new Identifier(this.newElement(Constants.ELEMENT_IDENTIFIER)); } /** * Set the identifier. * * @param anIdentifier * The identifier of the related information resource * @param type * The type of the identifier * @throws RIFCSException A RIFCSException * */ public final void setIdentifier(final String anIdentifier, final String type) throws RIFCSException { this.identifier = this.newIdentifier(); this.identifier.setValue(anIdentifier); this.identifier.setType(type); this.getElement().appendChild(this.identifier.getElement()); } /** * Obtain the identifier. * * @return Identifier * The identifier of the resource or * <code>null</code> if no identifier is present */ public final Identifier getIdentifier() { return identifier; } /** * Set the title. * * @param title * The title of the related information resource */ public final void setTitle(final String title) { Element e = this.newElement(Constants.ELEMENT_TITLE); e.setTextContent(title); this.getElement().appendChild(e); } /** * Get the title. * * @return String * The title of the related information resource or * <code>null</code> if no title is present */ public final String getTitle() { NodeList nl = super.getElements(Constants.ELEMENT_TITLE); if (nl.getLength() == 1) { return nl.item(0).getTextContent(); } return null; } /** * Set the actionable URI. * * @param url * an actionable URL where the resource can be located */ public final void setURL(final String url) { Element value = this.newElement(Constants.ELEMENT_URL); value.setTextContent(url); this.getElement().appendChild(value); } /** * Return the citation uri. * * @return String * an actionable URI where the resource can be located */ public final String getURL() { NodeList nl = super.getElements(Constants.ELEMENT_URL); if (nl.getLength() == 1) { return nl.item(0).getTextContent(); } return null; } /** * Set the resource edition. * * @param edition * the resource edition */ public final void setEdition(final String edition) { Element e = this.newElement(Constants.ELEMENT_EDITION); e.setTextContent(edition); this.getElement().appendChild(e); } /** * Return the resource edition. * * @return String * the resource edition */ public final String getEdition() { NodeList nl = super.getElements(Constants.ELEMENT_EDITION); if (nl.getLength() == 1) { return nl.item(0).getTextContent(); } return null; } /** * Set the resource publisher. * * @param publisher * the resource publisher */ public final void setPublisher(final String publisher) { Element e = this.newElement(Constants.ELEMENT_PUBLISHER); e.setTextContent(publisher); this.getElement().appendChild(e); } /** * Return the resource publisher. * * @return String * the resource publisher */ public final String getPublisher() { NodeList nl = super.getElements(Constants.ELEMENT_PUBLISHER); if (nl.getLength() == 1) { return nl.item(0).getTextContent(); } return null; } /** * Set the placePublished. * * @param placePublished * the place the resource was published */ public final void setPlacePublished(final String placePublished) { Element e = this.newElement(Constants.ELEMENT_PLACE_PUBLISHED); e.setTextContent(placePublished); this.getElement().appendChild(e); } /** * Return the placePublished. * * @return String * the place the resource was published */ public final String getPlacePublished() { NodeList nl = super.getElements(Constants.ELEMENT_PLACE_PUBLISHED); if (nl.getLength() == 1) { return nl.item(0).getTextContent(); } return null; } /** * Set the resource context. * * @param context * the context of the resource (for example if the resource is * a smaller part of a larger context) */ public final void setContext(final String context) { Element e = this.newElement(Constants.ELEMENT_CONTEXT); e.setTextContent(context); this.getElement().appendChild(e); } /** * Return the context. * * @return String * the context of the resource (for example if the resource is * a smaller part of a larger context) */ public final String getContext() { NodeList nl = super.getElements(Constants.ELEMENT_CONTEXT); if (nl.getLength() == 1) { return nl.item(0).getTextContent(); } return null; } /** * Add a name to the citation information. * * @param contributor * a Contributor object */ public final void addContributor(final Contributor contributor) { this.getElement().appendChild(contributor.getElement()); this.names.add(contributor); } /** * Obtain the contributors to this resource who are required for * forming a citation of this resource. * * @return * A list of Contributor objects */ public final List<Contributor> getContributors() { return names; } /** * Add a date to the citation information. * * @param date * a CitationDate object */ public final void addDate(final CitationDate date) { this.getElement().appendChild(date.getElement()); this.dates.add(date); } /** * Obtain the contributors to this resource who are required for * forming a citation of this resource. * * @return * A list of Contributor objects */ public final List<CitationDate> getDates() { return dates; } /** Initialisation code for existing documents. A wrapper that * invokes initIdentifier(), initContributors(), etc., in turn. * * @throws RIFCSException A RIFCSException * */ private void initStructures() throws RIFCSException { initIdentifier(); initContributors(); initCitationDates(); } /** Initialisation code for identifier elements. * * @throws RIFCSException A RIFCSException * */ private void initIdentifier() throws RIFCSException { NodeList nl = super.getElements(Constants.ELEMENT_IDENTIFIER); if (nl.getLength() > 0) { this.identifier = new Identifier(nl.item(0)); } } /** Initialisation code for contributor elements. * * @throws RIFCSException A RIFCSException * */ private void initContributors() throws RIFCSException { NodeList nl = super.getElements(Constants.ELEMENT_CONTRIBUTOR); for (int i = 0; i < nl.getLength(); i++) { names.add(new Contributor(nl.item(i))); } } /** Initialisation code for citationDate elements. * * @throws RIFCSException A RIFCSException * */ private void initCitationDates() throws RIFCSException { NodeList nl = super.getElements(Constants.ELEMENT_DATE); for (int i = 0; i < nl.getLength(); i++) { dates.add(new CitationDate(nl.item(i))); } } }
src/org/ands/rifcs/base/CitationMetadata.java
/** * Date Modified: $Date: 2012-04-04 12:13:39 +1000 (Wed, 04 Apr 2012) $ * Version: $Revision: 1695 $ * * Copyright 2009 The Australian National University (ANU) * * 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.ands.rifcs.base; import java.util.ArrayList; import java.util.List; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; /** * Class representing registry object related information. * * @author Scott Yeadon * */ public class CitationMetadata extends RIFCSElement { private Identifier identifier = null; private List<Contributor> names = new ArrayList<Contributor>(); private List<CitationDate> dates = new ArrayList<CitationDate>(); /** * Construct a CitationMetadata object. * * @param n * A w3c Node, typically an Element * * @throws RIFCSException A RIFCSException */ protected CitationMetadata(final Node n) throws RIFCSException { super(n, Constants.ELEMENT_CITATION_METADATA); initStructures(); } /** * Create and return an empty Contributor object. * * The returned object has no properties or content and is not part * of the RIF-CS document, it is essentially a constructor of an object * owned by the RIF-CS document. The returned object needs to be * "filled out" (e.g. with properties, additional sub-elements, etc) * before being added to the RIF-CS document. * * @throws RIFCSException A RIFCSException * */ public final Contributor newContributor() throws RIFCSException { return new Contributor(this.newElement(Constants.ELEMENT_CONTRIBUTOR)); } /** * Create and return an empty CitationDate object. * * The returned object has no properties or content and is not part * of the RIF-CS document, it is essentially a constructor of an object * owned by the RIF-CS document. The returned object needs to be * "filled out" (e.g. with properties, additional sub-elements, etc) * before being added to the RIF-CS document. * * @throws RIFCSException A RIFCSException * */ public final CitationDate newCitationDate() throws RIFCSException { return new CitationDate(this.newElement(Constants.ELEMENT_DATE)); } /** * Create and return an empty Identifier object. * * The returned object has no properties or content and is not part * of the RIF-CS document, it is essentially a constructor of an object * owned by the RIF-CS document. The returned object needs to be * "filled out" (e.g. with properties, additional sub-elements, etc) * before being added to the RIF-CS document. * * @throws RIFCSException A RIFCSException * */ public final Identifier newIdentifier() throws RIFCSException { return new Identifier(this.newElement(Constants.ELEMENT_IDENTIFIER)); } /** * Set the identifier. * * @param anIdentifier * The identifier of the related information resource * @param type * The type of the identifier * @throws RIFCSException A RIFCSException * */ public final void setIdentifier(final String anIdentifier, final String type) throws RIFCSException { this.identifier = this.newIdentifier(); this.identifier.setValue(anIdentifier); this.identifier.setType(type); this.getElement().appendChild(this.identifier.getElement()); } /** * Obtain the identifier. * * @return Identifier * The identifier of the resource or * <code>null</code> if no identifier is present */ public final Identifier getIdentifier() { return identifier; } /** * Set the title. * * @param title * The title of the related information resource */ public final void setTitle(final String title) { Element e = this.newElement(Constants.ELEMENT_TITLE); e.setTextContent(title); this.getElement().appendChild(e); } /** * Get the title. * * @return String * The title of the related information resource or * <code>null</code> if no title is present */ public final String getTitle() { NodeList nl = super.getElements(Constants.ELEMENT_TITLE); if (nl.getLength() == 1) { return nl.item(0).getTextContent(); } return null; } /** * Set the actionable URI. * * @param url * an actionable URL where the resource can be located */ public final void setURL(final String url) { Element value = this.newElement(Constants.ELEMENT_URL); value.setTextContent(url); this.getElement().appendChild(value); } /** * Return the citation uri. * * @return String * an actionable URI where the resource can be located */ public final String getURL() { NodeList nl = super.getElements(Constants.ELEMENT_URL); if (nl.getLength() == 1) { return nl.item(0).getTextContent(); } return null; } /** * Set the resource edition. * * @param edition * the resource edition */ public final void setEdition(final String edition) { Element e = this.newElement(Constants.ELEMENT_EDITION); e.setTextContent(edition); this.getElement().appendChild(e); } /** * Return the resource edition. * * @return String * the resource edition */ public final String getEdition() { NodeList nl = super.getElements(Constants.ELEMENT_EDITION); if (nl.getLength() == 1) { return nl.item(0).getTextContent(); } return null; } /** * Set the resource publisher. * * @param publisher * the resource publisher */ public final void setPublisher(final String publisher) { Element e = this.newElement(Constants.ELEMENT_PUBLISHER); e.setTextContent(publisher); this.getElement().appendChild(e); } /** * Return the resource publisher. * * @return String * the resource publisher */ public final String getPublisher() { NodeList nl = super.getElements(Constants.ELEMENT_PUBLISHER); if (nl.getLength() == 1) { return nl.item(0).getTextContent(); } return null; } /** * Set the placePublished. * * @param placePublished * the place the resource was published */ public final void setPlacePublished(final String placePublished) { Element e = this.newElement(Constants.ELEMENT_PLACE_PUBLISHED); e.setTextContent(placePublished); this.getElement().appendChild(e); } /** * Return the placePublished. * * @return String * the place the resource was published */ public final String getPlacePublished() { NodeList nl = super.getElements(Constants.ELEMENT_PLACE_PUBLISHED); if (nl.getLength() == 1) { return nl.item(0).getTextContent(); } return null; } /** * Set the resource context. * * @param context * the context of the resource (for example if the resource is * a smaller part of a larger context) */ public final void setContext(final String context) { Element e = this.newElement(Constants.ELEMENT_CONTEXT); e.setTextContent(context); this.getElement().appendChild(e); } /** * Return the context. * * @return String * the context of the resource (for example if the resource is * a smaller part of a larger context) */ public final String getContext() { NodeList nl = super.getElements(Constants.ELEMENT_CONTEXT); if (nl.getLength() == 1) { return nl.item(0).getTextContent(); } return null; } /** * Add a name to the citation information. * * @param contributor * a Contributor object */ public final void addContributor(final Contributor contributor) { this.getElement().appendChild(contributor.getElement()); this.names.add(contributor); } /** * Obtain the contributors to this resource who are required for * forming a citation of this resource. * * @return * A list of Contributor objects */ public final List<Contributor> getContributors() { return names; } /** * Add a date to the citation information. * * @param date * a CitationDate object */ public final void addDate(final CitationDate date) { this.getElement().appendChild(date.getElement()); this.dates.add(date); } /** * Obtain the contributors to this resource who are required for * forming a citation of this resource. * * @return * A list of Contributor objects */ public final List<CitationDate> getDates() { return dates; } /* initialisation code for existing documents */ private void initStructures() throws RIFCSException { initIdentifier(); initContributors(); initCitationDates(); } /* initialisation code for existing documents */ private void initIdentifier() throws RIFCSException { NodeList nl = super.getElements(Constants.ELEMENT_IDENTIFIER); if (nl.getLength() > 0) { this.identifier = new Identifier(nl.item(0)); } } private void initContributors() throws RIFCSException { NodeList nl = super.getElements(Constants.ELEMENT_CONTRIBUTOR); for (int i = 0; i < nl.getLength(); i++) { names.add(new Contributor(nl.item(i))); } } private void initCitationDates() throws RIFCSException { NodeList nl = super.getElements(Constants.ELEMENT_DATE); for (int i = 0; i < nl.getLength(); i++) { dates.add(new CitationDate(nl.item(i))); } } }
Fix all Javadoc problems in CitationMetadata.java
src/org/ands/rifcs/base/CitationMetadata.java
Fix all Javadoc problems in CitationMetadata.java
Java
apache-2.0
8df37508e06143a52c861612b6d708f5be462650
0
jackscott/storm-graphite,Crim/storm-graphite,pugna0/storm-graphite,verisign/storm-graphite
/* * Copyright 2014 VeriSign, Inc. * * VeriSign 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. * * See the NOTICE file distributed with this work for additional information regarding copyright ownership. */ package com.verisign.storm.metrics; import backtype.storm.metric.api.IMetricsConsumer; import backtype.storm.task.IErrorReporter; import backtype.storm.task.TopologyContext; import com.google.common.base.Throwables; import com.verisign.storm.metrics.graphite.GraphiteAdapter; import com.verisign.storm.metrics.graphite.GraphiteCodec; import com.verisign.storm.metrics.graphite.GraphiteConnectionAttemptFailure; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.net.InetSocketAddress; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Map; /** * Listens for all of Storm's built-in metrics and forwards them to a Graphite server. * * To use, add this to your topology's configuration: * * <pre> * {@code * conf.registerMetricsConsumer(backtype.storm.metrics.GraphiteMetricsConsumer.class, 1); * conf.put("metrics.graphite.host", "<GRAPHITE HOSTNAME>"); * conf.put("metrics.graphite.port", "<GRAPHITE PORT>"); * conf.put("metrics.graphite.prefix", "<DOT DELIMITED PREFIX>"); * } * </pre> * * Or edit the storm.yaml config file: * * <pre> * {@code * topology.metrics.consumer.register: * - class: "backtype.storm.metrics.GraphiteMetricsConsumer" * parallelism.hint: 1 * metrics.graphite.host: "<GRAPHITE HOSTNAME>" * metrics.graphite.port: "<GRAPHITE PORT>" * metrics.graphite.prefix: "<DOT DELIMITED PREFIX>" * } * </pre> */ public class GraphiteMetricsConsumer implements IMetricsConsumer { private static final String GRAPHITE_HOST_OPTION = "metrics.graphite.host"; private static final String GRAPHITE_PORT_OPTION = "metrics.graphite.port"; private static final String GRAPHITE_PREFIX_OPTION = "metrics.graphite.prefix"; private static final Logger LOG = LoggerFactory.getLogger(GraphiteMetricsConsumer.class); private String graphiteHost; private int graphitePort; private String graphitePrefix; private String stormId; private GraphiteAdapter graphite; protected String getStormId() { return stormId; } protected String getGraphiteHost() { return graphiteHost; } protected int getGraphitePort() { return graphitePort; } protected String getGraphitePrefix() { return graphitePrefix; } @Override public void prepare(Map config, Object registrationArgument, TopologyContext context, IErrorReporter errorReporter) { configureGraphite(config); if (registrationArgument instanceof Map) { configureGraphite((Map) registrationArgument); } stormId = context.getStormId(); } private void configureGraphite(@SuppressWarnings("rawtypes") Map conf) { if (conf.containsKey(GRAPHITE_HOST_OPTION)) { graphiteHost = (String) conf.get(GRAPHITE_HOST_OPTION); } if (conf.containsKey(GRAPHITE_PORT_OPTION)) { graphitePort = Integer.parseInt((String) conf.get(GRAPHITE_PORT_OPTION)); } if (conf.containsKey(GRAPHITE_PREFIX_OPTION)) { graphitePrefix = (String) conf.get(GRAPHITE_PREFIX_OPTION); } } @Override @SuppressWarnings("unchecked") public void handleDataPoints(TaskInfo taskInfo, Collection<DataPoint> dataPoints) { graphiteConnect(); for (DataPoint dataPoint : dataPoints) { // TODO: Correctly process metrics of the messaging layer queues and connection states. // These metrics need to be handled differently as they are more structured than raw numbers. // For the moment we ignore these metrics and track this task at // https://github.com/verisign/storm-graphite/issues/2. if (dataPoint.name.equalsIgnoreCase("__send-iconnection") || dataPoint.name.equalsIgnoreCase("__recv-iconnection")) { continue; } // Most data points contain a Map as a value. if (dataPoint.value instanceof Map) { Map<String, Object> m = (Map<String, Object>) dataPoint.value; if (!m.isEmpty()) { for (String key : m.keySet()) { String value = GraphiteCodec.format(m.get(key)); String metricPath = constructMetricName(taskInfo, dataPoint).concat(".").concat(key); String prefixedMetricPath = graphitePrefix.isEmpty() ? metricPath : graphitePrefix.concat(".").concat(metricPath); sendToGraphite(prefixedMetricPath, value, taskInfo.timestamp); } } } else { String value = GraphiteCodec.format(dataPoint.value); String metricPath = constructMetricName(taskInfo, dataPoint).concat(".").concat("value"); String prefixedMetricPath = graphitePrefix.isEmpty() ? metricPath : graphitePrefix.concat(".").concat(metricPath); sendToGraphite(prefixedMetricPath, value, taskInfo.timestamp); } } flush(); graphiteDisconnect(); } /** * Construct a fully qualified name to assign to a particular metric described by dataPoint. * * @param taskInfo The information regarding the context in which the data point is supplied * @param dataPoint The data point (name, value) to assign a name to * * @return A fully qualified metric name assigned to data point */ private String constructMetricName(TaskInfo taskInfo, DataPoint dataPoint) { return stormId.concat(".").concat(taskInfo.srcComponentId).concat(".").concat(dataPoint.name); } protected void graphiteConnect() { graphite = new GraphiteAdapter(new InetSocketAddress(graphiteHost, graphitePort)); try { graphite.connect(); } catch (GraphiteConnectionAttemptFailure e) { String trace = Throwables.getStackTraceAsString(e); LOG.error("Could not connect to Graphite server " + graphite.serverFingerprint() + ": " + trace); } } protected void sendToGraphite(String metricPath, String value, long timestamp) { if (graphite != null ) { graphite.appendToSendBuffer(metricPath, value, timestamp); } } protected void flush() { try { if (graphite != null) { graphite.flushSendBuffer(); } } catch (IOException e) { String trace = Throwables.getStackTraceAsString(e); String msg = "Could not send metrics update to Graphite server " + graphite.serverFingerprint() + ": " + trace + " (" + graphite.getFailures() + " failed attempts so far)"; LOG.error(msg); } } protected void graphiteDisconnect() { if (graphite != null) { graphite.disconnect(); } } @Override public void cleanup() { graphiteDisconnect(); } }
src/main/java/com/verisign/storm/metrics/GraphiteMetricsConsumer.java
/* * Copyright 2014 VeriSign, Inc. * * VeriSign 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. * * See the NOTICE file distributed with this work for additional information regarding copyright ownership. */ package com.verisign.storm.metrics; import backtype.storm.metric.api.IMetricsConsumer; import backtype.storm.task.IErrorReporter; import backtype.storm.task.TopologyContext; import com.google.common.base.Throwables; import com.verisign.storm.metrics.graphite.GraphiteAdapter; import com.verisign.storm.metrics.graphite.GraphiteCodec; import com.verisign.storm.metrics.graphite.GraphiteConnectionAttemptFailure; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.net.InetSocketAddress; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Map; /** * Listens for all of Storm's built-in metrics and forwards them to a Graphite server. * * To use, add this to your topology's configuration: * * <pre> * {@code * conf.registerMetricsConsumer(backtype.storm.metrics.GraphiteMetricsConsumer.class, 1); * conf.put("metrics.graphite.host", "<GRAPHITE HOSTNAME>"); * conf.put("metrics.graphite.port", "<GRAPHITE PORT>"); * conf.put("metrics.graphite.prefix", "<DOT DELIMITED PREFIX>"); * } * </pre> * * Or edit the storm.yaml config file: * * <pre> * {@code * topology.metrics.consumer.register: * - class: "backtype.storm.metrics.GraphiteMetricsConsumer" * parallelism.hint: 1 * metrics.graphite.host: "<GRAPHITE HOSTNAME>" * metrics.graphite.port: "<GRAPHITE PORT>" * metrics.graphite.prefix: "<DOT DELIMITED PREFIX>" * } * </pre> */ public class GraphiteMetricsConsumer implements IMetricsConsumer { private static final String GRAPHITE_HOST_OPTION = "metrics.graphite.host"; private static final String GRAPHITE_PORT_OPTION = "metrics.graphite.port"; private static final String GRAPHITE_PREFIX_OPTION = "metrics.graphite.prefix"; private static final Logger LOG = LoggerFactory.getLogger(GraphiteMetricsConsumer.class); private String graphiteHost; private int graphitePort; private String graphitePrefix; private String stormId; private GraphiteAdapter graphite; protected String getStormId() { return stormId; } protected String getGraphiteHost() { return graphiteHost; } protected int getGraphitePort() { return graphitePort; } protected String getGraphitePrefix() { return graphitePrefix; } @Override public void prepare(Map config, Object registrationArgument, TopologyContext context, IErrorReporter errorReporter) { configureGraphite(config); if (registrationArgument instanceof Map) { configureGraphite((Map) registrationArgument); } stormId = context.getStormId(); } private void configureGraphite(@SuppressWarnings("rawtypes") Map conf) { if (conf.containsKey(GRAPHITE_HOST_OPTION)) { graphiteHost = (String) conf.get(GRAPHITE_HOST_OPTION); } if (conf.containsKey(GRAPHITE_PORT_OPTION)) { graphitePort = Integer.parseInt((String) conf.get(GRAPHITE_PORT_OPTION)); } if (conf.containsKey(GRAPHITE_PREFIX_OPTION)) { graphitePrefix = (String) conf.get(GRAPHITE_PREFIX_OPTION); } } @Override @SuppressWarnings("unchecked") public void handleDataPoints(TaskInfo taskInfo, Collection<DataPoint> dataPoints) { graphiteConnect(); for (DataPoint dataPoint : dataPoints) { // Messaging layer queues and connection states need to be handled differently as they are more structured // than raw numbers. if (dataPoint.name.equalsIgnoreCase("__send-iconnection") || dataPoint.name.equalsIgnoreCase("__recv-iconnection")) { continue; } // Most data points contain a Map as a value. if (dataPoint.value instanceof Map) { Map<String, Object> m = (Map<String, Object>) dataPoint.value; if (!m.isEmpty()) { for (String key : m.keySet()) { String value = GraphiteCodec.format(m.get(key)); String metricPath = constructMetricName(taskInfo, dataPoint).concat(".").concat(key); String prefixedMetricPath = graphitePrefix.isEmpty() ? metricPath : graphitePrefix.concat(".").concat(metricPath); sendToGraphite(prefixedMetricPath, value, taskInfo.timestamp); } } } else { String value = GraphiteCodec.format(dataPoint.value); String metricPath = constructMetricName(taskInfo, dataPoint).concat(".").concat("value"); String prefixedMetricPath = graphitePrefix.isEmpty() ? metricPath : graphitePrefix.concat(".").concat(metricPath); sendToGraphite(prefixedMetricPath, value, taskInfo.timestamp); } } flush(); graphiteDisconnect(); } /** * Construct a fully qualified name to assign to a particular metric described by dataPoint. * * @param taskInfo The information regarding the context in which the data point is supplied * @param dataPoint The data point (name, value) to assign a name to * * @return A fully qualified metric name assigned to data point */ private String constructMetricName(TaskInfo taskInfo, DataPoint dataPoint) { return stormId.concat(".").concat(taskInfo.srcComponentId).concat(".").concat(dataPoint.name); } protected void graphiteConnect() { graphite = new GraphiteAdapter(new InetSocketAddress(graphiteHost, graphitePort)); try { graphite.connect(); } catch (GraphiteConnectionAttemptFailure e) { String trace = Throwables.getStackTraceAsString(e); LOG.error("Could not connect to Graphite server " + graphite.serverFingerprint() + ": " + trace); } } protected void sendToGraphite(String metricPath, String value, long timestamp) { if (graphite != null ) { graphite.appendToSendBuffer(metricPath, value, timestamp); } } protected void flush() { try { if (graphite != null) { graphite.flushSendBuffer(); } } catch (IOException e) { String trace = Throwables.getStackTraceAsString(e); String msg = "Could not send metrics update to Graphite server " + graphite.serverFingerprint() + ": " + trace + " (" + graphite.getFailures() + " failed attempts so far)"; LOG.error(msg); } } protected void graphiteDisconnect() { if (graphite != null) { graphite.disconnect(); } } @Override public void cleanup() { graphiteDisconnect(); } }
Storm 0.10's new connection metrics: add link to GH issue
src/main/java/com/verisign/storm/metrics/GraphiteMetricsConsumer.java
Storm 0.10's new connection metrics: add link to GH issue
Java
apache-2.0
c7e87485c290c4b00a8e33cfa078ec872719440c
0
jasonsparc/Chemistry
package io.jasonsparc.chemistry; import android.support.annotation.AnyRes; import android.support.annotation.LayoutRes; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v7.widget.RecyclerView.ViewHolder; import android.view.ViewGroup; import java.util.ArrayList; import java.util.List; import io.jasonsparc.chemistry.util.IdSelectors; import io.jasonsparc.chemistry.util.ItemBinders; import io.jasonsparc.chemistry.util.VhFactories; import io.jasonsparc.chemistry.util.VhInitializers; import io.jasonsparc.chemistry.util.ViewTypes; /** * Created by Jason on 19/08/2016. */ public abstract class BasicChemistry<Item, VH extends ViewHolder> extends Chemistry<Item> implements VhFactory<VH>, ItemBinder<Item, VH> { @Override public final int getItemViewType(Item item) { return getViewType(); } @Override public final VhFactory<? extends VH> getVhFactory(Item item) { return this; } @Override public final ItemBinder<? super Item, ? super VH> getItemBinder(Item item) { return this; } @ViewType @AnyRes public abstract int getViewType(); @Override public abstract VH createViewHolder(ViewGroup parent); @Override public abstract void bindViewHolder(VH holder, Item item); // Utilities public final <RI extends Item> Boiler<RI, VH> wrap() { return make(this); } public final <RI extends Item> Boiler<RI, VH> wrap(@ViewType @AnyRes int viewType) { return make(viewType, this); } // Boiler-delegating methods public interface Transformer<Item, VH extends ViewHolder> { void apply(Boiler<Item, VH> boiler); } public final Boiler<Item, VH> compose(@NonNull Transformer<? super Item, VH> transformer) { return make(this).compose(transformer); } public final Boiler<Item, VH> useItemIds(@NonNull IdSelector<? super Item> idSelector) { return make(this).useItemIds(idSelector); } public final Boiler<Item, VH> useViewType(@ViewType @AnyRes int viewType) { return make(this).useViewType(viewType); } public final Boiler<Item, VH> useUniqueViewType() { return make(this).useUniqueViewType(); } public final Boiler<Item, VH> useVhFactory(@NonNull VhFactory<? extends VH> vhFactory) { return make(this).useVhFactory(vhFactory); } public final Boiler<Item, VH> useVhFactory(@NonNull ViewFactory viewFactory, @NonNull ItemVhFactory<? extends VH> itemVhFactory) { return make(this).useVhFactory(viewFactory, itemVhFactory); } public final Boiler<Item, VH> useVhFactory(@NonNull ViewFactory viewFactory, @NonNull Class<? extends VH> vhClass) { return make(this).useVhFactory(viewFactory, vhClass); } public final Boiler<Item, VH> useVhFactory(@LayoutRes int itemLayout, @NonNull ItemVhFactory<? extends VH> itemVhFactory) { return make(this).useVhFactory(itemLayout, itemVhFactory); } public final Boiler<Item, VH> useVhFactory(@LayoutRes int itemLayout, @NonNull Class<? extends VH> vhClass) { return make(this).useVhFactory(itemLayout, vhClass); } public final Boiler<Item, VH> addInit(@NonNull VhInitializer<? super VH> vhInitializer) { return make(this).addInit(vhInitializer); } public final Boiler<Item, VH> addBinder(@NonNull ItemBinder<? super Item, ? super VH> itemBinder) { return make(this).addBinder(itemBinder); } public final Boiler<Item, VH> add(@NonNull VhInitializer<? super VH> vhInitializer) { return make(this).add(vhInitializer); } public final Boiler<Item, VH> add(@NonNull ItemBinder<? super Item, ? super VH> itemBinder) { return make(this).add(itemBinder); } // Boiler implementation public static final class Boiler<Item, VH extends ViewHolder> { @NonNull IdSelector<? super Item> idSelector; @ViewType @AnyRes int viewType; @Nullable VhFactory<? extends VH> vhFactory; final ArrayList<VhInitializer<? super VH>> vhInitializers = new ArrayList<>(4); final ArrayList<ItemBinder<? super Item, ? super VH>> itemBinders = new ArrayList<>(4); Boiler() { idSelector = IdSelectors.empty(); } Boiler(@NonNull Preperator<? super Item> preperator) { idSelector = preperator.idSelector; viewType = preperator.viewType; } Boiler(@NonNull Preperator<? super Item> preperator, @NonNull VhFactory<? extends VH> vhFactory) { this(preperator); this.vhFactory = vhFactory; } Boiler(@NonNull BasicChemistry<? super Item, VH> base) { if (base instanceof CompositeImpl<?, ?>) { @SuppressWarnings("unchecked") CompositeImpl<? super Item, VH> composite = (CompositeImpl) base; idSelector = composite.idSelector; viewType = composite.viewType; vhFactory = composite.vhFactory; itemBinders.add(composite.itemBinder); } else { idSelector = base; viewType = base.getViewType(); vhFactory = base; itemBinders.add(base); } } public BasicChemistry<Item, VH> boil() { return new CompositeImpl<>(this); } @SuppressWarnings("unchecked") public Boiler<Item, VH> compose(@NonNull Transformer<? super Item, VH> transformer) { ((Transformer<Item, VH>) transformer).apply(this); return this; } public Boiler<Item, VH> useItemIds(@NonNull IdSelector<? super Item> idSelector) { this.idSelector = idSelector; return this; } public Boiler<Item, VH> useViewType(@ViewType @AnyRes int viewType) { ViewTypes.validateArgument(viewType); this.viewType = viewType; return this; } public Boiler<Item, VH> useUniqueViewType() { //noinspection Range this.viewType = 0; // Defer id generation. See CompositeImpl below... return this; } public Boiler<Item, VH> useVhFactory(@NonNull VhFactory<? extends VH> vhFactory) { this.vhFactory = vhFactory; return this; } public Boiler<Item, VH> useVhFactory(@NonNull ViewFactory viewFactory, @NonNull ItemVhFactory<? extends VH> itemVhFactory) { vhFactory = VhFactories.make(viewFactory, itemVhFactory); return this; } public Boiler<Item, VH> useVhFactory(@NonNull ViewFactory viewFactory, @NonNull Class<? extends VH> vhClass) { vhFactory = VhFactories.make(viewFactory, vhClass); return this; } public Boiler<Item, VH> useVhFactory(@LayoutRes int itemLayout, @NonNull ItemVhFactory<? extends VH> itemVhFactory) { vhFactory = VhFactories.make(itemLayout, itemVhFactory); return this; } public Boiler<Item, VH> useVhFactory(@LayoutRes int itemLayout, @NonNull Class<? extends VH> vhClass) { vhFactory = VhFactories.make(itemLayout, vhClass); return this; } public Boiler<Item, VH> addInit(@NonNull VhInitializer<? super VH> vhInitializer) { vhInitializers.add(vhInitializer); return this; } public Boiler<Item, VH> addBinder(@NonNull ItemBinder<? super Item, ? super VH> itemBinder) { itemBinders.add(itemBinder); return this; } public Boiler<Item, VH> add(@NonNull VhInitializer<? super VH> vhInitializer) { vhInitializers.add(vhInitializer); return this; } public Boiler<Item, VH> add(@NonNull ItemBinder<? super Item, ? super VH> itemBinder) { itemBinders.add(itemBinder); return this; } public List<VhInitializer<? super VH>> vhInitializers() { return vhInitializers; } public List<ItemBinder<? super Item, ? super VH>> itemBinders() { return itemBinders; } } // Preperator implementation public static final class Preperator<Item> { @NonNull IdSelector<? super Item> idSelector = IdSelectors.empty(); @ViewType @AnyRes int viewType; Preperator() { } public Preperator<Item> useItemIds(@NonNull IdSelector<? super Item> idSelector) { this.idSelector = idSelector; return this; } public Preperator<Item> useViewType(@ViewType @AnyRes int viewType) { ViewTypes.validateArgument(viewType); this.viewType = viewType; return this; } public Preperator<Item> useUniqueViewType() { //noinspection Range this.viewType = 0; // Defer id generation. See CompositeImpl below... return this; } public <VH extends ViewHolder> Boiler<Item, VH> useVhFactory(@NonNull VhFactory<? extends VH> vhFactory) { return new Boiler<>(this, vhFactory); } public <VH extends ViewHolder> Boiler<Item, VH> useVhFactory(@NonNull ViewFactory viewFactory, @NonNull ItemVhFactory<? extends VH> itemVhFactory) { return new Boiler<>(this, VhFactories.make(viewFactory, itemVhFactory)); } public <VH extends ViewHolder> Boiler<Item, VH> useVhFactory(@NonNull ViewFactory viewFactory, @NonNull Class<? extends VH> vhClass) { return new Boiler<>(this, VhFactories.make(viewFactory, vhClass)); } public <VH extends ViewHolder> Boiler<Item, VH> useVhFactory(@LayoutRes int itemLayout, @NonNull ItemVhFactory<? extends VH> itemVhFactory) { return new Boiler<>(this, VhFactories.make(itemLayout, itemVhFactory)); } public <VH extends ViewHolder> Boiler<Item, VH> useVhFactory(@LayoutRes int itemLayout, @NonNull Class<? extends VH> vhClass) { return new Boiler<>(this, VhFactories.make(itemLayout, vhClass)); } public <VH extends ViewHolder> Boiler<Item, VH> compose(@NonNull Transformer<? super Item, VH> transformer) { return new Boiler<Item, VH>(this).compose(transformer); } public <VH extends ViewHolder> Boiler<Item, VH> makeBoiler() { return new Boiler<>(this); } } // Internals static final class CompositeImpl<Item, VH extends ViewHolder> extends BasicChemistry<Item, VH> { @NonNull final IdSelector<? super Item> idSelector; @ViewType @AnyRes final int viewType; @NonNull final VhFactory<? extends VH> vhFactory; @NonNull final ItemBinder<? super Item, ? super VH> itemBinder; CompositeImpl(@NonNull BasicChemistry.Boiler<Item, VH> boiler) { // Must perform a special null-check for vhFactory, in case the user forgot to set it. if (boiler.vhFactory == null) throw new NullPointerException("vhFactory == null; forgot to set it?"); vhFactory = VhFactories.make(boiler.vhFactory, VhInitializers.make(boiler.vhInitializers)); itemBinder = ItemBinders.make(boiler.itemBinders); idSelector = boiler.idSelector; //noinspection Range viewType = boiler.viewType != 0 ? boiler.viewType : ViewTypes.generate(); } @Override public long getItemId(Item item) { return idSelector.getItemId(item); } @Override public int getViewType() { return viewType; } @Override public VH createViewHolder(ViewGroup parent) { return vhFactory.createViewHolder(parent); } @Override public void bindViewHolder(VH holder, Item item) { itemBinder.bindViewHolder(holder, item); } } }
library/src/main/java/io/jasonsparc/chemistry/BasicChemistry.java
package io.jasonsparc.chemistry; import android.support.annotation.AnyRes; import android.support.annotation.LayoutRes; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v7.widget.RecyclerView.ViewHolder; import android.view.ViewGroup; import java.util.ArrayList; import java.util.List; import io.jasonsparc.chemistry.util.IdSelectors; import io.jasonsparc.chemistry.util.ItemBinders; import io.jasonsparc.chemistry.util.VhFactories; import io.jasonsparc.chemistry.util.VhInitializers; import io.jasonsparc.chemistry.util.ViewTypes; /** * Created by Jason on 19/08/2016. */ public abstract class BasicChemistry<Item, VH extends ViewHolder> extends Chemistry<Item> implements VhFactory<VH>, ItemBinder<Item, VH> { @Override public final int getItemViewType(Item item) { return getViewType(); } @Override public final VhFactory<? extends VH> getVhFactory(Item item) { return this; } @Override public final ItemBinder<? super Item, ? super VH> getItemBinder(Item item) { return this; } @ViewType @AnyRes public abstract int getViewType(); @Override public abstract VH createViewHolder(ViewGroup parent); @Override public abstract void bindViewHolder(VH holder, Item item); // Utilities public final <RI extends Item> Boiler<RI, VH> boiler() { return make(this); } public final <RI extends Item> Boiler<RI, VH> boiler(@ViewType @AnyRes int viewType) { return make(viewType, this); } // Boiler-delegating methods public interface Transformer<Item, VH extends ViewHolder> { void apply(Boiler<Item, VH> boiler); } public final Boiler<Item, VH> compose(@NonNull Transformer<? super Item, VH> transformer) { return make(this).compose(transformer); } public final Boiler<Item, VH> useItemIds(@NonNull IdSelector<? super Item> idSelector) { return make(this).useItemIds(idSelector); } public final Boiler<Item, VH> useViewType(@ViewType @AnyRes int viewType) { return make(this).useViewType(viewType); } public final Boiler<Item, VH> useUniqueViewType() { return make(this).useUniqueViewType(); } public final Boiler<Item, VH> useVhFactory(@NonNull VhFactory<? extends VH> vhFactory) { return make(this).useVhFactory(vhFactory); } public final Boiler<Item, VH> useVhFactory(@NonNull ViewFactory viewFactory, @NonNull ItemVhFactory<? extends VH> itemVhFactory) { return make(this).useVhFactory(viewFactory, itemVhFactory); } public final Boiler<Item, VH> useVhFactory(@NonNull ViewFactory viewFactory, @NonNull Class<? extends VH> vhClass) { return make(this).useVhFactory(viewFactory, vhClass); } public final Boiler<Item, VH> useVhFactory(@LayoutRes int itemLayout, @NonNull ItemVhFactory<? extends VH> itemVhFactory) { return make(this).useVhFactory(itemLayout, itemVhFactory); } public final Boiler<Item, VH> useVhFactory(@LayoutRes int itemLayout, @NonNull Class<? extends VH> vhClass) { return make(this).useVhFactory(itemLayout, vhClass); } public final Boiler<Item, VH> addInit(@NonNull VhInitializer<? super VH> vhInitializer) { return make(this).addInit(vhInitializer); } public final Boiler<Item, VH> addBinder(@NonNull ItemBinder<? super Item, ? super VH> itemBinder) { return make(this).addBinder(itemBinder); } public final Boiler<Item, VH> add(@NonNull VhInitializer<? super VH> vhInitializer) { return make(this).add(vhInitializer); } public final Boiler<Item, VH> add(@NonNull ItemBinder<? super Item, ? super VH> itemBinder) { return make(this).add(itemBinder); } // Boiler implementation public static final class Boiler<Item, VH extends ViewHolder> { @NonNull IdSelector<? super Item> idSelector; @ViewType @AnyRes int viewType; @Nullable VhFactory<? extends VH> vhFactory; final ArrayList<VhInitializer<? super VH>> vhInitializers = new ArrayList<>(4); final ArrayList<ItemBinder<? super Item, ? super VH>> itemBinders = new ArrayList<>(4); Boiler() { idSelector = IdSelectors.empty(); } Boiler(@NonNull Preperator<? super Item> preperator) { idSelector = preperator.idSelector; viewType = preperator.viewType; } Boiler(@NonNull Preperator<? super Item> preperator, @NonNull VhFactory<? extends VH> vhFactory) { this(preperator); this.vhFactory = vhFactory; } Boiler(@NonNull BasicChemistry<? super Item, VH> base) { if (base instanceof CompositeImpl<?, ?>) { @SuppressWarnings("unchecked") CompositeImpl<? super Item, VH> composite = (CompositeImpl) base; idSelector = composite.idSelector; viewType = composite.viewType; vhFactory = composite.vhFactory; itemBinders.add(composite.itemBinder); } else { idSelector = base; viewType = base.getViewType(); vhFactory = base; itemBinders.add(base); } } public BasicChemistry<Item, VH> boil() { return new CompositeImpl<>(this); } @SuppressWarnings("unchecked") public Boiler<Item, VH> compose(@NonNull Transformer<? super Item, VH> transformer) { ((Transformer<Item, VH>) transformer).apply(this); return this; } public Boiler<Item, VH> useItemIds(@NonNull IdSelector<? super Item> idSelector) { this.idSelector = idSelector; return this; } public Boiler<Item, VH> useViewType(@ViewType @AnyRes int viewType) { ViewTypes.validateArgument(viewType); this.viewType = viewType; return this; } public Boiler<Item, VH> useUniqueViewType() { //noinspection Range this.viewType = 0; // Defer id generation. See CompositeImpl below... return this; } public Boiler<Item, VH> useVhFactory(@NonNull VhFactory<? extends VH> vhFactory) { this.vhFactory = vhFactory; return this; } public Boiler<Item, VH> useVhFactory(@NonNull ViewFactory viewFactory, @NonNull ItemVhFactory<? extends VH> itemVhFactory) { vhFactory = VhFactories.make(viewFactory, itemVhFactory); return this; } public Boiler<Item, VH> useVhFactory(@NonNull ViewFactory viewFactory, @NonNull Class<? extends VH> vhClass) { vhFactory = VhFactories.make(viewFactory, vhClass); return this; } public Boiler<Item, VH> useVhFactory(@LayoutRes int itemLayout, @NonNull ItemVhFactory<? extends VH> itemVhFactory) { vhFactory = VhFactories.make(itemLayout, itemVhFactory); return this; } public Boiler<Item, VH> useVhFactory(@LayoutRes int itemLayout, @NonNull Class<? extends VH> vhClass) { vhFactory = VhFactories.make(itemLayout, vhClass); return this; } public Boiler<Item, VH> addInit(@NonNull VhInitializer<? super VH> vhInitializer) { vhInitializers.add(vhInitializer); return this; } public Boiler<Item, VH> addBinder(@NonNull ItemBinder<? super Item, ? super VH> itemBinder) { itemBinders.add(itemBinder); return this; } public Boiler<Item, VH> add(@NonNull VhInitializer<? super VH> vhInitializer) { vhInitializers.add(vhInitializer); return this; } public Boiler<Item, VH> add(@NonNull ItemBinder<? super Item, ? super VH> itemBinder) { itemBinders.add(itemBinder); return this; } public List<VhInitializer<? super VH>> vhInitializers() { return vhInitializers; } public List<ItemBinder<? super Item, ? super VH>> itemBinders() { return itemBinders; } } // Preperator implementation public static final class Preperator<Item> { @NonNull IdSelector<? super Item> idSelector = IdSelectors.empty(); @ViewType @AnyRes int viewType; Preperator() { } public Preperator<Item> useItemIds(@NonNull IdSelector<? super Item> idSelector) { this.idSelector = idSelector; return this; } public Preperator<Item> useViewType(@ViewType @AnyRes int viewType) { ViewTypes.validateArgument(viewType); this.viewType = viewType; return this; } public Preperator<Item> useUniqueViewType() { //noinspection Range this.viewType = 0; // Defer id generation. See CompositeImpl below... return this; } public <VH extends ViewHolder> Boiler<Item, VH> useVhFactory(@NonNull VhFactory<? extends VH> vhFactory) { return new Boiler<>(this, vhFactory); } public <VH extends ViewHolder> Boiler<Item, VH> useVhFactory(@NonNull ViewFactory viewFactory, @NonNull ItemVhFactory<? extends VH> itemVhFactory) { return new Boiler<>(this, VhFactories.make(viewFactory, itemVhFactory)); } public <VH extends ViewHolder> Boiler<Item, VH> useVhFactory(@NonNull ViewFactory viewFactory, @NonNull Class<? extends VH> vhClass) { return new Boiler<>(this, VhFactories.make(viewFactory, vhClass)); } public <VH extends ViewHolder> Boiler<Item, VH> useVhFactory(@LayoutRes int itemLayout, @NonNull ItemVhFactory<? extends VH> itemVhFactory) { return new Boiler<>(this, VhFactories.make(itemLayout, itemVhFactory)); } public <VH extends ViewHolder> Boiler<Item, VH> useVhFactory(@LayoutRes int itemLayout, @NonNull Class<? extends VH> vhClass) { return new Boiler<>(this, VhFactories.make(itemLayout, vhClass)); } public <VH extends ViewHolder> Boiler<Item, VH> compose(@NonNull Transformer<? super Item, VH> transformer) { return new Boiler<Item, VH>(this).compose(transformer); } public <VH extends ViewHolder> Boiler<Item, VH> makeBoiler() { return new Boiler<>(this); } } // Internals static final class CompositeImpl<Item, VH extends ViewHolder> extends BasicChemistry<Item, VH> { @NonNull final IdSelector<? super Item> idSelector; @ViewType @AnyRes final int viewType; @NonNull final VhFactory<? extends VH> vhFactory; @NonNull final ItemBinder<? super Item, ? super VH> itemBinder; CompositeImpl(@NonNull BasicChemistry.Boiler<Item, VH> boiler) { // Must perform a special null-check for vhFactory, in case the user forgot to set it. if (boiler.vhFactory == null) throw new NullPointerException("vhFactory == null; forgot to set it?"); vhFactory = VhFactories.make(boiler.vhFactory, VhInitializers.make(boiler.vhInitializers)); itemBinder = ItemBinders.make(boiler.itemBinders); idSelector = boiler.idSelector; //noinspection Range viewType = boiler.viewType != 0 ? boiler.viewType : ViewTypes.generate(); } @Override public long getItemId(Item item) { return idSelector.getItemId(item); } @Override public int getViewType() { return viewType; } @Override public VH createViewHolder(ViewGroup parent) { return vhFactory.createViewHolder(parent); } @Override public void bindViewHolder(VH holder, Item item) { itemBinder.bindViewHolder(holder, item); } } }
Rename boiler-providing method to its actual outcome
library/src/main/java/io/jasonsparc/chemistry/BasicChemistry.java
Rename boiler-providing method to its actual outcome
Java
apache-2.0
228453e4c30affef7187a13900be8eb19ac7549d
0
Tycheo/coffeemud,oriontribunal/CoffeeMud,bozimmerman/CoffeeMud,oriontribunal/CoffeeMud,Tycheo/coffeemud,MaxRau/CoffeeMud,sfunk1x/CoffeeMud,Tycheo/coffeemud,bozimmerman/CoffeeMud,Tycheo/coffeemud,MaxRau/CoffeeMud,MaxRau/CoffeeMud,sfunk1x/CoffeeMud,MaxRau/CoffeeMud,oriontribunal/CoffeeMud,bozimmerman/CoffeeMud,bozimmerman/CoffeeMud,sfunk1x/CoffeeMud,oriontribunal/CoffeeMud,sfunk1x/CoffeeMud
package com.planet_ink.coffee_mud.application; import com.planet_ink.coffee_mud.core.*; import com.planet_ink.coffee_mud.core.CMSecurity.DbgFlag; import com.planet_ink.coffee_mud.core.interfaces.*; import com.planet_ink.coffee_mud.core.collections.*; import com.planet_ink.coffee_mud.core.exceptions.*; import com.planet_ink.coffee_mud.Abilities.interfaces.*; import com.planet_ink.coffee_mud.Areas.interfaces.*; import com.planet_ink.coffee_mud.Behaviors.interfaces.*; import com.planet_ink.coffee_mud.CharClasses.interfaces.*; import com.planet_ink.coffee_mud.Commands.interfaces.*; import com.planet_ink.coffee_mud.Common.interfaces.*; import com.planet_ink.coffee_mud.Exits.interfaces.*; import com.planet_ink.coffee_mud.Items.interfaces.*; import com.planet_ink.coffee_mud.Locales.interfaces.*; import com.planet_ink.coffee_mud.MOBS.interfaces.*; import com.planet_ink.coffee_mud.Races.interfaces.*; import com.planet_ink.coffee_mud.Libraries.interfaces.*; import com.planet_ink.coffee_mud.core.database.DBConnector; import com.planet_ink.coffee_mud.core.database.DBConnection; import com.planet_ink.coffee_mud.core.database.DBInterface; import com.planet_ink.coffee_mud.core.threads.CMRunnable; import com.planet_ink.coffee_mud.core.threads.ServiceEngine; import com.planet_ink.coffee_mud.core.smtp.SMTPserver; import com.planet_ink.coffee_mud.core.intermud.IMudClient; import com.planet_ink.coffee_mud.core.intermud.cm1.CM1Server; import com.planet_ink.coffee_mud.core.intermud.i3.IMudInterface; import com.planet_ink.coffee_mud.core.intermud.imc2.IMC2Driver; import com.planet_ink.coffee_mud.core.intermud.i3.server.I3Server; import com.planet_ink.coffee_web.http.MIMEType; import com.planet_ink.coffee_web.interfaces.FileManager; import com.planet_ink.coffee_web.server.WebServer; import com.planet_ink.coffee_web.util.CWConfig; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.InputStream; import java.io.PrintWriter; // for writing to sockets import java.io.IOException; import java.io.RandomAccessFile; import java.lang.reflect.Method; import java.net.*; import java.util.*; import java.sql.*; /* Copyright 2000-2014 Bo Zimmerman 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. */ public class MUD extends Thread implements MudHost { private static final float HOST_VERSION_MAJOR = (float)5.8; private static final float HOST_VERSION_MINOR = (float)4.2; private static enum MudState {STARTING,WAITING,ACCEPTING,STOPPED} private volatile MudState state = MudState.STOPPED; private ServerSocket servsock = null; private boolean acceptConns= false; private final String host = "MyHost"; private int port = 5555; private final long startupTime= System.currentTimeMillis(); private final ThreadGroup threadGroup; private static volatile int grpid = 0; private static boolean bringDown = false; private static String execExternalCommand = null; private static I3Server i3server = null; private static IMC2Driver imc2server = null; private static List<WebServer> webServers = new Vector<WebServer>(); private static SMTPserver smtpServerThread = null; private static List<String> autoblocked = new Vector<String>(); private static List<DBConnector> databases = new Vector<DBConnector>(); private static List<CM1Server> cm1Servers = new Vector<CM1Server>(); private static List<Triad<String,Long,Integer>> accessed = new LinkedList<Triad<String,Long,Integer>>(); private static final ServiceEngine serviceEngine = new ServiceEngine(); public MUD(String name) { super(name); threadGroup=Thread.currentThread().getThreadGroup(); } @Override public void acceptConnection(Socket sock) throws SocketException, IOException { setState(MudState.ACCEPTING); serviceEngine.executeRunnable(threadGroup.getName(),new ConnectionAcceptor(sock)); } @Override public ThreadGroup threadGroup() { return threadGroup; } private class ConnectionAcceptor implements CMRunnable { Socket sock; long startTime=0; public ConnectionAcceptor(Socket sock) throws SocketException, IOException { this.sock=sock; sock.setSoLinger(true,3); } @Override public long getStartTime() { return startTime; } @Override public int getGroupID() { return Thread.currentThread().getThreadGroup().getName().charAt(0); } @Override public void run() { startTime=System.currentTimeMillis(); try { if (acceptConns) { String address="unknown"; try{address=sock.getInetAddress().getHostAddress().trim();}catch(final Exception e){} int proceed=0; if(CMSecurity.isBanned(address)) proceed=1; int numAtThisAddress=0; final long LastConnectionDelay=(5*60*1000); boolean anyAtThisAddress=false; final int maxAtThisAddress=6; if(!CMSecurity.isDisabled(CMSecurity.DisFlag.CONNSPAMBLOCK)) { if(!CMProps.isOnWhiteList(CMProps.SYSTEMWL_CONNS, address)) { synchronized(accessed) { for(final Iterator<Triad<String,Long,Integer>> i=accessed.iterator();i.hasNext();) { final Triad<String,Long,Integer> triad=i.next(); if((triad.second.longValue()+LastConnectionDelay)<System.currentTimeMillis()) i.remove(); else if(triad.first.trim().equalsIgnoreCase(address)) { anyAtThisAddress=true; triad.second=Long.valueOf(System.currentTimeMillis()); numAtThisAddress=triad.third.intValue()+1; triad.third=Integer.valueOf(numAtThisAddress); } } if(!anyAtThisAddress) accessed.add(new Triad<String,Long,Integer>(address,Long.valueOf(System.currentTimeMillis()),Integer.valueOf(1))); } if(autoblocked.contains(address.toUpperCase())) { if(!anyAtThisAddress) autoblocked.remove(address.toUpperCase()); else proceed=2; } else if(numAtThisAddress>=maxAtThisAddress) { autoblocked.add(address.toUpperCase()); proceed=2; } } } if(proceed!=0) { final int abusiveCount=numAtThisAddress-maxAtThisAddress+1; final long rounder=Math.round(Math.sqrt(abusiveCount)); if(abusiveCount == (rounder*rounder)) Log.sysOut(Thread.currentThread().getName(),"Blocking a connection from "+address +" ("+numAtThisAddress+")"); try { final PrintWriter out = new PrintWriter(sock.getOutputStream()); out.println("\n\rOFFLINE: Blocked\n\r"); out.flush(); if(proceed==2) out.println("\n\rYour address has been blocked temporarily due to excessive invalid connections. Please try back in " + (LastConnectionDelay/60000) + " minutes, and not before.\n\r\n\r"); else out.println("\n\rYou are unwelcome. No one likes you here. Go away.\n\r\n\r"); out.flush(); try{Thread.sleep(250);}catch(final Exception e){} out.close(); } catch(final IOException e) { // dont say anything, just eat it. } sock = null; } else { Log.sysOut(Thread.currentThread().getName(),"Connection from "+address); // also the intro page final CMFile introDir=new CMFile(Resources.makeFileResourceName("text"),null,CMFile.FLAG_FORCEALLOW); String introFilename="text/intro.txt"; if(introDir.isDirectory()) { final CMFile[] files=introDir.listFiles(); final Vector<String> choices=new Vector<String>(); for (final CMFile file : files) if(file.getName().toLowerCase().startsWith("intro") &&file.getName().toLowerCase().endsWith(".txt")) choices.addElement("text/"+file.getName()); if(choices.size()>0) introFilename=choices.elementAt(CMLib.dice().roll(1,choices.size(),-1)); } StringBuffer introText=Resources.getFileResource(introFilename,true); try { introText = CMLib.webMacroFilter().virtualPageFilter(introText);}catch(final Exception ex){} final Session S=(Session)CMClass.getCommon("DefaultSession"); S.initializeSession(sock, threadGroup().getName(), introText != null ? introText.toString() : null); CMLib.sessions().add(S); sock = null; } } else if((CMLib.database()!=null)&&(CMLib.database().isConnected())&&(CMLib.encoder()!=null)) { StringBuffer rejectText; try { rejectText = Resources.getFileResource("text/offline.txt",true); } catch(final java.lang.NullPointerException npe) { rejectText=new StringBuffer("");} try { final PrintWriter out = new PrintWriter(sock.getOutputStream()); out.println("\n\rOFFLINE: " + CMProps.getVar(CMProps.Str.MUDSTATUS)+"\n\r"); out.println(rejectText); out.flush(); try{Thread.sleep(1000);}catch(final Exception e){} out.close(); } catch(final IOException e) { // dont say anything, just eat it. } sock = null; } else { try{sock.close();}catch(final Exception e){} sock = null; } } finally { startTime=0; } } @Override public long activeTimeMillis() { return (startTime>0)?System.currentTimeMillis()-startTime:0;} } @Override public String getLanguage() { final String lang = CMProps.instance().getStr("LANGUAGE").toUpperCase().trim(); if(lang.length()==0) return "English"; for (final String[] element : LanguageLibrary.ISO_LANG_CODES) if(lang.equals(element[0])) return element[1]; return "English"; } public void setState(MudState st) { if(st!=state) state=st; } @Override public void run() { setState(MudState.STARTING); int q_len = 6; Socket sock=null; InetAddress bindAddr = null; if (CMProps.getIntVar(CMProps.Int.MUDBACKLOG) > 0) q_len = CMProps.getIntVar(CMProps.Int.MUDBACKLOG); if (CMProps.getVar(CMProps.Str.MUDBINDADDRESS).length() > 0) { try { bindAddr = InetAddress.getByName(CMProps.getVar(CMProps.Str.MUDBINDADDRESS)); } catch (final UnknownHostException e) { Log.errOut(Thread.currentThread().getName(),"ERROR: MUD Server could not bind to address " + CMProps.getVar(CMProps.Str.MUDBINDADDRESS)); } } try { servsock=new ServerSocket(port, q_len, bindAddr); Log.sysOut(Thread.currentThread().getName(),"MUD Server started on port: "+port); if (bindAddr != null) Log.sysOut(Thread.currentThread().getName(),"MUD Server bound to: "+bindAddr.toString()); CMLib.hosts().add(this); while(servsock!=null) { setState(MudState.WAITING); sock=servsock.accept(); acceptConnection(sock); } } catch(final Exception t) { if((!(t instanceof java.net.SocketException)) ||(t.getMessage()==null) ||(t.getMessage().toLowerCase().indexOf("socket closed")<0)) { Log.errOut(Thread.currentThread().getName(),t); } } Log.sysOut(Thread.currentThread().getName(),"Server cleaning up."); try { if(servsock!=null) servsock.close(); if(sock!=null) sock.close(); } catch(final IOException e) { } Log.sysOut(Thread.currentThread().getName(),"MUD on port "+port+" stopped!"); setState(MudState.STOPPED); CMLib.hosts().remove(this); } @Override public String getStatus() { if(CMProps.getBoolVar(CMProps.Bool.MUDSHUTTINGDOWN)) return CMProps.getVar(CMProps.Str.MUDSTATUS); if(!CMProps.getBoolVar(CMProps.Bool.MUDSTARTED)) return CMProps.getVar(CMProps.Str.MUDSTATUS); return state.toString(); } @Override public void shutdown(Session S, boolean keepItDown, String externalCommand) { globalShutdown(S,keepItDown,externalCommand); interrupt(); // kill the damn archon thread. } public static void defaultShutdown() { globalShutdown(null,true,null); } public static void globalShutdown(Session S, boolean keepItDown, String externalCommand) { CMProps.setBoolAllVar(CMProps.Bool.MUDSTARTED,false); CMProps.setBoolAllVar(CMProps.Bool.MUDSHUTTINGDOWN,true); serviceEngine.suspendAll(null); if(S!=null) S.print(CMLib.lang().L("Closing MUD listeners to new connections...")); for(int i=0;i<CMLib.hosts().size();i++) CMLib.hosts().get(i).setAcceptConnections(false); Log.sysOut(Thread.currentThread().getName(),"New Connections are now closed"); if(S!=null) S.println(CMLib.lang().L("Done.")); if(!CMSecurity.isSaveFlag("NOPLAYERS")) { if(S!=null) S.print(CMLib.lang().L("Saving players...")); CMProps.setUpAllLowVar(CMProps.Str.MUDSTATUS,"Shutting down...Saving players..."); for(final Enumeration<CMLibrary> e=CMLib.libraries(CMLib.Library.SESSIONS);e.hasMoreElements();) { final SessionsList list=((SessionsList)e.nextElement()); for(final Session S2 : list.allIterable()) { final MOB M = S2.mob(); if((M!=null)&&(M.playerStats()!=null)) { M.playerStats().setLastDateTime(System.currentTimeMillis()); // important! shutdown their affects! for(int a=M.numAllEffects()-1;a>=0;a--) // reverse enumeration { final Ability A=M.fetchEffect(a); try { if((A!=null)&&(A.canBeUninvoked())) A.unInvoke(); if((A!=null)&&(!A.isSavable())) M.delEffect(A); } catch(final Exception ex) {Log.errOut(ex);} } } } } for(final Enumeration<CMLibrary> e=CMLib.libraries(CMLib.Library.PLAYERS);e.hasMoreElements();) ((PlayerLibrary)e.nextElement()).savePlayers(); if(S!=null) S.println(CMLib.lang().L("done")); Log.sysOut(Thread.currentThread().getName(),"All users saved."); } if(S!=null) S.print(CMLib.lang().L("Saving stats...")); for(final Enumeration<CMLibrary> e=CMLib.libraries(CMLib.Library.STATS);e.hasMoreElements();) ((StatisticsLibrary)e.nextElement()).update(); if(S!=null) S.println(CMLib.lang().L("done")); Log.sysOut(Thread.currentThread().getName(),"Stats saved."); CMProps.setUpAllLowVar(CMProps.Str.MUDSTATUS,"Shutting down" + (keepItDown? "..." : " and restarting...")); Log.sysOut(Thread.currentThread().getName(),"Notifying all objects of shutdown..."); if(S!=null) S.print(CMLib.lang().L("Notifying all objects of shutdown...")); CMProps.setUpAllLowVar(CMProps.Str.MUDSTATUS,"Shutting down...Notifying Objects"); MOB mob=null; if(S!=null) mob=S.mob(); if(mob==null) mob=CMClass.getMOB("StdMOB"); final CMMsg msg=CMClass.getMsg(mob,null,CMMsg.MSG_SHUTDOWN,null); final Vector<Room> roomSet=new Vector<Room>(); try { for(final Enumeration<CMLibrary> e=CMLib.libraries(CMLib.Library.MAP);e.hasMoreElements();) { final WorldMap map=((WorldMap)e.nextElement()); for(final Enumeration<Area> a=map.areas();a.hasMoreElements();) a.nextElement().setAreaState(Area.State.STOPPED); } for(final Enumeration<CMLibrary> e=CMLib.libraries(CMLib.Library.MAP);e.hasMoreElements();) { final WorldMap map=((WorldMap)e.nextElement()); for(final Enumeration<Room> r=map.rooms();r.hasMoreElements();) { final Room R=r.nextElement(); R.send(mob,msg); roomSet.addElement(R); } } }catch(final NoSuchElementException e){} if(S!=null) S.println(CMLib.lang().L("done")); final CMLib.Library[][] libraryShutdownLists={ {CMLib.Library.QUEST,CMLib.Library.TECH,CMLib.Library.SESSIONS}, {CMLib.Library.STATS,CMLib.Library.THREADS}, {CMLib.Library.SOCIALS,CMLib.Library.CLANS,CMLib.Library.CHANNELS,CMLib.Library.JOURNALS, CMLib.Library.POLLS,CMLib.Library.HELP,CMLib.Library.CATALOG,CMLib.Library.MAP, CMLib.Library.PLAYERS } }; for(final CMLib.Library lib : libraryShutdownLists[0]) { CMProps.setUpAllLowVar(CMProps.Str.MUDSTATUS,"Shutting down "+CMStrings.capitalizeAndLower(lib.name())+"..."); for(final Enumeration<CMLibrary> e=CMLib.libraries(lib);e.hasMoreElements();) { try { e.nextElement().shutdown(); } catch(Throwable t) { Log.errOut(t); } } } if(S!=null) S.println(CMLib.lang().L("Save thread stopped")); if(CMSecurity.isSaveFlag("ROOMMOBS") ||CMSecurity.isSaveFlag("ROOMITEMS") ||CMSecurity.isSaveFlag("ROOMSHOPS")) { if(S!=null) S.print(CMLib.lang().L("Saving room data...")); CMProps.setUpAllLowVar(CMProps.Str.MUDSTATUS,"Shutting down...Rejuving the dead"); serviceEngine.tickAllTickers(null); CMProps.setUpAllLowVar(CMProps.Str.MUDSTATUS,"Shutting down...Map Update"); for(final Enumeration<CMLibrary> e=CMLib.libraries(CMLib.Library.MAP);e.hasMoreElements();) { final WorldMap map=((WorldMap)e.nextElement()); for(final Enumeration<Area> a=map.areas();a.hasMoreElements();) a.nextElement().setAreaState(Area.State.STOPPED); } int roomCounter=0; Room R=null; for(final Enumeration<Room> e=roomSet.elements();e.hasMoreElements();) { if(((++roomCounter)%200)==0) { if(S!=null) S.print("."); CMProps.setUpAllLowVar(CMProps.Str.MUDSTATUS,"Shutting down...Map Update ("+roomCounter+")"); } R=e.nextElement(); if(R.roomID().length()>0) R.executeMsg(mob,CMClass.getMsg(mob,R,null,CMMsg.MSG_EXPIRE,null)); } if(S!=null) S.println(CMLib.lang().L("done")); Log.sysOut(Thread.currentThread().getName(),"Map data saved."); } CMProps.setUpAllLowVar(CMProps.Str.MUDSTATUS,"Shutting down...CM1Servers"); for(final CM1Server cm1server : cm1Servers) { try { cm1server.shutdown(); } finally { if(S!=null) S.println(CMLib.lang().L("@x1 stopped",cm1server.getName())); Log.sysOut(Thread.currentThread().getName(),cm1server.getName()+" stopped"); } } cm1Servers.clear(); if(i3server!=null) { CMProps.setUpAllLowVar(CMProps.Str.MUDSTATUS,"Shutting down...I3Server"); I3Server.shutdown(); i3server=null; if(S!=null) S.println(CMLib.lang().L("I3Server stopped")); Log.sysOut(Thread.currentThread().getName(),"I3Server stopped"); } if(imc2server!=null) { CMProps.setUpAllLowVar(CMProps.Str.MUDSTATUS,"Shutting down...IMC2Server"); imc2server.shutdown(); imc2server=null; if(S!=null) S.println(CMLib.lang().L("IMC2Server stopped")); Log.sysOut(Thread.currentThread().getName(),"IMC2Server stopped"); } if(S!=null) S.print(CMLib.lang().L("Stopping player Sessions...")); CMProps.setUpAllLowVar(CMProps.Str.MUDSTATUS,"Shutting down...Stopping sessions"); for(final Enumeration<CMLibrary> e=CMLib.libraries(CMLib.Library.SESSIONS);e.hasMoreElements();) { final SessionsList list=((SessionsList)e.nextElement()); for(final Session S2 : list.allIterable()) { if((S!=null)&&(S2==S)) list.remove(S2); else { CMProps.setUpAllLowVar(CMProps.Str.MUDSTATUS,"Shutting down...Stopping session "+S2.getAddress()); S2.stopSession(true,true,true); CMProps.setUpAllLowVar(CMProps.Str.MUDSTATUS,"Shutting down...Done stopping session "+S2.getAddress()); } if(S!=null) S.print("."); } } if(S!=null) S.println(CMLib.lang().L("All users logged off")); try{Thread.sleep(3000);}catch(final Exception e){/* give sessions a few seconds to inform the map */} Log.sysOut(Thread.currentThread().getName(),"All users logged off."); if(smtpServerThread!=null) { CMProps.setUpAllLowVar(CMProps.Str.MUDSTATUS,"Shutting down...smtp server"); smtpServerThread.shutdown(); smtpServerThread = null; Log.sysOut(Thread.currentThread().getName(),"SMTP Server stopped."); if(S!=null) S.println(CMLib.lang().L("SMTP Server stopped")); } if(S!=null) S.print(CMLib.lang().L("Stopping all threads...")); for(final CMLib.Library lib : libraryShutdownLists[1]) { CMProps.setUpAllLowVar(CMProps.Str.MUDSTATUS,"Shutting down "+CMStrings.capitalizeAndLower(lib.name())+"..."); for(final Enumeration<CMLibrary> e=CMLib.libraries(lib);e.hasMoreElements();) e.nextElement().shutdown(); } if(S!=null) S.println(CMLib.lang().L("done")); Log.sysOut(Thread.currentThread().getName(),"Map Threads Stopped."); CMProps.setUpAllLowVar(CMProps.Str.MUDSTATUS,"Shutting down services..."); for(final CMLib.Library lib : libraryShutdownLists[2]) { CMProps.setUpAllLowVar(CMProps.Str.MUDSTATUS,"Shutting down "+CMStrings.capitalizeAndLower(lib.name())+"..."); for(final Enumeration<CMLibrary> e=CMLib.libraries(lib);e.hasMoreElements();) e.nextElement().shutdown(); } for(final CMLib.Library lib : CMLib.Library.values()) { boolean found=false; for(final CMLib.Library[] prevSet : libraryShutdownLists) found=found||CMParms.contains(prevSet, lib); if(!found) { CMProps.setUpAllLowVar(CMProps.Str.MUDSTATUS,"Shutting down "+CMStrings.capitalizeAndLower(lib.name())+"..."); for(final Enumeration<CMLibrary> e=CMLib.libraries(lib);e.hasMoreElements();) e.nextElement().shutdown(); } } CMProps.setUpAllLowVar(CMProps.Str.MUDSTATUS,"Shutting down...unloading resources"); Resources.shutdown(); Log.sysOut(Thread.currentThread().getName(),"Resources Cleared."); if(S!=null) S.println(CMLib.lang().L("All resources unloaded")); CMProps.setUpAllLowVar(CMProps.Str.MUDSTATUS,"Shutting down...closing db connections"); for(int d=0;d<databases.size();d++) databases.get(d).killConnections(); if(S!=null) S.println(CMLib.lang().L("Database connections closed")); Log.sysOut(Thread.currentThread().getName(),"Database connections closed."); for(int i=0;i<webServers.size();i++) { final WebServer webServerThread=webServers.get(i); CMProps.setUpAllLowVar(CMProps.Str.MUDSTATUS,"Shutting down web server "+webServerThread.getName()+"..."); webServerThread.close(); Log.sysOut(Thread.currentThread().getName(),"Web server "+webServerThread.getName()+" stopped."); if(S!=null) S.println(CMLib.lang().L("Web server @x1 stopped",webServerThread.getName())); } webServers.clear(); CMProps.setUpAllLowVar(CMProps.Str.MUDSTATUS,"Shutting down...unloading macros"); CMLib.lang().clear(); CMProps.setUpAllLowVar(CMProps.Str.MUDSTATUS,"Shutting down...unloading classes"); CMClass.shutdown(); CMProps.setUpAllLowVar(CMProps.Str.MUDSTATUS,"Shutting down" + (keepItDown? "..." : " and restarting...")); try{Thread.sleep(500);}catch(final Exception i){} Log.sysOut(Thread.currentThread().getName(),"CoffeeMud shutdown complete."); if(S!=null) S.println(CMLib.lang().L("CoffeeMud shutdown complete.")); bringDown=keepItDown; serviceEngine.resumeAll(); if(!keepItDown) if(S!=null) S.println(CMLib.lang().L("Restarting...")); if(S!=null) S.stopSession(true,true,false); try{Thread.sleep(500);}catch(final Exception i){} System.gc(); System.runFinalization(); try{Thread.sleep(500);}catch(final Exception i){} execExternalCommand=externalCommand; CMProps.setUpAllLowVar(CMProps.Str.MUDSTATUS,"Shutdown: you are the special lucky chosen one!"); for(int m=CMLib.hosts().size()-1;m>=0;m--) if(CMLib.hosts().get(m) instanceof Thread) { try { CMLib.killThread((Thread)CMLib.hosts().get(m),100,30); } catch(final Exception t){} } CMLib.hosts().clear(); if(!keepItDown) CMProps.setBoolAllVar(CMProps.Bool.MUDSHUTTINGDOWN,false); } private static void startIntermud3() { final char tCode=Thread.currentThread().getThreadGroup().getName().charAt(0); final CMProps page=CMProps.instance(); try { if(page.getBoolean("RUNI3SERVER")&&(tCode==MAIN_HOST)&&(!CMSecurity.isDisabled(CMSecurity.DisFlag.I3))) { if(i3server!=null) I3Server.shutdown(); i3server=null; String playstate=page.getStr("MUDSTATE"); if((playstate==null)||(playstate.length()==0)) playstate=page.getStr("I3STATE"); if((playstate==null)||(!CMath.isInteger(playstate))) playstate="Development"; else switch(CMath.s_int(playstate.trim())) { case 0: playstate = "MudLib Development"; break; case 1: playstate = "Restricted Access"; break; case 2: playstate = "Beta Testing"; break; case 3: playstate = "Open to the public"; break; default: playstate = "MudLib Development"; break; } final IMudInterface imud=new IMudInterface(CMProps.getVar(CMProps.Str.MUDNAME), "CoffeeMud v"+CMProps.getVar(CMProps.Str.MUDVER), CMLib.mud(0).getPort(), playstate, CMLib.channels().getI3ChannelsList()); i3server=new I3Server(); int i3port=page.getInt("I3PORT"); if(i3port==0) i3port=27766; I3Server.start(CMProps.getVar(CMProps.Str.MUDNAME),i3port,imud); } } catch(final Exception e) { if(i3server!=null) I3Server.shutdown(); i3server=null; } } private static void startCM1() { final char tCode=Thread.currentThread().getThreadGroup().getName().charAt(0); final CMProps page=CMProps.instance(); CM1Server cm1server = null; try { final String runcm1=page.getPrivateStr("RUNCM1SERVER"); if((runcm1!=null)&&(runcm1.equalsIgnoreCase("TRUE"))) { final String iniFile = page.getStr("CM1CONFIG"); for(final CM1Server s : cm1Servers) if(s.getINIFilename().equalsIgnoreCase(iniFile)) { s.shutdown(); cm1Servers.remove(s); } cm1server=new CM1Server("CM1Server"+tCode,iniFile); cm1server.start(); cm1Servers.add(cm1server); } } catch(final Exception e) { if(cm1server!=null) { cm1server.shutdown(); cm1Servers.remove(cm1server); } } } private static void startIntermud2() { final char tCode=Thread.currentThread().getThreadGroup().getName().charAt(0); final CMProps page=CMProps.instance(); try { if(page.getBoolean("RUNIMC2CLIENT")&&(tCode==MAIN_HOST)&&(!CMSecurity.isDisabled(CMSecurity.DisFlag.IMC2))) { imc2server=new IMC2Driver(); if(!imc2server.imc_startup(false, page.getStr("IMC2LOGIN").trim(), CMProps.getVar(CMProps.Str.MUDNAME), page.getStr("IMC2MYEMAIL").trim(), page.getStr("IMC2MYWEB").trim(), page.getStr("IMC2HUBNAME").trim(), page.getInt("IMC2HUBPORT"), page.getStr("IMC2PASS1").trim(), page.getStr("IMC2PASS2").trim(), CMLib.channels().getIMC2ChannelsList())) { Log.errOut(Thread.currentThread().getName(),"IMC2 Failed to start!"); imc2server=null; } else { CMLib.intermud().registerIMC2(imc2server); imc2server.start(); } } } catch(final Exception e) { Log.errOut(e); } } @Override public void interrupt() { if(servsock!=null) { try { servsock.close(); servsock = null; } catch(final IOException e) { } } super.interrupt(); } public static int activeThreadCount(ThreadGroup tGroup, boolean nonDaemonsOnly) { int realAC=0; final int ac = tGroup.activeCount(); final Thread tArray[] = new Thread [ac+1]; tGroup.enumerate(tArray); for (int i = 0; i<ac; ++i) { if (tArray[i] != null && tArray[i].isAlive() && (tArray[i] != Thread.currentThread()) && ((!nonDaemonsOnly)||(!tArray[i].isDaemon()))) realAC++; } return realAC; } private static int killCount(ThreadGroup tGroup, boolean nonDaemonsOnly) { int killed=0; final int ac = tGroup.activeCount(); final Thread tArray[] = new Thread [ac+1]; tGroup.enumerate(tArray); for (int i = 0; i<ac; ++i) { if (tArray[i] != null && tArray[i].isAlive() && (tArray[i] != Thread.currentThread()) && ((!nonDaemonsOnly)||(!tArray[i].isDaemon()))) { CMLib.killThread(tArray[i],500,10); killed++; } } return killed; } private static void threadList(ThreadGroup tGroup, boolean nonDaemonsOnly) { if(tGroup==null) return; final int ac = tGroup.activeCount(); final Thread tArray[] = new Thread [ac+1]; tGroup.enumerate(tArray); for (int i = 0; i<ac; ++i) { if (tArray[i] != null && tArray[i].isAlive() && (tArray[i] != Thread.currentThread()) && ((!nonDaemonsOnly)||(!tArray[i].isDaemon()))) { String summary; if(tArray[i] instanceof MudHost) summary=": "+CMClass.classID(tArray[i])+": "+((MudHost)tArray[i]).getStatus(); else { final Runnable R=serviceEngine.findRunnableByThread(tArray[i]); if(R instanceof TickableGroup) summary=": "+((TickableGroup)R).getName()+": "+((TickableGroup)R).getStatus(); else if(R instanceof Session) { final Session S=(Session)R; final MOB mob=S.mob(); final String mobName=(mob==null)?"null":mob.Name(); summary=": session "+mobName+": "+S.getStatus().toString()+": "+CMParms.combineQuoted(S.getPreviousCMD(),0); } else if(R instanceof CMRunnable) summary=": "+CMClass.classID(R)+": active for "+((CMRunnable)R).activeTimeMillis()+"ms"; else if(CMClass.classID(R).length()>0) summary=": "+CMClass.classID(R); else summary=""; } Log.sysOut(Thread.currentThread().getName(), "-->Thread: "+tArray[i].getName() + summary+"\n\r"); } } } @Override public String getHost() { return host; } @Override public int getPort() { return port; } private static class HostGroup extends Thread { private String name=null; private String iniFile=null; private String logName=null; private char threadCode=MAIN_HOST; private boolean hostStarted=false; private boolean failedStart=false; //protected ThreadGroup threadGroup; public HostGroup(ThreadGroup G, String mudName, String iniFileName) { super(G,"HOST"+grpid); //threadGroup=G; synchronized("HostGroupInit".intern()) { logName="mud"+((grpid>0)?("."+grpid):""); grpid++; iniFile=iniFileName; name=mudName; setDaemon(true); threadCode=G.getName().charAt(0); } } public boolean isStarted() { return hostStarted; } public boolean failedToStart() { return failedStart; } public void fatalStartupError(Thread t, int type) { String errorInternal=null; switch(type) { case 1: errorInternal="ERROR: initHost() will not run without properties. Exiting."; break; case 2: errorInternal="Map is empty?! Exiting."; break; case 3: errorInternal="Database init failed. Exiting."; break; case 4: errorInternal="Fatal exception. Exiting."; break; case 5: errorInternal="MUD Server did not start. Exiting."; break; default: errorInternal="Fatal error loading classes. Make sure you start up coffeemud from the directory containing the class files."; break; } Log.errOut(Thread.currentThread().getName(),errorInternal); bringDown=true; CMProps.setBoolAllVar(CMProps.Bool.MUDSHUTTINGDOWN,true); //CMLib.killThread(t,100,1); } protected boolean initHost() { final Thread t=Thread.currentThread(); final CMProps page=CMProps.instance(); if ((page == null) || (!page.isLoaded())) { fatalStartupError(t,1); return false; } final char tCode=Thread.currentThread().getThreadGroup().getName().charAt(0); final boolean checkPrivate=(tCode!=MAIN_HOST); final List<String> compress=CMParms.parseCommas(page.getStr("COMPRESS").toUpperCase(),true); CMProps.setBoolVar(CMProps.Bool.ITEMDCOMPRESS,compress.contains("ITEMDESC")); CMProps.setBoolVar(CMProps.Bool.MOBCOMPRESS,compress.contains("GENMOBS")); CMProps.setBoolVar(CMProps.Bool.ROOMDCOMPRESS,compress.contains("ROOMDESC")); CMProps.setBoolVar(CMProps.Bool.MOBDCOMPRESS,compress.contains("MOBDESC")); Resources.setCompression(compress.contains("RESOURCES")); final List<String> nocache=CMParms.parseCommas(page.getStr("NOCACHE").toUpperCase(),true); CMProps.setBoolVar(CMProps.Bool.MOBNOCACHE,nocache.contains("GENMOBS")); CMProps.setBoolVar(CMProps.Bool.ROOMDNOCACHE,nocache.contains("ROOMDESC")); CMProps.setBoolVar(CMProps.Bool.FILERESOURCENOCACHE, nocache.contains("FILERESOURCES")); CMProps.setBoolVar(CMProps.Bool.CATALOGNOCACHE, nocache.contains("CATALOG")); CMProps.setBoolVar(CMProps.Bool.MAPFINDSNOCACHE,nocache.contains("MAPFINDERS")); CMProps.setBoolVar(CMProps.Bool.ACCOUNTSNOCACHE,nocache.contains("ACCOUNTS")); CMProps.setBoolVar(CMProps.Bool.PLAYERSNOCACHE,nocache.contains("PLAYERS")); DBConnector currentDBconnector=null; String dbClass=page.getStr("DBCLASS"); if(tCode!=MAIN_HOST) { DatabaseEngine baseEngine=(DatabaseEngine)CMLib.library(MAIN_HOST,CMLib.Library.DATABASE); while((!MUD.bringDown) &&((baseEngine==null)||(!baseEngine.isConnected()))) { try {Thread.sleep(500);}catch(final Exception e){ break;} baseEngine=(DatabaseEngine)CMLib.library(MAIN_HOST,CMLib.Library.DATABASE); } if(MUD.bringDown) return false; if(page.getPrivateStr("DBCLASS").length()==0) { CMLib.registerLibrary(baseEngine); dbClass=""; } } if(dbClass.length()>0) { final String dbService=page.getStr("DBSERVICE"); final String dbUser=page.getStr("DBUSER"); final String dbPass=page.getStr("DBPASS"); final int dbConns=page.getInt("DBCONNECTIONS"); final int dbPingIntMins=page.getInt("DBPINGINTERVALMINS"); if(dbConns == 0) { Log.errOut(Thread.currentThread().getName(),"Fatal error: DBCONNECTIONS in INI file is "+dbConns); System.exit(-1); } final boolean dbReuse=page.getBoolean("DBREUSE"); final boolean useQue=!CMSecurity.isDisabled(CMSecurity.DisFlag.DBERRORQUE); final boolean useQueStart=!CMSecurity.isDisabled(CMSecurity.DisFlag.DBERRORQUESTART); CMProps.setUpLowVar(CMProps.Str.MUDSTATUS,"Booting: connecting to database"); currentDBconnector=new DBConnector(dbClass,dbService,dbUser,dbPass,dbConns,dbPingIntMins,dbReuse,useQue,useQueStart); currentDBconnector.reconnect(); CMLib.registerLibrary(new DBInterface(currentDBconnector,CMProps.getPrivateSubSet("DB.*"))); final DBConnection DBTEST=currentDBconnector.DBFetch(); if(DBTEST!=null) currentDBconnector.DBDone(DBTEST); if((DBTEST!=null)&&(currentDBconnector.amIOk())&&(CMLib.database().isConnected())) { Log.sysOut(Thread.currentThread().getName(),"Connected to "+currentDBconnector.service()); databases.add(currentDBconnector); } else { final String DBerrors=currentDBconnector.errorStatus().toString(); Log.errOut(Thread.currentThread().getName(),"Fatal database error: "+DBerrors); return false; } } else if(CMLib.database()==null) { Log.errOut(Thread.currentThread().getName(),"No registered database!"); return false; } // test the database try { final CMFile F = new CMFile("/test.the.database",null); if(F.exists()) Log.sysOut(Thread.currentThread().getName(),"Test file found .. hmm.. that was unexpected."); } catch(final Exception e) { Log.errOut(e); Log.errOut("Database error! Panic shutdown!"); return false; } String webServersList=page.getPrivateStr("RUNWEBSERVERS"); if(webServersList.equalsIgnoreCase("true")) webServersList="pub,admin"; if((webServersList.length()>0)&&(!webServersList.equalsIgnoreCase("false"))) { final List<String> serverNames=CMParms.parseCommas(webServersList,true); for(int s=0;s<serverNames.size();s++) { final String serverName=serverNames.get(s); try { final StringBuffer commonProps=new CMFile("web/common.ini", null, CMFile.FLAG_LOGERRORS).text(); final StringBuffer finalProps=new CMFile("web/"+serverName+".ini", null, CMFile.FLAG_LOGERRORS).text(); commonProps.append("\n").append(finalProps.toString()); final CWConfig config=new CWConfig(); config.setFileManager(new CMFile.CMFileManager()); WebServer.initConfig(config, Log.instance(), new ByteArrayInputStream(commonProps.toString().getBytes())); if(CMSecurity.isDebugging(DbgFlag.HTTPREQ)) config.setDebugFlag(page.getStr("DBGMSGS")); if(CMSecurity.isDebugging(DbgFlag.HTTPACCESS)) config.setAccessLogFlag(page.getStr("ACCMSGS")); final WebServer webServer=new WebServer(serverName+Thread.currentThread().getThreadGroup().getName().charAt(0),config); config.setCoffeeWebServer(webServer); webServer.start(); webServers.add(webServer); } catch(final Exception e) { Log.errOut("HTTP server "+serverName+"NOT started: "+e.getMessage()); } } } if(page.getPrivateStr("RUNSMTPSERVER").equalsIgnoreCase("true")) { smtpServerThread = new SMTPserver(CMLib.mud(0)); smtpServerThread.start(); serviceEngine.startTickDown(Thread.currentThread().getThreadGroup(),smtpServerThread,Tickable.TICKID_EMAIL,CMProps.getTickMillis(),(int)CMProps.getTicksPerMinute() * 5); } CMProps.setUpLowVar(CMProps.Str.MUDSTATUS,"Booting: loading base classes"); if(!CMClass.loadAllCoffeeMudClasses(page)) { fatalStartupError(t,0); return false; } CMLib.lang().setLocale(CMLib.props().getStr("LANGUAGE"),CMLib.props().getStr("COUNTRY")); if((threadCode==MudHost.MAIN_HOST)||(CMLib.time()!=CMLib.library(MudHost.MAIN_HOST, CMLib.Library.TIME))) CMLib.time().globalClock().initializeINIClock(page); if((tCode==MAIN_HOST)||(checkPrivate&&CMProps.isPrivateToMe("FACTIONS"))) CMLib.factions().reloadFactions(CMProps.getVar(CMProps.Str.PREFACTIONS)); if((tCode==MAIN_HOST)||(checkPrivate&&CMProps.isPrivateToMe("CHANNELS"))||(checkPrivate&&CMProps.isPrivateToMe("JOURNALS"))) { int numChannelsLoaded=0; int numJournalsLoaded=0; if((tCode==MAIN_HOST)||(checkPrivate&&CMProps.isPrivateToMe("CHANNELS"))) numChannelsLoaded=CMLib.channels().loadChannels(page.getStr("CHANNELS"), page.getStr("ICHANNELS"), page.getStr("IMC2CHANNELS")); if((tCode==MAIN_HOST)||(checkPrivate&&CMProps.isPrivateToMe("JOURNALS"))) { numJournalsLoaded=CMLib.journals().loadCommandJournals(page.getStr("COMMANDJOURNALS")); numJournalsLoaded+=CMLib.journals().loadForumJournals(page.getStr("FORUMJOURNALS")); } Log.sysOut(Thread.currentThread().getName(),"Channels loaded : "+(numChannelsLoaded+numJournalsLoaded)); } if((tCode==MAIN_HOST)||(page.getRawPrivateStr("SYSOPMASK")!=null)) // needs to be after journals, for journal flags { CMSecurity.setSysOp(page.getStr("SYSOPMASK")); // requires all classes be loaded CMSecurity.parseGroups(page); } if((tCode==MAIN_HOST)||(checkPrivate&&CMProps.isPrivateToMe("SOCIALS"))) { CMProps.setUpLowVar(CMProps.Str.MUDSTATUS,"Booting: loading socials"); CMLib.socials().unloadSocials(); if(CMLib.socials().numSocialSets()==0) Log.errOut(Thread.currentThread().getName(),"WARNING: Unable to load socials from socials.txt!"); else Log.sysOut(Thread.currentThread().getName(),"Socials loaded : "+CMLib.socials().numSocialSets()); } if((tCode==MAIN_HOST)||(checkPrivate&&CMProps.isPrivateToMe("CLANS"))) { CMLib.database().DBReadAllClans(); Log.sysOut(Thread.currentThread().getName(),"Clans loaded : "+CMLib.clans().numClans()); } if((tCode==MAIN_HOST)||(checkPrivate&&CMProps.isPrivateToMe("FACTIONS"))) serviceEngine.startTickDown(Thread.currentThread().getThreadGroup(),CMLib.factions(),Tickable.TICKID_MOB,CMProps.getTickMillis(),10); CMProps.setUpLowVar(CMProps.Str.MUDSTATUS,"Booting: Starting CM1"); startCM1(); CMProps.setUpLowVar(CMProps.Str.MUDSTATUS,"Booting: Starting I3"); startIntermud3(); CMProps.setUpLowVar(CMProps.Str.MUDSTATUS,"Booting: Starting IMC2"); startIntermud2(); try{Thread.sleep(500);}catch(final Exception e){} if((tCode==MAIN_HOST)||(checkPrivate&&CMProps.isPrivateToMe("CATALOG"))) { Log.sysOut(Thread.currentThread().getName(),"Loading catalog..."); CMProps.setUpLowVar(CMProps.Str.MUDSTATUS,"Booting: loading catalog...."); CMLib.database().DBReadCatalogs(); } if((tCode==MAIN_HOST)||(checkPrivate&&CMProps.isPrivateToMe("MAP"))) { Log.sysOut(Thread.currentThread().getName(),"Loading map..."); CMProps.setUpLowVar(CMProps.Str.MUDSTATUS,"Booting: loading rooms...."); CMLib.database().DBReadAllRooms(null); CMProps.setUpLowVar(CMProps.Str.MUDSTATUS,"Booting: loading space...."); CMLib.database().DBReadSpace(); CMProps.setUpLowVar(CMProps.Str.MUDSTATUS,"Booting: preparing map...."); Log.sysOut(Thread.currentThread().getName(),"Preparing map..."); CMLib.database().DBReadArtifacts(); for(final Enumeration<Area> a=CMLib.map().areas();a.hasMoreElements();) { final Area A=a.nextElement(); CMProps.setUpLowVar(CMProps.Str.MUDSTATUS,"Booting: filling map ("+A.Name()+")"); A.fillInAreaRooms(); } Log.sysOut(Thread.currentThread().getName(),"Mapped rooms : "+CMLib.map().numRooms()+" in "+CMLib.map().numAreas()+" areas"); if(CMLib.map().numSpaceObjects()>0) Log.sysOut(Thread.currentThread().getName(),"Space objects : "+CMLib.map().numSpaceObjects()); if(!CMLib.map().roomIDs().hasMoreElements()) { Log.sysOut("NO MAPPED ROOM?! I'll make ya one!"); final String id="START";//New Area#0"; final Area newArea=CMClass.getAreaType("StdArea"); newArea.setName(CMLib.lang().L("New Area")); CMLib.map().addArea(newArea); CMLib.database().DBCreateArea(newArea); final Room room=CMClass.getLocale("StdRoom"); room.setRoomID(id); room.setArea(newArea); room.setDisplayText(CMLib.lang().L("New Room")); room.setDescription(CMLib.lang().L("Brand new database room! You need to change this text with the MODIFY ROOM command. If your character is not an Archon, pick up the book you see here and read it immediately!")); CMLib.database().DBCreateRoom(room); final Item I=CMClass.getMiscMagic("ManualArchon"); room.addItem(I); CMLib.database().DBUpdateItems(room); } CMLib.login().initStartRooms(page); CMLib.login().initDeathRooms(page); CMLib.login().initBodyRooms(page); } if((tCode==MAIN_HOST)||(checkPrivate&&CMProps.isPrivateToMe("QUESTS"))) { CMLib.database().DBReadQuests(CMLib.mud(0)); if(CMLib.quests().numQuests()>0) Log.sysOut(Thread.currentThread().getName(),"Quests loaded : "+CMLib.quests().numQuests()); } if(tCode!=MAIN_HOST) { CMProps.setUpLowVar(CMProps.Str.MUDSTATUS,"Booting: Waiting for HOST0"); while((!MUD.bringDown) &&(!CMProps.getBoolVar(CMProps.Bool.MUDSTARTED)) &&(!CMProps.getBoolVar(CMProps.Bool.MUDSHUTTINGDOWN))) try{Thread.sleep(500);}catch(final Exception e){ break;} if((MUD.bringDown) ||(!CMProps.getBoolVar(CMProps.Bool.MUDSTARTED)) ||(CMProps.getBoolVar(CMProps.Bool.MUDSHUTTINGDOWN))) return false; } CMProps.setUpLowVar(CMProps.Str.MUDSTATUS,"Booting: readying for connections."); try { CMLib.activateLibraries(); Log.sysOut(Thread.currentThread().getName(),"Services and utilities started"); } catch (final Throwable th) { Log.errOut(Thread.currentThread().getName(),"CoffeeMud Server initHost() failed"); Log.errOut(Thread.currentThread().getName(),th); fatalStartupError(t,4); return false; } final StringBuffer str=new StringBuffer(""); for(int m=0;m<CMLib.hosts().size();m++) { final MudHost mud=CMLib.hosts().get(m); str.append(" "+mud.getPort()); } CMProps.setVar(CMProps.Str.MUDPORTS,str.toString()); CMProps.setBoolAllVar(CMProps.Bool.MUDSTARTED,true); CMProps.setUpLowVar(CMProps.Str.MUDSTATUS,"OK"); Log.sysOut(Thread.currentThread().getName(),"Host#"+threadCode+" initializated."); return true; } @Override public void run() { CMLib.initialize(); // initialize the lib CMClass.initialize(); // initialize the classes Log.shareWith(MudHost.MAIN_HOST); Resources.shareWith(MudHost.MAIN_HOST); // wait for ini to be loaded, and for other matters if(threadCode!=MAIN_HOST) { while((CMLib.library(MAIN_HOST,CMLib.Library.INTERMUD)==null)&&(!MUD.bringDown)) { try {Thread.sleep(500);}catch(final Exception e){ break;} } if(MUD.bringDown) return; } final CMProps page=CMProps.loadPropPage("//"+iniFile); if ((page==null)||(!page.isLoaded())) { Log.errOut(Thread.currentThread().getName(),"ERROR: Unable to read ini file: '"+iniFile+"'."); System.out.println("MUD/ERROR: Unable to read ini file: '"+iniFile+"'."); CMProps.setUpLowVar(CMProps.Str.MUDSTATUS,"A terminal error has occured!"); return; } page.resetSystemVars(); CMProps.setBoolAllVar(CMProps.Bool.MUDSTARTED,false); serviceEngine.activate(); if(threadCode!=MAIN_HOST) { if(CMath.isInteger(page.getPrivateStr("NUMLOGS"))) { Log.newInstance(); Log.instance().configureLogFile(logName,page.getInt("NUMLOGS")); Log.instance().configureLog(Log.Type.info, page.getStr("SYSMSGS")); Log.instance().configureLog(Log.Type.error, page.getStr("ERRMSGS")); Log.instance().configureLog(Log.Type.warning, page.getStr("WRNMSGS")); Log.instance().configureLog(Log.Type.debug, page.getStr("DBGMSGS")); Log.instance().configureLog(Log.Type.help, page.getStr("HLPMSGS")); Log.instance().configureLog(Log.Type.kills, page.getStr("KILMSGS")); Log.instance().configureLog(Log.Type.combat, page.getStr("CBTMSGS")); Log.instance().configureLog(Log.Type.access, page.getStr("ACCMSGS")); } if(page.getRawPrivateStr("SYSOPMASK")!=null) page.resetSecurityVars(); else CMSecurity.instance().markShared(); } if(page.getStr("DISABLE").trim().length()>0) Log.sysOut(Thread.currentThread().getName(),"Disabled subsystems: "+page.getStr("DISABLE")); if(page.getStr("DEBUG").trim().length()>0) { Log.sysOut(Thread.currentThread().getName(),"Debugging messages: "+page.getStr("DEBUG")); if(!Log.debugChannelOn()) Log.errOut(Thread.currentThread().getName(),"Debug logging is disabled! Check your DBGMSGS flag!"); } final DBConnector currentDBconnector=new DBConnector(); CMLib.registerLibrary(new DBInterface(currentDBconnector,CMProps.getPrivateSubSet("DB.*"))); CMProps.setVar(CMProps.Str.MUDVER,HOST_VERSION_MAJOR + "." + HOST_VERSION_MINOR); // an arbitrary dividing line. After threadCode 0 if(threadCode==MAIN_HOST) { CMLib.registerLibrary(serviceEngine); CMLib.registerLibrary(new IMudClient()); } else { CMLib.registerLibrary(CMLib.library(MAIN_HOST,CMLib.Library.THREADS)); CMLib.registerLibrary(CMLib.library(MAIN_HOST,CMLib.Library.INTERMUD)); } CMProps.setVar(CMProps.Str.INIPATH,iniFile,false); CMProps.setUpLowVar(CMProps.Str.MUDNAME,name.replace('\'','`')); try { CMProps.setUpLowVar(CMProps.Str.MUDSTATUS,"Booting"); CMProps.setVar(CMProps.Str.MUDBINDADDRESS,page.getStr("BIND")); CMProps.setIntVar(CMProps.Int.MUDBACKLOG,page.getInt("BACKLOG")); final LinkedList<MUD> hostMuds=new LinkedList<MUD>(); String ports=page.getProperty("PORT"); int pdex=ports.indexOf(','); while(pdex>0) { final MUD mud=new MUD("MUD@"+ports.substring(0,pdex)); mud.setState(MudState.STARTING); mud.acceptConns=false; mud.port=CMath.s_int(ports.substring(0,pdex)); ports=ports.substring(pdex+1); hostMuds.add(mud); mud.start(); pdex=ports.indexOf(','); } final MUD mud=new MUD("MUD@"+ports); mud.setState(MudState.STARTING); mud.acceptConns=false; mud.port=CMath.s_int(ports); hostMuds.add(mud); mud.start(); if(hostMuds.size()==0) { Log.errOut("HOST#"+this.threadCode+" could not start any listeners."); return; } boolean oneStarted=false; final long timeout=System.currentTimeMillis()+60000; while((!oneStarted) && (System.currentTimeMillis()<timeout)) { int numStopped=0; for(final MUD m : hostMuds) if(m.state==MudState.STOPPED) numStopped++; else if(m.state!=MudState.STARTING) oneStarted=true; if(numStopped==hostMuds.size()) { Log.errOut("HOST#"+this.threadCode+" could not start any listeners."); failedStart=true; return; } try { Thread.sleep(100); }catch(final Exception e){} } if(!oneStarted) { Log.errOut("HOST#"+this.threadCode+" could not start any listeners."); failedStart=true; return; } if(initHost()) { Thread joinable=null; for(int i=0;i<CMLib.hosts().size();i++) if(CMLib.hosts().get(i) instanceof Thread) { joinable=(Thread)CMLib.hosts().get(i); break; } if(joinable!=null) { hostStarted=true; joinable.join(); } else failedStart=true; } else { failedStart=true; } } catch(final InterruptedException e) { Log.errOut(Thread.currentThread().getName(),e); } } } @Override public List<Runnable> getOverdueThreads() { final Vector<Runnable> V=new Vector<Runnable>(); for(int w=0;w<webServers.size();w++) V.addAll(webServers.get(w).getOverdueThreads()); return V; } public static void main(String a[]) { String nameID=""; Thread.currentThread().setName(("MUD")); final Vector<String> iniFiles=new Vector<String>(); if(a.length>0) { for (final String element : a) nameID+=" "+element; nameID=nameID.trim(); final List<String> V=CMParms.cleanParameterList(nameID); for(int v=0;v<V.size();v++) { final String s=V.get(v); if(s.toUpperCase().startsWith("BOOT=")&&(s.length()>5)) { iniFiles.addElement(s.substring(5)); V.remove(v); v--; } } nameID=CMParms.combine(V,0); } CMLib.initialize(); // initialize this threads libs if(iniFiles.size()==0) iniFiles.addElement("coffeemud.ini"); if((nameID.length()==0)||(nameID.equalsIgnoreCase( "CoffeeMud" ))||nameID.equalsIgnoreCase("Your Muds Name")) { nameID="Unnamed_CoffeeMUD#"; long idNumber=new Random(System.currentTimeMillis()).nextLong(); try { idNumber=0; for(final Enumeration<NetworkInterface> e=NetworkInterface.getNetworkInterfaces();e.hasMoreElements();) { final NetworkInterface n=e.nextElement(); idNumber^=n.getDisplayName().hashCode(); try { final Method m=n.getClass().getMethod("getHardwareAddress"); final Object o=m.invoke(n); if(o instanceof byte[]) { for(int i=0;i<((byte[])o).length;i++) idNumber^=((byte[])o)[0] << (i*8); } }catch(final Exception e1){} } }catch(final Exception e1){} if(idNumber<0) idNumber=idNumber*-1; nameID=nameID+idNumber; System.err.println("*** Please give your mud a unique name in mud.bat or mudUNIX.sh!! ***"); } else if(nameID.equalsIgnoreCase( "TheRealCoffeeMudCopyright2000-2014ByBoZimmerman" )) nameID="CoffeeMud"; String iniFile=iniFiles.firstElement(); final CMProps page=CMProps.loadPropPage("//"+iniFile); if ((page==null)||(!page.isLoaded())) { Log.instance().configureLogFile("mud",1); Log.instance().configureLog(Log.Type.info, "BOTH"); Log.instance().configureLog(Log.Type.error, "BOTH"); Log.instance().configureLog(Log.Type.warning, "BOTH"); Log.instance().configureLog(Log.Type.debug, "BOTH"); Log.instance().configureLog(Log.Type.help, "BOTH"); Log.instance().configureLog(Log.Type.kills, "BOTH"); Log.instance().configureLog(Log.Type.combat, "BOTH"); Log.instance().configureLog(Log.Type.access, "BOTH"); Log.errOut(Thread.currentThread().getName(),"ERROR: Unable to read ini file: '"+iniFile+"'."); System.out.println("MUD/ERROR: Unable to read ini file: '"+iniFile+"'."); CMProps.setUpAllLowVar(CMProps.Str.MUDSTATUS,"A terminal error has occured!"); System.exit(-1); return; } Log.shareWith(MudHost.MAIN_HOST); Log.instance().configureLogFile("mud",page.getInt("NUMLOGS")); Log.instance().configureLog(Log.Type.info, page.getStr("SYSMSGS")); Log.instance().configureLog(Log.Type.error, page.getStr("ERRMSGS")); Log.instance().configureLog(Log.Type.warning, page.getStr("WRNMSGS")); Log.instance().configureLog(Log.Type.debug, page.getStr("DBGMSGS")); Log.instance().configureLog(Log.Type.help, page.getStr("HLPMSGS")); Log.instance().configureLog(Log.Type.kills, page.getStr("KILMSGS")); Log.instance().configureLog(Log.Type.combat, page.getStr("CBTMSGS")); Log.instance().configureLog(Log.Type.access, page.getStr("ACCMSGS")); final Thread shutdownHook=new Thread("ShutdownHook") { @Override public void run() { if(!CMProps.getBoolVar(CMProps.Bool.MUDSHUTTINGDOWN)) MUD.globalShutdown(null,true,null); } }; while(!bringDown) { System.out.println(); grpid=0; Log.sysOut(Thread.currentThread().getName(),"CoffeeMud v"+HOST_VERSION_MAJOR + "." + HOST_VERSION_MINOR); Log.sysOut(Thread.currentThread().getName(),"(C) 2000-2014 Bo Zimmerman"); Log.sysOut(Thread.currentThread().getName(),"http://www.coffeemud.org"); CMLib.hosts().clear(); final LinkedList<HostGroup> myGroups=new LinkedList<HostGroup>(); HostGroup mainGroup=null; for(int i=0;i<iniFiles.size();i++) { iniFile=iniFiles.elementAt(i); final ThreadGroup G=new ThreadGroup(i+"-MUD"); final HostGroup H=new HostGroup(G,nameID,iniFile); if(mainGroup==null) mainGroup=H; myGroups.add(H); H.start(); } if(mainGroup==null) { Log.errOut("CoffeeMud failed to start."); MUD.bringDown=true; CMProps.setBoolAllVar(CMProps.Bool.MUDSHUTTINGDOWN, true); } else { final long timeout=System.currentTimeMillis()+1800000; /// 30 mins int numPending=1; while((numPending>0)&&(System.currentTimeMillis()<timeout)) { numPending=0; for(final HostGroup g : myGroups) if(!g.failedToStart() && !g.isStarted()) numPending++; if(mainGroup.failedToStart()) break; try { Thread.sleep(100); } catch(final Exception e) {} } if(mainGroup.failedToStart()) { Log.errOut("CoffeeMud failed to start."); MUD.bringDown=true; CMProps.setBoolAllVar(CMProps.Bool.MUDSHUTTINGDOWN, true); } else { Runtime.getRuntime().addShutdownHook(shutdownHook); for(int i=0;i<CMLib.hosts().size();i++) CMLib.hosts().get(i).setAcceptConnections(true); Log.sysOut(Thread.currentThread().getName(),"Initialization complete."); try{mainGroup.join();}catch(final Exception e){e.printStackTrace(); Log.errOut(Thread.currentThread().getName(),e); } Runtime.getRuntime().removeShutdownHook(shutdownHook); } } System.gc(); try{Thread.sleep(1000);}catch(final Exception e){} System.runFinalization(); try{Thread.sleep(1000);}catch(final Exception e){} if(activeThreadCount(Thread.currentThread().getThreadGroup(),true)>1) { try{ Thread.sleep(1000);}catch(final Exception e){} killCount(Thread.currentThread().getThreadGroup(),true); try{ Thread.sleep(1000);}catch(final Exception e){} if(activeThreadCount(Thread.currentThread().getThreadGroup(),true)>1) { Log.sysOut(Thread.currentThread().getName(),"WARNING: " + activeThreadCount(Thread.currentThread().getThreadGroup(),true) +" other thread(s) are still active!"); threadList(Thread.currentThread().getThreadGroup(),true); } } if(!bringDown) { if(execExternalCommand!=null) { //Runtime r=Runtime.getRuntime(); //Process p=r.exec(external); Log.sysOut("Attempted to execute '"+execExternalCommand+"'."); execExternalCommand=null; bringDown=true; } } } } @Override public void setAcceptConnections(boolean truefalse) { acceptConns=truefalse; } @Override public boolean isAcceptingConnections() { return acceptConns; } @Override public long getUptimeSecs() { return (System.currentTimeMillis()-startupTime)/1000; } @Override public String executeCommand(String cmd) throws Exception { final Vector<String> V=CMParms.parse(cmd); if(V.size()==0) throw new CMException("Unknown command!"); final String word=V.firstElement(); if(word.equalsIgnoreCase("START")&&(V.size()>1)) { final String what=V.elementAt(1); if(what.equalsIgnoreCase("I3")) { startIntermud3(); return "Done"; } else if(what.equalsIgnoreCase("IMC2")) { startIntermud2(); return "Done"; } } throw new CMException("Unknown command: "+word); } }
com/planet_ink/coffee_mud/application/MUD.java
package com.planet_ink.coffee_mud.application; import com.planet_ink.coffee_mud.core.*; import com.planet_ink.coffee_mud.core.CMSecurity.DbgFlag; import com.planet_ink.coffee_mud.core.interfaces.*; import com.planet_ink.coffee_mud.core.collections.*; import com.planet_ink.coffee_mud.core.exceptions.*; import com.planet_ink.coffee_mud.Abilities.interfaces.*; import com.planet_ink.coffee_mud.Areas.interfaces.*; import com.planet_ink.coffee_mud.Behaviors.interfaces.*; import com.planet_ink.coffee_mud.CharClasses.interfaces.*; import com.planet_ink.coffee_mud.Commands.interfaces.*; import com.planet_ink.coffee_mud.Common.interfaces.*; import com.planet_ink.coffee_mud.Exits.interfaces.*; import com.planet_ink.coffee_mud.Items.interfaces.*; import com.planet_ink.coffee_mud.Locales.interfaces.*; import com.planet_ink.coffee_mud.MOBS.interfaces.*; import com.planet_ink.coffee_mud.Races.interfaces.*; import com.planet_ink.coffee_mud.Libraries.interfaces.*; import com.planet_ink.coffee_mud.core.database.DBConnector; import com.planet_ink.coffee_mud.core.database.DBConnection; import com.planet_ink.coffee_mud.core.database.DBInterface; import com.planet_ink.coffee_mud.core.threads.CMRunnable; import com.planet_ink.coffee_mud.core.threads.ServiceEngine; import com.planet_ink.coffee_mud.core.smtp.SMTPserver; import com.planet_ink.coffee_mud.core.intermud.IMudClient; import com.planet_ink.coffee_mud.core.intermud.cm1.CM1Server; import com.planet_ink.coffee_mud.core.intermud.i3.IMudInterface; import com.planet_ink.coffee_mud.core.intermud.imc2.IMC2Driver; import com.planet_ink.coffee_mud.core.intermud.i3.server.I3Server; import com.planet_ink.coffee_web.http.MIMEType; import com.planet_ink.coffee_web.interfaces.FileManager; import com.planet_ink.coffee_web.server.WebServer; import com.planet_ink.coffee_web.util.CWConfig; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.InputStream; import java.io.PrintWriter; // for writing to sockets import java.io.IOException; import java.io.RandomAccessFile; import java.lang.reflect.Method; import java.net.*; import java.util.*; import java.sql.*; /* Copyright 2000-2014 Bo Zimmerman 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. */ public class MUD extends Thread implements MudHost { private static final float HOST_VERSION_MAJOR = (float)5.8; private static final float HOST_VERSION_MINOR = (float)4.1; private static enum MudState {STARTING,WAITING,ACCEPTING,STOPPED} private volatile MudState state = MudState.STOPPED; private ServerSocket servsock = null; private boolean acceptConns= false; private final String host = "MyHost"; private int port = 5555; private final long startupTime= System.currentTimeMillis(); private final ThreadGroup threadGroup; private static volatile int grpid = 0; private static boolean bringDown = false; private static String execExternalCommand = null; private static I3Server i3server = null; private static IMC2Driver imc2server = null; private static List<WebServer> webServers = new Vector<WebServer>(); private static SMTPserver smtpServerThread = null; private static List<String> autoblocked = new Vector<String>(); private static List<DBConnector> databases = new Vector<DBConnector>(); private static List<CM1Server> cm1Servers = new Vector<CM1Server>(); private static List<Triad<String,Long,Integer>> accessed = new LinkedList<Triad<String,Long,Integer>>(); private static final ServiceEngine serviceEngine = new ServiceEngine(); public MUD(String name) { super(name); threadGroup=Thread.currentThread().getThreadGroup(); } @Override public void acceptConnection(Socket sock) throws SocketException, IOException { setState(MudState.ACCEPTING); serviceEngine.executeRunnable(threadGroup.getName(),new ConnectionAcceptor(sock)); } @Override public ThreadGroup threadGroup() { return threadGroup; } private class ConnectionAcceptor implements CMRunnable { Socket sock; long startTime=0; public ConnectionAcceptor(Socket sock) throws SocketException, IOException { this.sock=sock; sock.setSoLinger(true,3); } @Override public long getStartTime() { return startTime; } @Override public int getGroupID() { return Thread.currentThread().getThreadGroup().getName().charAt(0); } @Override public void run() { startTime=System.currentTimeMillis(); try { if (acceptConns) { String address="unknown"; try{address=sock.getInetAddress().getHostAddress().trim();}catch(final Exception e){} int proceed=0; if(CMSecurity.isBanned(address)) proceed=1; int numAtThisAddress=0; final long LastConnectionDelay=(5*60*1000); boolean anyAtThisAddress=false; final int maxAtThisAddress=6; if(!CMSecurity.isDisabled(CMSecurity.DisFlag.CONNSPAMBLOCK)) { if(!CMProps.isOnWhiteList(CMProps.SYSTEMWL_CONNS, address)) { synchronized(accessed) { for(final Iterator<Triad<String,Long,Integer>> i=accessed.iterator();i.hasNext();) { final Triad<String,Long,Integer> triad=i.next(); if((triad.second.longValue()+LastConnectionDelay)<System.currentTimeMillis()) i.remove(); else if(triad.first.trim().equalsIgnoreCase(address)) { anyAtThisAddress=true; triad.second=Long.valueOf(System.currentTimeMillis()); numAtThisAddress=triad.third.intValue()+1; triad.third=Integer.valueOf(numAtThisAddress); } } if(!anyAtThisAddress) accessed.add(new Triad<String,Long,Integer>(address,Long.valueOf(System.currentTimeMillis()),Integer.valueOf(1))); } if(autoblocked.contains(address.toUpperCase())) { if(!anyAtThisAddress) autoblocked.remove(address.toUpperCase()); else proceed=2; } else if(numAtThisAddress>=maxAtThisAddress) { autoblocked.add(address.toUpperCase()); proceed=2; } } } if(proceed!=0) { final int abusiveCount=numAtThisAddress-maxAtThisAddress+1; final long rounder=Math.round(Math.sqrt(abusiveCount)); if(abusiveCount == (rounder*rounder)) Log.sysOut(Thread.currentThread().getName(),"Blocking a connection from "+address +" ("+numAtThisAddress+")"); try { final PrintWriter out = new PrintWriter(sock.getOutputStream()); out.println("\n\rOFFLINE: Blocked\n\r"); out.flush(); if(proceed==2) out.println("\n\rYour address has been blocked temporarily due to excessive invalid connections. Please try back in " + (LastConnectionDelay/60000) + " minutes, and not before.\n\r\n\r"); else out.println("\n\rYou are unwelcome. No one likes you here. Go away.\n\r\n\r"); out.flush(); try{Thread.sleep(250);}catch(final Exception e){} out.close(); } catch(final IOException e) { // dont say anything, just eat it. } sock = null; } else { Log.sysOut(Thread.currentThread().getName(),"Connection from "+address); // also the intro page final CMFile introDir=new CMFile(Resources.makeFileResourceName("text"),null,CMFile.FLAG_FORCEALLOW); String introFilename="text/intro.txt"; if(introDir.isDirectory()) { final CMFile[] files=introDir.listFiles(); final Vector<String> choices=new Vector<String>(); for (final CMFile file : files) if(file.getName().toLowerCase().startsWith("intro") &&file.getName().toLowerCase().endsWith(".txt")) choices.addElement("text/"+file.getName()); if(choices.size()>0) introFilename=choices.elementAt(CMLib.dice().roll(1,choices.size(),-1)); } StringBuffer introText=Resources.getFileResource(introFilename,true); try { introText = CMLib.webMacroFilter().virtualPageFilter(introText);}catch(final Exception ex){} final Session S=(Session)CMClass.getCommon("DefaultSession"); S.initializeSession(sock, threadGroup().getName(), introText != null ? introText.toString() : null); CMLib.sessions().add(S); sock = null; } } else if((CMLib.database()!=null)&&(CMLib.database().isConnected())&&(CMLib.encoder()!=null)) { StringBuffer rejectText; try { rejectText = Resources.getFileResource("text/offline.txt",true); } catch(final java.lang.NullPointerException npe) { rejectText=new StringBuffer("");} try { final PrintWriter out = new PrintWriter(sock.getOutputStream()); out.println("\n\rOFFLINE: " + CMProps.getVar(CMProps.Str.MUDSTATUS)+"\n\r"); out.println(rejectText); out.flush(); try{Thread.sleep(1000);}catch(final Exception e){} out.close(); } catch(final IOException e) { // dont say anything, just eat it. } sock = null; } else { try{sock.close();}catch(final Exception e){} sock = null; } } finally { startTime=0; } } @Override public long activeTimeMillis() { return (startTime>0)?System.currentTimeMillis()-startTime:0;} } @Override public String getLanguage() { final String lang = CMProps.instance().getStr("LANGUAGE").toUpperCase().trim(); if(lang.length()==0) return "English"; for (final String[] element : LanguageLibrary.ISO_LANG_CODES) if(lang.equals(element[0])) return element[1]; return "English"; } public void setState(MudState st) { if(st!=state) state=st; } @Override public void run() { setState(MudState.STARTING); int q_len = 6; Socket sock=null; InetAddress bindAddr = null; if (CMProps.getIntVar(CMProps.Int.MUDBACKLOG) > 0) q_len = CMProps.getIntVar(CMProps.Int.MUDBACKLOG); if (CMProps.getVar(CMProps.Str.MUDBINDADDRESS).length() > 0) { try { bindAddr = InetAddress.getByName(CMProps.getVar(CMProps.Str.MUDBINDADDRESS)); } catch (final UnknownHostException e) { Log.errOut(Thread.currentThread().getName(),"ERROR: MUD Server could not bind to address " + CMProps.getVar(CMProps.Str.MUDBINDADDRESS)); } } try { servsock=new ServerSocket(port, q_len, bindAddr); Log.sysOut(Thread.currentThread().getName(),"MUD Server started on port: "+port); if (bindAddr != null) Log.sysOut(Thread.currentThread().getName(),"MUD Server bound to: "+bindAddr.toString()); CMLib.hosts().add(this); while(servsock!=null) { setState(MudState.WAITING); sock=servsock.accept(); acceptConnection(sock); } } catch(final Exception t) { if((!(t instanceof java.net.SocketException)) ||(t.getMessage()==null) ||(t.getMessage().toLowerCase().indexOf("socket closed")<0)) { Log.errOut(Thread.currentThread().getName(),t); } } Log.sysOut(Thread.currentThread().getName(),"Server cleaning up."); try { if(servsock!=null) servsock.close(); if(sock!=null) sock.close(); } catch(final IOException e) { } Log.sysOut(Thread.currentThread().getName(),"MUD on port "+port+" stopped!"); setState(MudState.STOPPED); CMLib.hosts().remove(this); } @Override public String getStatus() { if(CMProps.getBoolVar(CMProps.Bool.MUDSHUTTINGDOWN)) return CMProps.getVar(CMProps.Str.MUDSTATUS); if(!CMProps.getBoolVar(CMProps.Bool.MUDSTARTED)) return CMProps.getVar(CMProps.Str.MUDSTATUS); return state.toString(); } @Override public void shutdown(Session S, boolean keepItDown, String externalCommand) { globalShutdown(S,keepItDown,externalCommand); interrupt(); // kill the damn archon thread. } public static void defaultShutdown() { globalShutdown(null,true,null); } public static void globalShutdown(Session S, boolean keepItDown, String externalCommand) { CMProps.setBoolAllVar(CMProps.Bool.MUDSTARTED,false); CMProps.setBoolAllVar(CMProps.Bool.MUDSHUTTINGDOWN,true); serviceEngine.suspendAll(null); if(S!=null) S.print(CMLib.lang().L("Closing MUD listeners to new connections...")); for(int i=0;i<CMLib.hosts().size();i++) CMLib.hosts().get(i).setAcceptConnections(false); Log.sysOut(Thread.currentThread().getName(),"New Connections are now closed"); if(S!=null) S.println(CMLib.lang().L("Done.")); if(!CMSecurity.isSaveFlag("NOPLAYERS")) { if(S!=null) S.print(CMLib.lang().L("Saving players...")); CMProps.setUpAllLowVar(CMProps.Str.MUDSTATUS,"Shutting down...Saving players..."); for(final Enumeration<CMLibrary> e=CMLib.libraries(CMLib.Library.SESSIONS);e.hasMoreElements();) { final SessionsList list=((SessionsList)e.nextElement()); for(final Session S2 : list.allIterable()) { final MOB M = S2.mob(); if((M!=null)&&(M.playerStats()!=null)) { M.playerStats().setLastDateTime(System.currentTimeMillis()); // important! shutdown their affects! for(int a=M.numAllEffects()-1;a>=0;a--) // reverse enumeration { final Ability A=M.fetchEffect(a); try { if((A!=null)&&(A.canBeUninvoked())) A.unInvoke(); if((A!=null)&&(!A.isSavable())) M.delEffect(A); } catch(final Exception ex) {Log.errOut(ex);} } } } } for(final Enumeration<CMLibrary> e=CMLib.libraries(CMLib.Library.PLAYERS);e.hasMoreElements();) ((PlayerLibrary)e.nextElement()).savePlayers(); if(S!=null) S.println(CMLib.lang().L("done")); Log.sysOut(Thread.currentThread().getName(),"All users saved."); } if(S!=null) S.print(CMLib.lang().L("Saving stats...")); for(final Enumeration<CMLibrary> e=CMLib.libraries(CMLib.Library.STATS);e.hasMoreElements();) ((StatisticsLibrary)e.nextElement()).update(); if(S!=null) S.println(CMLib.lang().L("done")); Log.sysOut(Thread.currentThread().getName(),"Stats saved."); CMProps.setUpAllLowVar(CMProps.Str.MUDSTATUS,"Shutting down" + (keepItDown? "..." : " and restarting...")); Log.sysOut(Thread.currentThread().getName(),"Notifying all objects of shutdown..."); if(S!=null) S.print(CMLib.lang().L("Notifying all objects of shutdown...")); CMProps.setUpAllLowVar(CMProps.Str.MUDSTATUS,"Shutting down...Notifying Objects"); MOB mob=null; if(S!=null) mob=S.mob(); if(mob==null) mob=CMClass.getMOB("StdMOB"); final CMMsg msg=CMClass.getMsg(mob,null,CMMsg.MSG_SHUTDOWN,null); final Vector<Room> roomSet=new Vector<Room>(); try { for(final Enumeration<CMLibrary> e=CMLib.libraries(CMLib.Library.MAP);e.hasMoreElements();) { final WorldMap map=((WorldMap)e.nextElement()); for(final Enumeration<Area> a=map.areas();a.hasMoreElements();) a.nextElement().setAreaState(Area.State.STOPPED); } for(final Enumeration<CMLibrary> e=CMLib.libraries(CMLib.Library.MAP);e.hasMoreElements();) { final WorldMap map=((WorldMap)e.nextElement()); for(final Enumeration<Room> r=map.rooms();r.hasMoreElements();) { final Room R=r.nextElement(); R.send(mob,msg); roomSet.addElement(R); } } }catch(final NoSuchElementException e){} if(S!=null) S.println(CMLib.lang().L("done")); final CMLib.Library[][] libraryShutdownLists={ {CMLib.Library.QUEST,CMLib.Library.TECH,CMLib.Library.SESSIONS}, {CMLib.Library.STATS,CMLib.Library.THREADS}, {CMLib.Library.SOCIALS,CMLib.Library.CLANS,CMLib.Library.CHANNELS,CMLib.Library.JOURNALS, CMLib.Library.POLLS,CMLib.Library.HELP,CMLib.Library.CATALOG,CMLib.Library.MAP, CMLib.Library.PLAYERS } }; for(final CMLib.Library lib : libraryShutdownLists[0]) { CMProps.setUpAllLowVar(CMProps.Str.MUDSTATUS,"Shutting down "+CMStrings.capitalizeAndLower(lib.name())+"..."); for(final Enumeration<CMLibrary> e=CMLib.libraries(lib);e.hasMoreElements();) { try { e.nextElement().shutdown(); } catch(Throwable t) { Log.errOut(t); } } } if(S!=null) S.println(CMLib.lang().L("Save thread stopped")); if(CMSecurity.isSaveFlag("ROOMMOBS") ||CMSecurity.isSaveFlag("ROOMITEMS") ||CMSecurity.isSaveFlag("ROOMSHOPS")) { if(S!=null) S.print(CMLib.lang().L("Saving room data...")); CMProps.setUpAllLowVar(CMProps.Str.MUDSTATUS,"Shutting down...Rejuving the dead"); serviceEngine.tickAllTickers(null); CMProps.setUpAllLowVar(CMProps.Str.MUDSTATUS,"Shutting down...Map Update"); for(final Enumeration<CMLibrary> e=CMLib.libraries(CMLib.Library.MAP);e.hasMoreElements();) { final WorldMap map=((WorldMap)e.nextElement()); for(final Enumeration<Area> a=map.areas();a.hasMoreElements();) a.nextElement().setAreaState(Area.State.STOPPED); } int roomCounter=0; Room R=null; for(final Enumeration<Room> e=roomSet.elements();e.hasMoreElements();) { if(((++roomCounter)%200)==0) { if(S!=null) S.print("."); CMProps.setUpAllLowVar(CMProps.Str.MUDSTATUS,"Shutting down...Map Update ("+roomCounter+")"); } R=e.nextElement(); if(R.roomID().length()>0) R.executeMsg(mob,CMClass.getMsg(mob,R,null,CMMsg.MSG_EXPIRE,null)); } if(S!=null) S.println(CMLib.lang().L("done")); Log.sysOut(Thread.currentThread().getName(),"Map data saved."); } CMProps.setUpAllLowVar(CMProps.Str.MUDSTATUS,"Shutting down...CM1Servers"); for(final CM1Server cm1server : cm1Servers) { try { cm1server.shutdown(); } finally { if(S!=null) S.println(CMLib.lang().L("@x1 stopped",cm1server.getName())); Log.sysOut(Thread.currentThread().getName(),cm1server.getName()+" stopped"); } } cm1Servers.clear(); if(i3server!=null) { CMProps.setUpAllLowVar(CMProps.Str.MUDSTATUS,"Shutting down...I3Server"); I3Server.shutdown(); i3server=null; if(S!=null) S.println(CMLib.lang().L("I3Server stopped")); Log.sysOut(Thread.currentThread().getName(),"I3Server stopped"); } if(imc2server!=null) { CMProps.setUpAllLowVar(CMProps.Str.MUDSTATUS,"Shutting down...IMC2Server"); imc2server.shutdown(); imc2server=null; if(S!=null) S.println(CMLib.lang().L("IMC2Server stopped")); Log.sysOut(Thread.currentThread().getName(),"IMC2Server stopped"); } if(S!=null) S.print(CMLib.lang().L("Stopping player Sessions...")); CMProps.setUpAllLowVar(CMProps.Str.MUDSTATUS,"Shutting down...Stopping sessions"); for(final Enumeration<CMLibrary> e=CMLib.libraries(CMLib.Library.SESSIONS);e.hasMoreElements();) { final SessionsList list=((SessionsList)e.nextElement()); for(final Session S2 : list.allIterable()) { if((S!=null)&&(S2==S)) list.remove(S2); else { CMProps.setUpAllLowVar(CMProps.Str.MUDSTATUS,"Shutting down...Stopping session "+S2.getAddress()); S2.stopSession(true,true,true); CMProps.setUpAllLowVar(CMProps.Str.MUDSTATUS,"Shutting down...Done stopping session "+S2.getAddress()); } if(S!=null) S.print("."); } } if(S!=null) S.println(CMLib.lang().L("All users logged off")); try{Thread.sleep(3000);}catch(final Exception e){/* give sessions a few seconds to inform the map */} Log.sysOut(Thread.currentThread().getName(),"All users logged off."); if(smtpServerThread!=null) { CMProps.setUpAllLowVar(CMProps.Str.MUDSTATUS,"Shutting down...smtp server"); smtpServerThread.shutdown(); smtpServerThread = null; Log.sysOut(Thread.currentThread().getName(),"SMTP Server stopped."); if(S!=null) S.println(CMLib.lang().L("SMTP Server stopped")); } if(S!=null) S.print(CMLib.lang().L("Stopping all threads...")); for(final CMLib.Library lib : libraryShutdownLists[1]) { CMProps.setUpAllLowVar(CMProps.Str.MUDSTATUS,"Shutting down "+CMStrings.capitalizeAndLower(lib.name())+"..."); for(final Enumeration<CMLibrary> e=CMLib.libraries(lib);e.hasMoreElements();) e.nextElement().shutdown(); } if(S!=null) S.println(CMLib.lang().L("done")); Log.sysOut(Thread.currentThread().getName(),"Map Threads Stopped."); CMProps.setUpAllLowVar(CMProps.Str.MUDSTATUS,"Shutting down services..."); for(final CMLib.Library lib : libraryShutdownLists[2]) { CMProps.setUpAllLowVar(CMProps.Str.MUDSTATUS,"Shutting down "+CMStrings.capitalizeAndLower(lib.name())+"..."); for(final Enumeration<CMLibrary> e=CMLib.libraries(lib);e.hasMoreElements();) e.nextElement().shutdown(); } for(final CMLib.Library lib : CMLib.Library.values()) { boolean found=false; for(final CMLib.Library[] prevSet : libraryShutdownLists) found=found||CMParms.contains(prevSet, lib); if(!found) { CMProps.setUpAllLowVar(CMProps.Str.MUDSTATUS,"Shutting down "+CMStrings.capitalizeAndLower(lib.name())+"..."); for(final Enumeration<CMLibrary> e=CMLib.libraries(lib);e.hasMoreElements();) e.nextElement().shutdown(); } } CMProps.setUpAllLowVar(CMProps.Str.MUDSTATUS,"Shutting down...unloading resources"); Resources.shutdown(); Log.sysOut(Thread.currentThread().getName(),"Resources Cleared."); if(S!=null) S.println(CMLib.lang().L("All resources unloaded")); CMProps.setUpAllLowVar(CMProps.Str.MUDSTATUS,"Shutting down...closing db connections"); for(int d=0;d<databases.size();d++) databases.get(d).killConnections(); if(S!=null) S.println(CMLib.lang().L("Database connections closed")); Log.sysOut(Thread.currentThread().getName(),"Database connections closed."); for(int i=0;i<webServers.size();i++) { final WebServer webServerThread=webServers.get(i); CMProps.setUpAllLowVar(CMProps.Str.MUDSTATUS,"Shutting down web server "+webServerThread.getName()+"..."); webServerThread.close(); Log.sysOut(Thread.currentThread().getName(),"Web server "+webServerThread.getName()+" stopped."); if(S!=null) S.println(CMLib.lang().L("Web server @x1 stopped",webServerThread.getName())); } webServers.clear(); CMProps.setUpAllLowVar(CMProps.Str.MUDSTATUS,"Shutting down...unloading macros"); CMLib.lang().clear(); CMProps.setUpAllLowVar(CMProps.Str.MUDSTATUS,"Shutting down...unloading classes"); CMClass.shutdown(); CMProps.setUpAllLowVar(CMProps.Str.MUDSTATUS,"Shutting down" + (keepItDown? "..." : " and restarting...")); try{Thread.sleep(500);}catch(final Exception i){} Log.sysOut(Thread.currentThread().getName(),"CoffeeMud shutdown complete."); if(S!=null) S.println(CMLib.lang().L("CoffeeMud shutdown complete.")); bringDown=keepItDown; serviceEngine.resumeAll(); if(!keepItDown) if(S!=null) S.println(CMLib.lang().L("Restarting...")); if(S!=null) S.stopSession(true,true,false); try{Thread.sleep(500);}catch(final Exception i){} System.gc(); System.runFinalization(); try{Thread.sleep(500);}catch(final Exception i){} execExternalCommand=externalCommand; CMProps.setUpAllLowVar(CMProps.Str.MUDSTATUS,"Shutdown: you are the special lucky chosen one!"); for(int m=CMLib.hosts().size()-1;m>=0;m--) if(CMLib.hosts().get(m) instanceof Thread) { try { CMLib.killThread((Thread)CMLib.hosts().get(m),100,30); } catch(final Exception t){} } CMLib.hosts().clear(); if(!keepItDown) CMProps.setBoolAllVar(CMProps.Bool.MUDSHUTTINGDOWN,false); } private static void startIntermud3() { final char tCode=Thread.currentThread().getThreadGroup().getName().charAt(0); final CMProps page=CMProps.instance(); try { if(page.getBoolean("RUNI3SERVER")&&(tCode==MAIN_HOST)&&(!CMSecurity.isDisabled(CMSecurity.DisFlag.I3))) { if(i3server!=null) I3Server.shutdown(); i3server=null; String playstate=page.getStr("MUDSTATE"); if((playstate==null)||(playstate.length()==0)) playstate=page.getStr("I3STATE"); if((playstate==null)||(!CMath.isInteger(playstate))) playstate="Development"; else switch(CMath.s_int(playstate.trim())) { case 0: playstate = "MudLib Development"; break; case 1: playstate = "Restricted Access"; break; case 2: playstate = "Beta Testing"; break; case 3: playstate = "Open to the public"; break; default: playstate = "MudLib Development"; break; } final IMudInterface imud=new IMudInterface(CMProps.getVar(CMProps.Str.MUDNAME), "CoffeeMud v"+CMProps.getVar(CMProps.Str.MUDVER), CMLib.mud(0).getPort(), playstate, CMLib.channels().getI3ChannelsList()); i3server=new I3Server(); int i3port=page.getInt("I3PORT"); if(i3port==0) i3port=27766; I3Server.start(CMProps.getVar(CMProps.Str.MUDNAME),i3port,imud); } } catch(final Exception e) { if(i3server!=null) I3Server.shutdown(); i3server=null; } } private static void startCM1() { final char tCode=Thread.currentThread().getThreadGroup().getName().charAt(0); final CMProps page=CMProps.instance(); CM1Server cm1server = null; try { final String runcm1=page.getPrivateStr("RUNCM1SERVER"); if((runcm1!=null)&&(runcm1.equalsIgnoreCase("TRUE"))) { final String iniFile = page.getStr("CM1CONFIG"); for(final CM1Server s : cm1Servers) if(s.getINIFilename().equalsIgnoreCase(iniFile)) { s.shutdown(); cm1Servers.remove(s); } cm1server=new CM1Server("CM1Server"+tCode,iniFile); cm1server.start(); cm1Servers.add(cm1server); } } catch(final Exception e) { if(cm1server!=null) { cm1server.shutdown(); cm1Servers.remove(cm1server); } } } private static void startIntermud2() { final char tCode=Thread.currentThread().getThreadGroup().getName().charAt(0); final CMProps page=CMProps.instance(); try { if(page.getBoolean("RUNIMC2CLIENT")&&(tCode==MAIN_HOST)&&(!CMSecurity.isDisabled(CMSecurity.DisFlag.IMC2))) { imc2server=new IMC2Driver(); if(!imc2server.imc_startup(false, page.getStr("IMC2LOGIN").trim(), CMProps.getVar(CMProps.Str.MUDNAME), page.getStr("IMC2MYEMAIL").trim(), page.getStr("IMC2MYWEB").trim(), page.getStr("IMC2HUBNAME").trim(), page.getInt("IMC2HUBPORT"), page.getStr("IMC2PASS1").trim(), page.getStr("IMC2PASS2").trim(), CMLib.channels().getIMC2ChannelsList())) { Log.errOut(Thread.currentThread().getName(),"IMC2 Failed to start!"); imc2server=null; } else { CMLib.intermud().registerIMC2(imc2server); imc2server.start(); } } } catch(final Exception e) { Log.errOut(e); } } @Override public void interrupt() { if(servsock!=null) { try { servsock.close(); servsock = null; } catch(final IOException e) { } } super.interrupt(); } public static int activeThreadCount(ThreadGroup tGroup, boolean nonDaemonsOnly) { int realAC=0; final int ac = tGroup.activeCount(); final Thread tArray[] = new Thread [ac+1]; tGroup.enumerate(tArray); for (int i = 0; i<ac; ++i) { if (tArray[i] != null && tArray[i].isAlive() && (tArray[i] != Thread.currentThread()) && ((!nonDaemonsOnly)||(!tArray[i].isDaemon()))) realAC++; } return realAC; } private static int killCount(ThreadGroup tGroup, boolean nonDaemonsOnly) { int killed=0; final int ac = tGroup.activeCount(); final Thread tArray[] = new Thread [ac+1]; tGroup.enumerate(tArray); for (int i = 0; i<ac; ++i) { if (tArray[i] != null && tArray[i].isAlive() && (tArray[i] != Thread.currentThread()) && ((!nonDaemonsOnly)||(!tArray[i].isDaemon()))) { CMLib.killThread(tArray[i],500,10); killed++; } } return killed; } private static void threadList(ThreadGroup tGroup, boolean nonDaemonsOnly) { if(tGroup==null) return; final int ac = tGroup.activeCount(); final Thread tArray[] = new Thread [ac+1]; tGroup.enumerate(tArray); for (int i = 0; i<ac; ++i) { if (tArray[i] != null && tArray[i].isAlive() && (tArray[i] != Thread.currentThread()) && ((!nonDaemonsOnly)||(!tArray[i].isDaemon()))) { String summary; if(tArray[i] instanceof MudHost) summary=": "+CMClass.classID(tArray[i])+": "+((MudHost)tArray[i]).getStatus(); else { final Runnable R=serviceEngine.findRunnableByThread(tArray[i]); if(R instanceof TickableGroup) summary=": "+((TickableGroup)R).getName()+": "+((TickableGroup)R).getStatus(); else if(R instanceof Session) { final Session S=(Session)R; final MOB mob=S.mob(); final String mobName=(mob==null)?"null":mob.Name(); summary=": session "+mobName+": "+S.getStatus().toString()+": "+CMParms.combineQuoted(S.getPreviousCMD(),0); } else if(R instanceof CMRunnable) summary=": "+CMClass.classID(R)+": active for "+((CMRunnable)R).activeTimeMillis()+"ms"; else if(CMClass.classID(R).length()>0) summary=": "+CMClass.classID(R); else summary=""; } Log.sysOut(Thread.currentThread().getName(), "-->Thread: "+tArray[i].getName() + summary+"\n\r"); } } } @Override public String getHost() { return host; } @Override public int getPort() { return port; } private static class HostGroup extends Thread { private String name=null; private String iniFile=null; private String logName=null; private char threadCode=MAIN_HOST; private boolean hostStarted=false; private boolean failedStart=false; //protected ThreadGroup threadGroup; public HostGroup(ThreadGroup G, String mudName, String iniFileName) { super(G,"HOST"+grpid); //threadGroup=G; synchronized("HostGroupInit".intern()) { logName="mud"+((grpid>0)?("."+grpid):""); grpid++; iniFile=iniFileName; name=mudName; setDaemon(true); threadCode=G.getName().charAt(0); } } public boolean isStarted() { return hostStarted; } public boolean failedToStart() { return failedStart; } public void fatalStartupError(Thread t, int type) { String errorInternal=null; switch(type) { case 1: errorInternal="ERROR: initHost() will not run without properties. Exiting."; break; case 2: errorInternal="Map is empty?! Exiting."; break; case 3: errorInternal="Database init failed. Exiting."; break; case 4: errorInternal="Fatal exception. Exiting."; break; case 5: errorInternal="MUD Server did not start. Exiting."; break; default: errorInternal="Fatal error loading classes. Make sure you start up coffeemud from the directory containing the class files."; break; } Log.errOut(Thread.currentThread().getName(),errorInternal); bringDown=true; CMProps.setBoolAllVar(CMProps.Bool.MUDSHUTTINGDOWN,true); //CMLib.killThread(t,100,1); } protected boolean initHost() { final Thread t=Thread.currentThread(); final CMProps page=CMProps.instance(); if ((page == null) || (!page.isLoaded())) { fatalStartupError(t,1); return false; } final char tCode=Thread.currentThread().getThreadGroup().getName().charAt(0); final boolean checkPrivate=(tCode!=MAIN_HOST); final List<String> compress=CMParms.parseCommas(page.getStr("COMPRESS").toUpperCase(),true); CMProps.setBoolVar(CMProps.Bool.ITEMDCOMPRESS,compress.contains("ITEMDESC")); CMProps.setBoolVar(CMProps.Bool.MOBCOMPRESS,compress.contains("GENMOBS")); CMProps.setBoolVar(CMProps.Bool.ROOMDCOMPRESS,compress.contains("ROOMDESC")); CMProps.setBoolVar(CMProps.Bool.MOBDCOMPRESS,compress.contains("MOBDESC")); Resources.setCompression(compress.contains("RESOURCES")); final List<String> nocache=CMParms.parseCommas(page.getStr("NOCACHE").toUpperCase(),true); CMProps.setBoolVar(CMProps.Bool.MOBNOCACHE,nocache.contains("GENMOBS")); CMProps.setBoolVar(CMProps.Bool.ROOMDNOCACHE,nocache.contains("ROOMDESC")); CMProps.setBoolVar(CMProps.Bool.FILERESOURCENOCACHE, nocache.contains("FILERESOURCES")); CMProps.setBoolVar(CMProps.Bool.CATALOGNOCACHE, nocache.contains("CATALOG")); CMProps.setBoolVar(CMProps.Bool.MAPFINDSNOCACHE,nocache.contains("MAPFINDERS")); CMProps.setBoolVar(CMProps.Bool.ACCOUNTSNOCACHE,nocache.contains("ACCOUNTS")); CMProps.setBoolVar(CMProps.Bool.PLAYERSNOCACHE,nocache.contains("PLAYERS")); DBConnector currentDBconnector=null; String dbClass=page.getStr("DBCLASS"); if(tCode!=MAIN_HOST) { DatabaseEngine baseEngine=(DatabaseEngine)CMLib.library(MAIN_HOST,CMLib.Library.DATABASE); while((!MUD.bringDown) &&((baseEngine==null)||(!baseEngine.isConnected()))) { try {Thread.sleep(500);}catch(final Exception e){ break;} baseEngine=(DatabaseEngine)CMLib.library(MAIN_HOST,CMLib.Library.DATABASE); } if(MUD.bringDown) return false; if(page.getPrivateStr("DBCLASS").length()==0) { CMLib.registerLibrary(baseEngine); dbClass=""; } } if(dbClass.length()>0) { final String dbService=page.getStr("DBSERVICE"); final String dbUser=page.getStr("DBUSER"); final String dbPass=page.getStr("DBPASS"); final int dbConns=page.getInt("DBCONNECTIONS"); final int dbPingIntMins=page.getInt("DBPINGINTERVALMINS"); if(dbConns == 0) { Log.errOut(Thread.currentThread().getName(),"Fatal error: DBCONNECTIONS in INI file is "+dbConns); System.exit(-1); } final boolean dbReuse=page.getBoolean("DBREUSE"); final boolean useQue=!CMSecurity.isDisabled(CMSecurity.DisFlag.DBERRORQUE); final boolean useQueStart=!CMSecurity.isDisabled(CMSecurity.DisFlag.DBERRORQUESTART); CMProps.setUpLowVar(CMProps.Str.MUDSTATUS,"Booting: connecting to database"); currentDBconnector=new DBConnector(dbClass,dbService,dbUser,dbPass,dbConns,dbPingIntMins,dbReuse,useQue,useQueStart); currentDBconnector.reconnect(); CMLib.registerLibrary(new DBInterface(currentDBconnector,CMProps.getPrivateSubSet("DB.*"))); final DBConnection DBTEST=currentDBconnector.DBFetch(); if(DBTEST!=null) currentDBconnector.DBDone(DBTEST); if((DBTEST!=null)&&(currentDBconnector.amIOk())&&(CMLib.database().isConnected())) { Log.sysOut(Thread.currentThread().getName(),"Connected to "+currentDBconnector.service()); databases.add(currentDBconnector); } else { final String DBerrors=currentDBconnector.errorStatus().toString(); Log.errOut(Thread.currentThread().getName(),"Fatal database error: "+DBerrors); return false; } } else if(CMLib.database()==null) { Log.errOut(Thread.currentThread().getName(),"No registered database!"); return false; } // test the database try { final CMFile F = new CMFile("/test.the.database",null); if(F.exists()) Log.sysOut(Thread.currentThread().getName(),"Test file found .. hmm.. that was unexpected."); } catch(final Exception e) { Log.errOut(e); Log.errOut("Database error! Panic shutdown!"); return false; } String webServersList=page.getPrivateStr("RUNWEBSERVERS"); if(webServersList.equalsIgnoreCase("true")) webServersList="pub,admin"; if((webServersList.length()>0)&&(!webServersList.equalsIgnoreCase("false"))) { final List<String> serverNames=CMParms.parseCommas(webServersList,true); for(int s=0;s<serverNames.size();s++) { final String serverName=serverNames.get(s); try { final StringBuffer commonProps=new CMFile("web/common.ini", null, CMFile.FLAG_LOGERRORS).text(); final StringBuffer finalProps=new CMFile("web/"+serverName+".ini", null, CMFile.FLAG_LOGERRORS).text(); commonProps.append("\n").append(finalProps.toString()); final CWConfig config=new CWConfig(); config.setFileManager(new CMFile.CMFileManager()); WebServer.initConfig(config, Log.instance(), new ByteArrayInputStream(commonProps.toString().getBytes())); if(CMSecurity.isDebugging(DbgFlag.HTTPREQ)) config.setDebugFlag(page.getStr("DBGMSGS")); if(CMSecurity.isDebugging(DbgFlag.HTTPACCESS)) config.setAccessLogFlag(page.getStr("ACCMSGS")); final WebServer webServer=new WebServer(serverName+Thread.currentThread().getThreadGroup().getName().charAt(0),config); config.setCoffeeWebServer(webServer); webServer.start(); webServers.add(webServer); } catch(final Exception e) { Log.errOut("HTTP server "+serverName+"NOT started: "+e.getMessage()); } } } if(page.getPrivateStr("RUNSMTPSERVER").equalsIgnoreCase("true")) { smtpServerThread = new SMTPserver(CMLib.mud(0)); smtpServerThread.start(); serviceEngine.startTickDown(Thread.currentThread().getThreadGroup(),smtpServerThread,Tickable.TICKID_EMAIL,CMProps.getTickMillis(),(int)CMProps.getTicksPerMinute() * 5); } CMProps.setUpLowVar(CMProps.Str.MUDSTATUS,"Booting: loading base classes"); if(!CMClass.loadAllCoffeeMudClasses(page)) { fatalStartupError(t,0); return false; } CMLib.lang().setLocale(CMLib.props().getStr("LANGUAGE"),CMLib.props().getStr("COUNTRY")); if((threadCode==MudHost.MAIN_HOST)||(CMLib.time()!=CMLib.library(MudHost.MAIN_HOST, CMLib.Library.TIME))) CMLib.time().globalClock().initializeINIClock(page); if((tCode==MAIN_HOST)||(checkPrivate&&CMProps.isPrivateToMe("FACTIONS"))) CMLib.factions().reloadFactions(CMProps.getVar(CMProps.Str.PREFACTIONS)); if((tCode==MAIN_HOST)||(checkPrivate&&CMProps.isPrivateToMe("CHANNELS"))||(checkPrivate&&CMProps.isPrivateToMe("JOURNALS"))) { int numChannelsLoaded=0; int numJournalsLoaded=0; if((tCode==MAIN_HOST)||(checkPrivate&&CMProps.isPrivateToMe("CHANNELS"))) numChannelsLoaded=CMLib.channels().loadChannels(page.getStr("CHANNELS"), page.getStr("ICHANNELS"), page.getStr("IMC2CHANNELS")); if((tCode==MAIN_HOST)||(checkPrivate&&CMProps.isPrivateToMe("JOURNALS"))) { numJournalsLoaded=CMLib.journals().loadCommandJournals(page.getStr("COMMANDJOURNALS")); numJournalsLoaded+=CMLib.journals().loadForumJournals(page.getStr("FORUMJOURNALS")); } Log.sysOut(Thread.currentThread().getName(),"Channels loaded : "+(numChannelsLoaded+numJournalsLoaded)); } if((tCode==MAIN_HOST)||(page.getRawPrivateStr("SYSOPMASK")!=null)) // needs to be after journals, for journal flags { CMSecurity.setSysOp(page.getStr("SYSOPMASK")); // requires all classes be loaded CMSecurity.parseGroups(page); } if((tCode==MAIN_HOST)||(checkPrivate&&CMProps.isPrivateToMe("SOCIALS"))) { CMProps.setUpLowVar(CMProps.Str.MUDSTATUS,"Booting: loading socials"); CMLib.socials().unloadSocials(); if(CMLib.socials().numSocialSets()==0) Log.errOut(Thread.currentThread().getName(),"WARNING: Unable to load socials from socials.txt!"); else Log.sysOut(Thread.currentThread().getName(),"Socials loaded : "+CMLib.socials().numSocialSets()); } if((tCode==MAIN_HOST)||(checkPrivate&&CMProps.isPrivateToMe("CLANS"))) { CMLib.database().DBReadAllClans(); Log.sysOut(Thread.currentThread().getName(),"Clans loaded : "+CMLib.clans().numClans()); } if((tCode==MAIN_HOST)||(checkPrivate&&CMProps.isPrivateToMe("FACTIONS"))) serviceEngine.startTickDown(Thread.currentThread().getThreadGroup(),CMLib.factions(),Tickable.TICKID_MOB,CMProps.getTickMillis(),10); CMProps.setUpLowVar(CMProps.Str.MUDSTATUS,"Booting: Starting CM1"); startCM1(); CMProps.setUpLowVar(CMProps.Str.MUDSTATUS,"Booting: Starting I3"); startIntermud3(); CMProps.setUpLowVar(CMProps.Str.MUDSTATUS,"Booting: Starting IMC2"); startIntermud2(); try{Thread.sleep(500);}catch(final Exception e){} if((tCode==MAIN_HOST)||(checkPrivate&&CMProps.isPrivateToMe("CATALOG"))) { Log.sysOut(Thread.currentThread().getName(),"Loading catalog..."); CMProps.setUpLowVar(CMProps.Str.MUDSTATUS,"Booting: loading catalog...."); CMLib.database().DBReadCatalogs(); } if((tCode==MAIN_HOST)||(checkPrivate&&CMProps.isPrivateToMe("MAP"))) { Log.sysOut(Thread.currentThread().getName(),"Loading map..."); CMProps.setUpLowVar(CMProps.Str.MUDSTATUS,"Booting: loading rooms...."); CMLib.database().DBReadAllRooms(null); CMProps.setUpLowVar(CMProps.Str.MUDSTATUS,"Booting: loading space...."); CMLib.database().DBReadSpace(); CMProps.setUpLowVar(CMProps.Str.MUDSTATUS,"Booting: preparing map...."); Log.sysOut(Thread.currentThread().getName(),"Preparing map..."); CMLib.database().DBReadArtifacts(); for(final Enumeration<Area> a=CMLib.map().areas();a.hasMoreElements();) { final Area A=a.nextElement(); CMProps.setUpLowVar(CMProps.Str.MUDSTATUS,"Booting: filling map ("+A.Name()+")"); A.fillInAreaRooms(); } Log.sysOut(Thread.currentThread().getName(),"Mapped rooms : "+CMLib.map().numRooms()+" in "+CMLib.map().numAreas()+" areas"); if(CMLib.map().numSpaceObjects()>0) Log.sysOut(Thread.currentThread().getName(),"Space objects : "+CMLib.map().numSpaceObjects()); if(!CMLib.map().roomIDs().hasMoreElements()) { Log.sysOut("NO MAPPED ROOM?! I'll make ya one!"); final String id="START";//New Area#0"; final Area newArea=CMClass.getAreaType("StdArea"); newArea.setName(CMLib.lang().L("New Area")); CMLib.map().addArea(newArea); CMLib.database().DBCreateArea(newArea); final Room room=CMClass.getLocale("StdRoom"); room.setRoomID(id); room.setArea(newArea); room.setDisplayText(CMLib.lang().L("New Room")); room.setDescription(CMLib.lang().L("Brand new database room! You need to change this text with the MODIFY ROOM command. If your character is not an Archon, pick up the book you see here and read it immediately!")); CMLib.database().DBCreateRoom(room); final Item I=CMClass.getMiscMagic("ManualArchon"); room.addItem(I); CMLib.database().DBUpdateItems(room); } CMLib.login().initStartRooms(page); CMLib.login().initDeathRooms(page); CMLib.login().initBodyRooms(page); } if((tCode==MAIN_HOST)||(checkPrivate&&CMProps.isPrivateToMe("QUESTS"))) { CMLib.database().DBReadQuests(CMLib.mud(0)); if(CMLib.quests().numQuests()>0) Log.sysOut(Thread.currentThread().getName(),"Quests loaded : "+CMLib.quests().numQuests()); } if(tCode!=MAIN_HOST) { CMProps.setUpLowVar(CMProps.Str.MUDSTATUS,"Booting: Waiting for HOST0"); while((!MUD.bringDown) &&(!CMProps.getBoolVar(CMProps.Bool.MUDSTARTED)) &&(!CMProps.getBoolVar(CMProps.Bool.MUDSHUTTINGDOWN))) try{Thread.sleep(500);}catch(final Exception e){ break;} if((MUD.bringDown) ||(!CMProps.getBoolVar(CMProps.Bool.MUDSTARTED)) ||(CMProps.getBoolVar(CMProps.Bool.MUDSHUTTINGDOWN))) return false; } CMProps.setUpLowVar(CMProps.Str.MUDSTATUS,"Booting: readying for connections."); try { CMLib.activateLibraries(); Log.sysOut(Thread.currentThread().getName(),"Services and utilities started"); } catch (final Throwable th) { Log.errOut(Thread.currentThread().getName(),"CoffeeMud Server initHost() failed"); Log.errOut(Thread.currentThread().getName(),th); fatalStartupError(t,4); return false; } final StringBuffer str=new StringBuffer(""); for(int m=0;m<CMLib.hosts().size();m++) { final MudHost mud=CMLib.hosts().get(m); str.append(" "+mud.getPort()); } CMProps.setVar(CMProps.Str.MUDPORTS,str.toString()); CMProps.setBoolAllVar(CMProps.Bool.MUDSTARTED,true); CMProps.setUpLowVar(CMProps.Str.MUDSTATUS,"OK"); Log.sysOut(Thread.currentThread().getName(),"Host#"+threadCode+" initializated."); return true; } @Override public void run() { CMLib.initialize(); // initialize the lib CMClass.initialize(); // initialize the classes Log.shareWith(MudHost.MAIN_HOST); Resources.shareWith(MudHost.MAIN_HOST); // wait for ini to be loaded, and for other matters if(threadCode!=MAIN_HOST) { while((CMLib.library(MAIN_HOST,CMLib.Library.INTERMUD)==null)&&(!MUD.bringDown)) { try {Thread.sleep(500);}catch(final Exception e){ break;} } if(MUD.bringDown) return; } final CMProps page=CMProps.loadPropPage("//"+iniFile); if ((page==null)||(!page.isLoaded())) { Log.errOut(Thread.currentThread().getName(),"ERROR: Unable to read ini file: '"+iniFile+"'."); System.out.println("MUD/ERROR: Unable to read ini file: '"+iniFile+"'."); CMProps.setUpLowVar(CMProps.Str.MUDSTATUS,"A terminal error has occured!"); return; } page.resetSystemVars(); CMProps.setBoolAllVar(CMProps.Bool.MUDSTARTED,false); serviceEngine.activate(); if(threadCode!=MAIN_HOST) { if(CMath.isInteger(page.getPrivateStr("NUMLOGS"))) { Log.newInstance(); Log.instance().configureLogFile(logName,page.getInt("NUMLOGS")); Log.instance().configureLog(Log.Type.info, page.getStr("SYSMSGS")); Log.instance().configureLog(Log.Type.error, page.getStr("ERRMSGS")); Log.instance().configureLog(Log.Type.warning, page.getStr("WRNMSGS")); Log.instance().configureLog(Log.Type.debug, page.getStr("DBGMSGS")); Log.instance().configureLog(Log.Type.help, page.getStr("HLPMSGS")); Log.instance().configureLog(Log.Type.kills, page.getStr("KILMSGS")); Log.instance().configureLog(Log.Type.combat, page.getStr("CBTMSGS")); Log.instance().configureLog(Log.Type.access, page.getStr("ACCMSGS")); } if(page.getRawPrivateStr("SYSOPMASK")!=null) page.resetSecurityVars(); else CMSecurity.instance().markShared(); } if(page.getStr("DISABLE").trim().length()>0) Log.sysOut(Thread.currentThread().getName(),"Disabled subsystems: "+page.getStr("DISABLE")); if(page.getStr("DEBUG").trim().length()>0) { Log.sysOut(Thread.currentThread().getName(),"Debugging messages: "+page.getStr("DEBUG")); if(!Log.debugChannelOn()) Log.errOut(Thread.currentThread().getName(),"Debug logging is disabled! Check your DBGMSGS flag!"); } final DBConnector currentDBconnector=new DBConnector(); CMLib.registerLibrary(new DBInterface(currentDBconnector,CMProps.getPrivateSubSet("DB.*"))); CMProps.setVar(CMProps.Str.MUDVER,HOST_VERSION_MAJOR + "." + HOST_VERSION_MINOR); // an arbitrary dividing line. After threadCode 0 if(threadCode==MAIN_HOST) { CMLib.registerLibrary(serviceEngine); CMLib.registerLibrary(new IMudClient()); } else { CMLib.registerLibrary(CMLib.library(MAIN_HOST,CMLib.Library.THREADS)); CMLib.registerLibrary(CMLib.library(MAIN_HOST,CMLib.Library.INTERMUD)); } CMProps.setVar(CMProps.Str.INIPATH,iniFile,false); CMProps.setUpLowVar(CMProps.Str.MUDNAME,name.replace('\'','`')); try { CMProps.setUpLowVar(CMProps.Str.MUDSTATUS,"Booting"); CMProps.setVar(CMProps.Str.MUDBINDADDRESS,page.getStr("BIND")); CMProps.setIntVar(CMProps.Int.MUDBACKLOG,page.getInt("BACKLOG")); final LinkedList<MUD> hostMuds=new LinkedList<MUD>(); String ports=page.getProperty("PORT"); int pdex=ports.indexOf(','); while(pdex>0) { final MUD mud=new MUD("MUD@"+ports.substring(0,pdex)); mud.setState(MudState.STARTING); mud.acceptConns=false; mud.port=CMath.s_int(ports.substring(0,pdex)); ports=ports.substring(pdex+1); hostMuds.add(mud); mud.start(); pdex=ports.indexOf(','); } final MUD mud=new MUD("MUD@"+ports); mud.setState(MudState.STARTING); mud.acceptConns=false; mud.port=CMath.s_int(ports); hostMuds.add(mud); mud.start(); if(hostMuds.size()==0) { Log.errOut("HOST#"+this.threadCode+" could not start any listeners."); return; } boolean oneStarted=false; final long timeout=System.currentTimeMillis()+60000; while((!oneStarted) && (System.currentTimeMillis()<timeout)) { int numStopped=0; for(final MUD m : hostMuds) if(m.state==MudState.STOPPED) numStopped++; else if(m.state!=MudState.STARTING) oneStarted=true; if(numStopped==hostMuds.size()) { Log.errOut("HOST#"+this.threadCode+" could not start any listeners."); failedStart=true; return; } try { Thread.sleep(100); }catch(final Exception e){} } if(!oneStarted) { Log.errOut("HOST#"+this.threadCode+" could not start any listeners."); failedStart=true; return; } if(initHost()) { Thread joinable=null; for(int i=0;i<CMLib.hosts().size();i++) if(CMLib.hosts().get(i) instanceof Thread) { joinable=(Thread)CMLib.hosts().get(i); break; } if(joinable!=null) { hostStarted=true; joinable.join(); } else failedStart=true; } else { failedStart=true; } } catch(final InterruptedException e) { Log.errOut(Thread.currentThread().getName(),e); } } } @Override public List<Runnable> getOverdueThreads() { final Vector<Runnable> V=new Vector<Runnable>(); for(int w=0;w<webServers.size();w++) V.addAll(webServers.get(w).getOverdueThreads()); return V; } public static void main(String a[]) { String nameID=""; Thread.currentThread().setName(("MUD")); final Vector<String> iniFiles=new Vector<String>(); if(a.length>0) { for (final String element : a) nameID+=" "+element; nameID=nameID.trim(); final List<String> V=CMParms.cleanParameterList(nameID); for(int v=0;v<V.size();v++) { final String s=V.get(v); if(s.toUpperCase().startsWith("BOOT=")&&(s.length()>5)) { iniFiles.addElement(s.substring(5)); V.remove(v); v--; } } nameID=CMParms.combine(V,0); } CMLib.initialize(); // initialize this threads libs if(iniFiles.size()==0) iniFiles.addElement("coffeemud.ini"); if((nameID.length()==0)||(nameID.equalsIgnoreCase( "CoffeeMud" ))||nameID.equalsIgnoreCase("Your Muds Name")) { nameID="Unnamed_CoffeeMUD#"; long idNumber=new Random(System.currentTimeMillis()).nextLong(); try { idNumber=0; for(final Enumeration<NetworkInterface> e=NetworkInterface.getNetworkInterfaces();e.hasMoreElements();) { final NetworkInterface n=e.nextElement(); idNumber^=n.getDisplayName().hashCode(); try { final Method m=n.getClass().getMethod("getHardwareAddress"); final Object o=m.invoke(n); if(o instanceof byte[]) { for(int i=0;i<((byte[])o).length;i++) idNumber^=((byte[])o)[0] << (i*8); } }catch(final Exception e1){} } }catch(final Exception e1){} if(idNumber<0) idNumber=idNumber*-1; nameID=nameID+idNumber; System.err.println("*** Please give your mud a unique name in mud.bat or mudUNIX.sh!! ***"); } else if(nameID.equalsIgnoreCase( "TheRealCoffeeMudCopyright2000-2014ByBoZimmerman" )) nameID="CoffeeMud"; String iniFile=iniFiles.firstElement(); final CMProps page=CMProps.loadPropPage("//"+iniFile); if ((page==null)||(!page.isLoaded())) { Log.instance().configureLogFile("mud",1); Log.instance().configureLog(Log.Type.info, "BOTH"); Log.instance().configureLog(Log.Type.error, "BOTH"); Log.instance().configureLog(Log.Type.warning, "BOTH"); Log.instance().configureLog(Log.Type.debug, "BOTH"); Log.instance().configureLog(Log.Type.help, "BOTH"); Log.instance().configureLog(Log.Type.kills, "BOTH"); Log.instance().configureLog(Log.Type.combat, "BOTH"); Log.instance().configureLog(Log.Type.access, "BOTH"); Log.errOut(Thread.currentThread().getName(),"ERROR: Unable to read ini file: '"+iniFile+"'."); System.out.println("MUD/ERROR: Unable to read ini file: '"+iniFile+"'."); CMProps.setUpAllLowVar(CMProps.Str.MUDSTATUS,"A terminal error has occured!"); System.exit(-1); return; } Log.shareWith(MudHost.MAIN_HOST); Log.instance().configureLogFile("mud",page.getInt("NUMLOGS")); Log.instance().configureLog(Log.Type.info, page.getStr("SYSMSGS")); Log.instance().configureLog(Log.Type.error, page.getStr("ERRMSGS")); Log.instance().configureLog(Log.Type.warning, page.getStr("WRNMSGS")); Log.instance().configureLog(Log.Type.debug, page.getStr("DBGMSGS")); Log.instance().configureLog(Log.Type.help, page.getStr("HLPMSGS")); Log.instance().configureLog(Log.Type.kills, page.getStr("KILMSGS")); Log.instance().configureLog(Log.Type.combat, page.getStr("CBTMSGS")); Log.instance().configureLog(Log.Type.access, page.getStr("ACCMSGS")); final Thread shutdownHook=new Thread("ShutdownHook") { @Override public void run() { if(!CMProps.getBoolVar(CMProps.Bool.MUDSHUTTINGDOWN)) MUD.globalShutdown(null,true,null); } }; while(!bringDown) { System.out.println(); grpid=0; Log.sysOut(Thread.currentThread().getName(),"CoffeeMud v"+HOST_VERSION_MAJOR + "." + HOST_VERSION_MINOR); Log.sysOut(Thread.currentThread().getName(),"(C) 2000-2014 Bo Zimmerman"); Log.sysOut(Thread.currentThread().getName(),"http://www.coffeemud.org"); CMLib.hosts().clear(); final LinkedList<HostGroup> myGroups=new LinkedList<HostGroup>(); HostGroup mainGroup=null; for(int i=0;i<iniFiles.size();i++) { iniFile=iniFiles.elementAt(i); final ThreadGroup G=new ThreadGroup(i+"-MUD"); final HostGroup H=new HostGroup(G,nameID,iniFile); if(mainGroup==null) mainGroup=H; myGroups.add(H); H.start(); } if(mainGroup==null) { Log.errOut("CoffeeMud failed to start."); MUD.bringDown=true; CMProps.setBoolAllVar(CMProps.Bool.MUDSHUTTINGDOWN, true); } else { final long timeout=System.currentTimeMillis()+1800000; /// 30 mins int numPending=1; while((numPending>0)&&(System.currentTimeMillis()<timeout)) { numPending=0; for(final HostGroup g : myGroups) if(!g.failedToStart() && !g.isStarted()) numPending++; if(mainGroup.failedToStart()) break; try { Thread.sleep(100); } catch(final Exception e) {} } if(mainGroup.failedToStart()) { Log.errOut("CoffeeMud failed to start."); MUD.bringDown=true; CMProps.setBoolAllVar(CMProps.Bool.MUDSHUTTINGDOWN, true); } else { Runtime.getRuntime().addShutdownHook(shutdownHook); for(int i=0;i<CMLib.hosts().size();i++) CMLib.hosts().get(i).setAcceptConnections(true); Log.sysOut(Thread.currentThread().getName(),"Initialization complete."); try{mainGroup.join();}catch(final Exception e){e.printStackTrace(); Log.errOut(Thread.currentThread().getName(),e); } Runtime.getRuntime().removeShutdownHook(shutdownHook); } } System.gc(); try{Thread.sleep(1000);}catch(final Exception e){} System.runFinalization(); try{Thread.sleep(1000);}catch(final Exception e){} if(activeThreadCount(Thread.currentThread().getThreadGroup(),true)>1) { try{ Thread.sleep(1000);}catch(final Exception e){} killCount(Thread.currentThread().getThreadGroup(),true); try{ Thread.sleep(1000);}catch(final Exception e){} if(activeThreadCount(Thread.currentThread().getThreadGroup(),true)>1) { Log.sysOut(Thread.currentThread().getName(),"WARNING: " + activeThreadCount(Thread.currentThread().getThreadGroup(),true) +" other thread(s) are still active!"); threadList(Thread.currentThread().getThreadGroup(),true); } } if(!bringDown) { if(execExternalCommand!=null) { //Runtime r=Runtime.getRuntime(); //Process p=r.exec(external); Log.sysOut("Attempted to execute '"+execExternalCommand+"'."); execExternalCommand=null; bringDown=true; } } } } @Override public void setAcceptConnections(boolean truefalse) { acceptConns=truefalse; } @Override public boolean isAcceptingConnections() { return acceptConns; } @Override public long getUptimeSecs() { return (System.currentTimeMillis()-startupTime)/1000; } @Override public String executeCommand(String cmd) throws Exception { final Vector<String> V=CMParms.parse(cmd); if(V.size()==0) throw new CMException("Unknown command!"); final String word=V.firstElement(); if(word.equalsIgnoreCase("START")&&(V.size()>1)) { final String what=V.elementAt(1); if(what.equalsIgnoreCase("I3")) { startIntermud3(); return "Done"; } else if(what.equalsIgnoreCase("IMC2")) { startIntermud2(); return "Done"; } } throw new CMException("Unknown command: "+word); } }
git-svn-id: svn://192.168.1.10/public/CoffeeMud@12723 0d6f1817-ed0e-0410-87c9-987e46238f29
com/planet_ink/coffee_mud/application/MUD.java
Java
apache-2.0
f2c16aa0dd023ee3386a0a9ca217ffbefade82ff
0
Thelonedevil/OTBProject,OTBProject/OTBProject,NthPortal/OTBProject
package com.github.otbproject.otbproject.gui; import com.github.otbproject.otbproject.App; import com.github.otbproject.otbproject.bot.Bot; import com.github.otbproject.otbproject.config.Configs; import com.github.otbproject.otbproject.fs.FSUtil; import com.github.otbproject.otbproject.util.Util; import com.github.otbproject.otbproject.util.version.AppVersion; import com.github.otbproject.otbproject.util.version.Version; import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.Alert; import javafx.scene.control.ButtonBar; import javafx.scene.control.ButtonType; import javafx.scene.control.DialogPane; import javafx.scene.image.Image; import javafx.scene.text.Font; import javafx.stage.Stage; import javafx.stage.StageStyle; import org.apache.commons.io.input.Tailer; import org.apache.commons.io.input.TailerListenerAdapter; import java.awt.*; import java.io.File; import java.io.IOException; import java.net.URL; public class GuiApplication extends Application { private static GuiController controller; private Tailer tailer; /** * The main entry point for all JavaFX applications. * The start method is called after the init method has returned, * and after the system is ready for the application to begin running. * <p> * NOTE: This method is called on the JavaFX Application Thread. * </p> * * @param primaryStage the primary stage for this application, onto which * the application scene can be set. The primary stage will be embedded in * the browser if the application was launched as an applet. * Applications may create other stages, if needed, but they will not be * primary stages and will not be embedded in the browser. */ @Override public void start(Stage primaryStage) throws Exception { Font.loadFont(getClass().getClassLoader().getResourceAsStream("UbuntuMono-R.ttf"), 12); Font.loadFont(getClass().getClassLoader().getResourceAsStream("Ubuntu-R.ttf"), 12); FXMLLoader loader = new FXMLLoader(getClass().getClassLoader().getResource("console.fxml")); Parent start = loader.load(); primaryStage.setScene(new Scene(start, 1200, 515)); primaryStage.setResizable(false); primaryStage.setTitle("OTBProject"); primaryStage.getIcons().add(new Image("http://otbproject.github.io/images/logo.png")); primaryStage.setOnCloseRequest(event -> { Alert alert = new Alert(Alert.AlertType.WARNING); alert.setTitle("Confirm Close"); alert.setHeaderText("WARNING: \"Close Window\" DOES NOT STOP THE BOT."); alert.setContentText("Closing this window without exiting may make it difficult to stop the bot.\nPress \"Exit\" to stop the bot and exit.\nPress \"Cancel\" to keep the window open."); DialogPane dialogPane = alert.getDialogPane(); setDialogPaneStyle(dialogPane); ButtonType buttonTypeCloseNoExit = new ButtonType("Close Window", ButtonBar.ButtonData.LEFT); ButtonType buttonTypeExit = new ButtonType("Exit", ButtonBar.ButtonData.FINISH); ButtonType buttonTypeCancel = new ButtonType("Cancel", ButtonBar.ButtonData.FINISH); alert.getButtonTypes().setAll(buttonTypeCloseNoExit, buttonTypeExit, buttonTypeCancel); GuiUtils.setDefaultButton(alert, buttonTypeExit); alert.initStyle(StageStyle.UNDECORATED); alert.showAndWait().ifPresent(buttonType -> { if (buttonType == buttonTypeCloseNoExit) { primaryStage.hide(); tailer.stop(); } else if (buttonType == buttonTypeExit) { App.logger.info("Stopping the process"); if (Bot.getBot() != null && Bot.getBot().isConnected()) { Bot.getBot().shutdown(); } App.logger.info("Process Stopped, Goodbye"); System.exit(0); } }); event.consume(); }); controller = loader.<GuiController>getController(); setUpMenus(); controller.cliOutput.appendText("> "); controller.commandsInput.setEditable(false); controller.commandsOutput.appendText("Type \"help\" for a list of commands.\nThe PID of the bot is probably " + App.PID + ", if you are using an Oracle JVM, but it may be different, especially if you are using a different JVM. Be careful stopping the bot using this PID."); File logFile = new File(FSUtil.logsDir() + File.separator + "console.log"); tailer = Tailer.create(logFile, new CustomTailer(), 250); controller.readHistory(); primaryStage.show(); checkForNewRelease(); } public static void start(String[] args) { launch(args); } public static void setInputActive() { GuiUtils.runSafe(() -> { controller.commandsInput.setEditable(true); controller.commandsInput.setPromptText("Enter command here..."); }); } public static void addInfo(String text) { GuiUtils.runSafe(() -> controller.commandsOutput.appendText("\n\n" + text)); } public static void clearLog() { GuiUtils.runSafe(controller.logOutput::clear); } public static void clearInfo() { GuiUtils.runSafe(controller.commandsOutput::clear); } public static void clearCliOutput() { GuiUtils.runSafe(controller.cliOutput::clear); } public static void clearHistory() { GuiUtils.runSafe(() -> { controller.history.clear(); controller.historyPointer = 0; controller.writeHistory(); }); } static class CustomTailer extends TailerListenerAdapter { @Override public void handle(String line) { GuiUtils.runSafe(() -> controller.logOutput.appendText(line + "\n")); } } private void setUpMenus() { controller.openBaseDir.setOnAction(event -> { Util.getSingleThreadExecutor("file-explorer-%d").execute(() -> { try { Desktop.getDesktop().open(new File(FSUtil.getBaseDir())); } catch (IOException e) { App.logger.catching(e); } }); event.consume(); }); controller.botStart.setOnAction(event -> { try { addInfo(Bot.Control.startup() ? "Started bot" : "Failed to start bot"); } catch (Bot.StartupException ignored) { addInfo("Did not start bot - bot already running"); } event.consume(); }); controller.botStop.setOnAction(event -> { addInfo(Bot.Control.shutdown(true) ? "Bot stopped" : "Did not stop bot - bot not running"); event.consume(); }); controller.botRestart.setOnAction(event -> { addInfo(Bot.Control.restart() ? "Restarted bot" : "Failed to restart bot"); event.consume(); }); controller.webOpen.setOnAction(event -> { openWebInterfaceInBrowser(); event.consume(); }); } private void setDialogPaneStyle(DialogPane dialogPane) { URL resource = getClass().getClassLoader().getResource("style.css"); if (resource != null) { dialogPane.getStylesheets().add(resource.toExternalForm()); } else { App.logger.error("Unable to get style sheet for alerts."); } } private void openWebInterfaceInBrowser() { this.getHostServices().showDocument("http://127.0.0.1:" + Configs.getWebConfig().getPortNumber()); } private void exitPrompt() { } private void checkForNewRelease() { if (Configs.getGeneralConfig().isUpdateChecking() && (AppVersion.latest().compareTo(App.VERSION) > 0) && (AppVersion.latest().type == Version.Type.RELEASE)) { Alert alert = new Alert(Alert.AlertType.INFORMATION); alert.setTitle("New Release Available"); alert.setHeaderText("New Release Available: OTB Project " + AppVersion.latest()); alert.setContentText("Version " + AppVersion.latest() + " of OTB Project is now available!" + "\n\nPress \"Get New Release\" or go to" + "\nhttps://github.com/OTBProject/OTBProject/releases/latest" + "\nto get the new release." + "\n\nPressing \"Don't Ask Again\" will prevent notifications " + "\nfor all future releases of OTB Project."); DialogPane dialogPane = alert.getDialogPane(); setDialogPaneStyle(dialogPane); ButtonType buttonTypeDontAskAgain = new ButtonType("Don't Ask Again", ButtonBar.ButtonData.LEFT); ButtonType buttonTypeGetRelease = new ButtonType("Get New Release", ButtonBar.ButtonData.FINISH); ButtonType buttonTypeIgnoreOnce = new ButtonType("Ignore Once", ButtonBar.ButtonData.FINISH); alert.getButtonTypes().setAll(buttonTypeDontAskAgain, buttonTypeGetRelease, buttonTypeIgnoreOnce); GuiUtils.setDefaultButton(alert, buttonTypeGetRelease); alert.initStyle(StageStyle.UNDECORATED); alert.showAndWait().ifPresent(buttonType -> { if (buttonType == buttonTypeDontAskAgain) { Configs.getGeneralConfig().setUpdateChecking(false); Configs.writeGeneralConfig(); } else if (buttonType == buttonTypeGetRelease) { this.getHostServices().showDocument("https://github.com/OTBProject/OTBProject/releases/latest"); } }); } } }
src/main/java/com/github/otbproject/otbproject/gui/GuiApplication.java
package com.github.otbproject.otbproject.gui; import com.github.otbproject.otbproject.App; import com.github.otbproject.otbproject.bot.Bot; import com.github.otbproject.otbproject.config.Configs; import com.github.otbproject.otbproject.fs.FSUtil; import com.github.otbproject.otbproject.util.Util; import com.github.otbproject.otbproject.util.version.AppVersion; import com.github.otbproject.otbproject.util.version.Version; import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.Alert; import javafx.scene.control.ButtonBar; import javafx.scene.control.ButtonType; import javafx.scene.control.DialogPane; import javafx.scene.image.Image; import javafx.scene.text.Font; import javafx.stage.Stage; import javafx.stage.StageStyle; import org.apache.commons.io.input.Tailer; import org.apache.commons.io.input.TailerListenerAdapter; import java.awt.*; import java.io.File; import java.io.IOException; import java.net.URL; public class GuiApplication extends Application { private static GuiController controller; private Tailer tailer; /** * The main entry point for all JavaFX applications. * The start method is called after the init method has returned, * and after the system is ready for the application to begin running. * <p> * NOTE: This method is called on the JavaFX Application Thread. * </p> * * @param primaryStage the primary stage for this application, onto which * the application scene can be set. The primary stage will be embedded in * the browser if the application was launched as an applet. * Applications may create other stages, if needed, but they will not be * primary stages and will not be embedded in the browser. */ @Override public void start(Stage primaryStage) throws Exception { Font.loadFont(getClass().getClassLoader().getResourceAsStream("UbuntuMono-R.ttf"), 12); Font.loadFont(getClass().getClassLoader().getResourceAsStream("Ubuntu-R.ttf"), 12); FXMLLoader loader = new FXMLLoader(getClass().getClassLoader().getResource("console.fxml")); Parent start = loader.load(); primaryStage.setScene(new Scene(start, 1200, 515)); primaryStage.setResizable(false); primaryStage.setTitle("OTBProject"); primaryStage.getIcons().add(new Image("http://otbproject.github.io/images/logo.png")); primaryStage.setOnCloseRequest(t -> { Alert alert = new Alert(Alert.AlertType.WARNING); alert.setTitle("Confirm Close"); alert.setHeaderText("WARNING: \"Close Window\" DOES NOT STOP THE BOT."); alert.setContentText("Closing this window without exiting may make it difficult to stop the bot.\nPress \"Exit\" to stop the bot and exit.\nPress \"Cancel\" to keep the window open."); DialogPane dialogPane = alert.getDialogPane(); setDialogPaneStyle(dialogPane); ButtonType buttonTypeCloseNoExit = new ButtonType("Close Window", ButtonBar.ButtonData.LEFT); ButtonType buttonTypeExit = new ButtonType("Exit", ButtonBar.ButtonData.FINISH); ButtonType buttonTypeCancel = new ButtonType("Cancel", ButtonBar.ButtonData.FINISH); alert.getButtonTypes().setAll(buttonTypeCloseNoExit, buttonTypeExit, buttonTypeCancel); GuiUtils.setDefaultButton(alert, buttonTypeExit); alert.initStyle(StageStyle.UNDECORATED); alert.showAndWait().ifPresent(buttonType -> { if (buttonType == buttonTypeCloseNoExit) { primaryStage.hide(); tailer.stop(); } else if (buttonType == buttonTypeExit) { App.logger.info("Stopping the process"); if (Bot.getBot() != null && Bot.getBot().isConnected()) { Bot.getBot().shutdown(); } App.logger.info("Process Stopped, Goodbye"); System.exit(0); } else { t.consume(); } }); }); controller = loader.<GuiController>getController(); setUpMenus(); controller.cliOutput.appendText("> "); controller.commandsInput.setEditable(false); controller.commandsOutput.appendText("Type \"help\" for a list of commands.\nThe PID of the bot is probably " + App.PID + ", if you are using an Oracle JVM, but it may be different, especially if you are using a different JVM. Be careful stopping the bot using this PID."); File logFile = new File(FSUtil.logsDir() + File.separator + "console.log"); tailer = Tailer.create(logFile, new CustomTailer(), 250); controller.readHistory(); primaryStage.show(); checkForNewRelease(); } public static void start(String[] args) { launch(args); } public static void setInputActive() { GuiUtils.runSafe(() -> { controller.commandsInput.setEditable(true); controller.commandsInput.setPromptText("Enter command here..."); }); } public static void addInfo(String text) { GuiUtils.runSafe(() -> controller.commandsOutput.appendText("\n\n" + text)); } public static void clearLog() { GuiUtils.runSafe(controller.logOutput::clear); } public static void clearInfo() { GuiUtils.runSafe(controller.commandsOutput::clear); } public static void clearCliOutput() { GuiUtils.runSafe(controller.cliOutput::clear); } public static void clearHistory() { GuiUtils.runSafe(() -> { controller.history.clear(); controller.historyPointer = 0; controller.writeHistory(); }); } static class CustomTailer extends TailerListenerAdapter { @Override public void handle(String line) { GuiUtils.runSafe(() -> controller.logOutput.appendText(line + "\n")); } } private void setUpMenus() { controller.openBaseDir.setOnAction(event -> { Util.getSingleThreadExecutor("file-explorer-%d").execute(() -> { try { Desktop.getDesktop().open(new File(FSUtil.getBaseDir())); } catch (IOException e) { App.logger.catching(e); } }); event.consume(); }); controller.botStart.setOnAction(event -> { try { addInfo(Bot.Control.startup() ? "Started bot" : "Failed to start bot"); } catch (Bot.StartupException ignored) { addInfo("Did not start bot - bot already running"); } event.consume(); }); controller.botStop.setOnAction(event -> { addInfo(Bot.Control.shutdown(true) ? "Bot stopped" : "Did not stop bot - bot not running"); event.consume(); }); controller.botRestart.setOnAction(event -> { addInfo(Bot.Control.restart() ? "Restarted bot" : "Failed to restart bot"); event.consume(); }); controller.webOpen.setOnAction(event -> { openWebInterfaceInBrowser(); event.consume(); }); } private void setDialogPaneStyle(DialogPane dialogPane) { URL resource = getClass().getClassLoader().getResource("style.css"); if (resource != null) { dialogPane.getStylesheets().add(resource.toExternalForm()); } else { App.logger.error("Unable to get style sheet for alerts."); } } private void openWebInterfaceInBrowser() { this.getHostServices().showDocument("http://127.0.0.1:" + Configs.getWebConfig().getPortNumber()); } private void checkForNewRelease() { if (Configs.getGeneralConfig().isUpdateChecking() && (AppVersion.latest().compareTo(App.VERSION) > 0) && (AppVersion.latest().type == Version.Type.RELEASE)) { Alert alert = new Alert(Alert.AlertType.INFORMATION); alert.setTitle("New Release Available"); alert.setHeaderText("New Release Available: OTB Project " + AppVersion.latest()); alert.setContentText("Version " + AppVersion.latest() + " of OTB Project is now available!" + "\n\nPress \"Get New Release\" or go to" + "\nhttps://github.com/OTBProject/OTBProject/releases/latest" + "\nto get the new release." + "\n\nPressing \"Don't Ask Again\" will prevent notifications " + "\nfor all future releases of OTB Project."); DialogPane dialogPane = alert.getDialogPane(); setDialogPaneStyle(dialogPane); ButtonType buttonTypeDontAskAgain = new ButtonType("Don't Ask Again", ButtonBar.ButtonData.LEFT); ButtonType buttonTypeGetRelease = new ButtonType("Get New Release", ButtonBar.ButtonData.FINISH); ButtonType buttonTypeIgnoreOnce = new ButtonType("Ignore Once", ButtonBar.ButtonData.FINISH); alert.getButtonTypes().setAll(buttonTypeDontAskAgain, buttonTypeGetRelease, buttonTypeIgnoreOnce); GuiUtils.setDefaultButton(alert, buttonTypeGetRelease); alert.initStyle(StageStyle.UNDECORATED); alert.showAndWait().ifPresent(buttonType -> { if (buttonType == buttonTypeDontAskAgain) { Configs.getGeneralConfig().setUpdateChecking(false); Configs.writeGeneralConfig(); } else if (buttonType == buttonTypeGetRelease) { this.getHostServices().showDocument("https://github.com/OTBProject/OTBProject/releases/latest"); } }); } } }
Tweaked naming and event consuming for close window alert in GuiApplication.
src/main/java/com/github/otbproject/otbproject/gui/GuiApplication.java
Tweaked naming and event consuming for close window alert in GuiApplication.
Java
apache-2.0
e0a271d74ecc4eea768b81d7262ae28355ec752a
0
mehulsbhatt/wasync,mehulsbhatt/wasync,ricardojlrufino/wasync,ricardojlrufino/wasync
/* * Copyright 2012 Jeanfrancois Arcand * * 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.atmosphere.wasync.util; import com.ning.http.client.AsyncHttpClient; import org.atmosphere.wasync.Client; import org.atmosphere.wasync.ClientFactory; import org.atmosphere.wasync.Function; import org.atmosphere.wasync.Request; import org.atmosphere.wasync.RequestBuilder; import org.atmosphere.wasync.Socket; import java.io.IOException; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; /** * A utility class that can be used to load a WebSocket enabled Server * * @author jeanfrancois Arcand */ public class WebSocketLoadTest { public static void main(String[] s) throws InterruptedException, IOException { if (s.length == 0) { s = new String[]{"500","1000","http://127.0.0.1:8080/chat"}; } final int clientNum = Integer.valueOf(s[0]); final int messageNum = Integer.valueOf(s[1]); String url = s[2]; System.out.println("Number of Client: " + clientNum); System.out.println("Number of Message: " + messageNum); final AsyncHttpClient c = new AsyncHttpClient(); final CountDownLatch l = new CountDownLatch(clientNum); final CountDownLatch messages = new CountDownLatch(messageNum * clientNum); Client client = ClientFactory.getDefault().newClient(); RequestBuilder request = client.newRequestBuilder(); request.method(Request.METHOD.GET).uri(url); request.transport(Request.TRANSPORT.WEBSOCKET); long clientCount = l.getCount(); final AtomicLong total = new AtomicLong(0); Socket[] sockets = new Socket[clientNum]; for (int i = 0; i < clientCount; i++) { final AtomicLong start = new AtomicLong(0); sockets[i] = client.create(client.newOptionsBuilder().runtime(c).build()) .on(new Function<Integer>() { @Override public void on(Integer statusCode) { start.set(System.currentTimeMillis()); l.countDown(); } }).on(new Function<String>() { int mCount = 0; @Override public void on(String s) { if (s.startsWith("message")) { String[] m = s.split("\n\r"); mCount += m.length; // System.out.println(messages.getCount()); messages.countDown(); if (mCount == messageNum) { total.addAndGet(System.currentTimeMillis() - start.get()); } } } }).on(new Function<Throwable>() { @Override public void on(Throwable t) { t.printStackTrace(); } }); } for (int i = 0; i < clientCount; i++) { sockets[i].open(request.build()); } l.await(60, TimeUnit.SECONDS); System.out.println("OK, all Connected: " + clientNum); Socket socket = client.create(client.newOptionsBuilder().runtime(c).build()); socket.open(request.build()); for (int i = 0; i < messageNum; i++ ) { socket.fire("message" + i); } messages.await(5, TimeUnit.MINUTES); socket.close(); c.close(); System.out.println("Total: " + (total.get()/clientCount)); } }
wasync/src/main/java/org/atmosphere/wasync/util/WebSocketLoadTest.java
/* * Copyright 2012 Jeanfrancois Arcand * * 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.atmosphere.wasync.util; import com.ning.http.client.AsyncHttpClient; import org.atmosphere.wasync.Client; import org.atmosphere.wasync.ClientFactory; import org.atmosphere.wasync.Function; import org.atmosphere.wasync.Request; import org.atmosphere.wasync.RequestBuilder; import org.atmosphere.wasync.Socket; import java.io.IOException; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; /** * A utility class that can be used to load a WebSocket enabled Server * * @author jeanfrancois Arcand */ public class WebSocketLoadTest { public static void main(String[] s) throws InterruptedException, IOException { if (s.length == 0) { s = new String[]{"500","1000","http://127.0.0.1:8080/atmosphere-chat/chat"}; } final int clientNum = Integer.valueOf(s[0]); final int messageNum = Integer.valueOf(s[1]); String url = s[2]; System.out.println("Number of Client: " + clientNum); System.out.println("Number of Message: " + messageNum); final AsyncHttpClient c = new AsyncHttpClient(); final CountDownLatch l = new CountDownLatch(clientNum); final CountDownLatch messages = new CountDownLatch(messageNum * clientNum); Client client = ClientFactory.getDefault().newClient(); RequestBuilder request = client.newRequestBuilder(); request.method(Request.METHOD.GET).uri(url); request.transport(Request.TRANSPORT.WEBSOCKET); long clientCount = l.getCount(); final AtomicLong total = new AtomicLong(0); for (int i = 0; i < clientCount; i++) { final AtomicLong start = new AtomicLong(0); Socket socket = client.create(client.newOptionsBuilder().runtime(c).build()); socket.on(new Function<Integer>() { @Override public void on(Integer statusCode) { start.set(System.currentTimeMillis()); l.countDown(); } }); socket.on(new Function<String>() { int mCount = 0; @Override public void on(String s) { if (s.startsWith("message")) { String[] m = s.split("\n\r"); mCount += m.length; System.out.println(messages.getCount()); messages.countDown(); if (mCount == messageNum) { total.addAndGet(System.currentTimeMillis() - start.get()); } } } }).on(new Function<Throwable>() { @Override public void on(Throwable t) { t.printStackTrace(); } }); socket.open(request.build()); } l.await(60, TimeUnit.SECONDS); System.out.println("OK, all Connected: " + clientNum); Socket socket = client.create(client.newOptionsBuilder().runtime(c).build()); socket.open(request.build()); for (int i = 0; i < messageNum; i++ ) { socket.fire("message" + i); } messages.await(5, TimeUnit.MINUTES); socket.close(); c.close(); System.out.println("Total: " + (total.get()/clientCount)); } }
Open all websocket at the same time
wasync/src/main/java/org/atmosphere/wasync/util/WebSocketLoadTest.java
Open all websocket at the same time
Java
apache-2.0
1c850e4a3bfe270cd0c64b85244a1447a40ba067
0
liyiorg/weixin-popular,moyq5/weixin-popular
package weixin.popular.support.token; import java.util.Date; import java.util.HashMap; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * 默认第三方平台component_access_token信息存储类 * * @author Moyq5 * */ public class DefaultComponentStorage implements TokenStorage { private static final Logger logger = LoggerFactory.getLogger(DefaultComponentStorage.class); // 模拟数据库表对象,每个元素为条记录 private static Map<String, RowData> map = new HashMap<String, RowData>(); @Override public RefreshInfo getOverdue() { // 模拟查询表,获取最近一个需要刷的刷新令牌信息 RowData row = latest(); if (null == row) { return null; } ComponentRefreshInfo refresh = new ComponentRefreshInfo(); refresh.setAppId(row.getAppId()); refresh.setAppSecret(row.getAppSecret()); refresh.setVerifyTicket(row.getVerifyTicket()); return refresh; } @Override public long nextTime() { long nextTime = -1; // 模拟查表,获取下一个最快要到期的令牌的时间 RowData row = latest(); if (null != row) { nextTime = row.getOverdueTime(); } long curTime = new Date().getTime(); if (nextTime < curTime) { // 默认每间隔10分检查一次是否有令牌需要刷新,保证刷新线程持续正常进行 nextTime = curTime + 600000; } return nextTime; } @Override public void update(TokenInfo tokenInfo) { ComponentTokenInfo info = (ComponentTokenInfo)tokenInfo; // 模拟更新表记录 RowData old = map.get(info.getAppId()); RowData row = new RowData(); row.setAccessToken(info.getAccessToken()); row.setAppId(old.getAppId()); row.setAppSecret(old.getAppSecret()); row.setOverdueTime(new Date().getTime() + (info.getExpiresIn()-600) * 1000);// 根据有效时长计算过期日期, 比微信服务端提前10分钟 row.setVerifyTicket(old.getVerifyTicket()); map.put(old.getAppId(), row); } @Override public String getAccessToken(TokenType type, String componentAppId, String authorizerAppId, String openId) { // 模拟查询表记录并获取access_token值 RowData rd = map.get(componentAppId); if (null == rd) { logger.warn("第三方平台信息不存在:componentAppId={}", componentAppId); return null; } return map.get(componentAppId).getAccessToken(); } /** * 模拟查表,获取最快要到期的"1个"token * * @return */ private RowData latest() { long nextTime = -1; RowData row = null; for (Map.Entry<String, RowData> entry : map.entrySet()) { if (entry.getValue().getOverdueTime() < nextTime || nextTime == -1) { row = entry.getValue(); nextTime = row.getOverdueTime(); } } return row; } /** * 模拟数据库第三方平台应用信息表记录对象 * * @author Moyq5 * */ public static class RowData { private String appId;// 第三方平台应用appId private String appSecret;// 第三方平台应用appSecret private String verifyTicket;// 第三方平台应用verifyTicket private long overdueTime;// 令牌过期时间 private String accessToken;// 当前有效的授权令牌 public String getAppId() { return appId; } public void setAppId(String appId) { this.appId = appId; } public String getAppSecret() { return appSecret; } public void setAppSecret(String appSecret) { this.appSecret = appSecret; } public String getVerifyTicket() { return verifyTicket; } public void setVerifyTicket(String verifyTicket) { this.verifyTicket = verifyTicket; } public long getOverdueTime() { return overdueTime; } public void setOverdueTime(long overdueTime) { this.overdueTime = overdueTime; } public String getAccessToken() { return accessToken; } public void setAccessToken(String accessToken) { this.accessToken = accessToken; } } }
src/main/java/weixin/popular/support/token/DefaultComponentStorage.java
package weixin.popular.support.token; import java.util.Date; import java.util.HashMap; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * 默认第三方平台component_access_token信息存储类 * * @author Moyq5 * */ public class DefaultComponentStorage implements TokenStorage { private static final Logger logger = LoggerFactory.getLogger(DefaultComponentStorage.class); // 模拟数据库表对象,每个元素为条记录 public static Map<String, RowData> map = new HashMap<String, RowData>(); @Override public RefreshInfo getOverdue() { // 模拟查询表,获取最近一个需要刷的刷新令牌信息 RowData row = latest(); if (null == row) { return null; } ComponentRefreshInfo refresh = new ComponentRefreshInfo(); refresh.setAppId(row.getAppId()); refresh.setAppSecret(row.getAppSecret()); refresh.setVerifyTicket(row.getVerifyTicket()); return refresh; } @Override public long nextTime() { long nextTime = -1; // 模拟查表,获取下一个最快要到期的令牌的时间 RowData row = latest(); if (null != row) { nextTime = row.getOverdueTime(); } long curTime = new Date().getTime(); if (nextTime < curTime) { // 默认每间隔10分检查一次是否有令牌需要刷新,保证刷新线程持续正常进行 nextTime = curTime + 600000; } return nextTime; } @Override public void update(TokenInfo tokenInfo) { ComponentTokenInfo info = (ComponentTokenInfo)tokenInfo; // 模拟更新表记录 RowData old = map.get(info.getAppId()); RowData row = new RowData(); row.setAccessToken(info.getAccessToken()); row.setAppId(old.getAppId()); row.setAppSecret(old.getAppSecret()); row.setOverdueTime(new Date().getTime() + (info.getExpiresIn()-600) * 1000);// 根据有效时长计算过期日期, 比微信服务端提前10分钟 row.setVerifyTicket(old.getVerifyTicket()); map.put(old.getAppId(), row); } @Override public String getAccessToken(TokenType type, String componentAppId, String authorizerAppId, String openId) { // 模拟查询表记录并获取access_token值 RowData rd = map.get(componentAppId); if (null == rd) { logger.warn("第三方平台信息不存在:componentAppId={}", componentAppId); return null; } return map.get(componentAppId).getAccessToken(); } /** * 模拟查表,获取最快要到期的"1个"token * * @return */ private RowData latest() { long nextTime = -1; RowData row = null; for (Map.Entry<String, RowData> entry : map.entrySet()) { if (entry.getValue().getOverdueTime() < nextTime || nextTime == -1) { row = entry.getValue(); nextTime = row.getOverdueTime(); } } return row; } /** * 模拟数据库第三方平台应用信息表记录对象 * * @author Moyq5 * */ public static class RowData { private String appId;// 第三方平台应用appId private String appSecret;// 第三方平台应用appSecret private String verifyTicket;// 第三方平台应用verifyTicket private long overdueTime;// 令牌过期时间 private String accessToken;// 当前有效的授权令牌 public String getAppId() { return appId; } public void setAppId(String appId) { this.appId = appId; } public String getAppSecret() { return appSecret; } public void setAppSecret(String appSecret) { this.appSecret = appSecret; } public String getVerifyTicket() { return verifyTicket; } public void setVerifyTicket(String verifyTicket) { this.verifyTicket = verifyTicket; } public long getOverdueTime() { return overdueTime; } public void setOverdueTime(long overdueTime) { this.overdueTime = overdueTime; } public String getAccessToken() { return accessToken; } public void setAccessToken(String accessToken) { this.accessToken = accessToken; } } }
更新第三方平台component_access_token存储类DefaultComponentStorage
src/main/java/weixin/popular/support/token/DefaultComponentStorage.java
更新第三方平台component_access_token存储类DefaultComponentStorage