repo_name
stringlengths
7
104
file_path
stringlengths
13
198
context
stringlengths
67
7.15k
import_statement
stringlengths
16
4.43k
code
stringlengths
40
6.98k
prompt
stringlengths
227
8.27k
next_line
stringlengths
8
795
el-groucho/jsRules
src/test/java/org/grouchotools/jsrules/loader/ResponseLoaderTest.java
// Path: src/main/java/org/grouchotools/jsrules/config/ResponseConfig.java // public class ResponseConfig extends JsonBean implements Config { // private String response; // private String responseClass; // // public ResponseConfig() { // // } // // public ResponseConfig(String response, String responseClass) { // this.response = response; // this.responseClass = responseClass; // } // // public String getResponse() { // return response; // } // // public void setResponse(String response) { // this.response = response; // } // // public String getResponseClass() { // return responseClass; // } // // public void setResponseClass(String responseClass) { // this.responseClass = responseClass; // } // // } // // Path: src/main/java/org/grouchotools/jsrules/exception/InvalidConfigException.java // public class InvalidConfigException extends JsRulesException { // // public InvalidConfigException() { // } // // public InvalidConfigException(String message) { // super(message); // } // // public InvalidConfigException(String message, Throwable cause) { // super(message, cause); // } // // public InvalidConfigException(Throwable cause) { // super(cause); // } // // public InvalidConfigException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // // } // // Path: src/main/java/org/grouchotools/jsrules/loader/impl/ResponseLoaderImpl.java // public class ResponseLoaderImpl<T> implements ResponseLoader<T> { // // /** // * // * @param config // * @return // * @throws org.grouchotools.jsrules.exception.InvalidConfigException // */ // @Override // public T load(ResponseConfig config) throws InvalidConfigException { // if (config == null || config.getResponseClass() == null) { // throw new InvalidConfigException("Response class must not be null"); // } // String responseClassName = config.getResponseClass().toUpperCase(); // ClassHandler handler; // try { // handler = ClassHandler.valueOf(responseClassName); // } catch (IllegalArgumentException ex) { // throw new InvalidConfigException(responseClassName+" is not a supported class", ex); // } // // String responseValue = config.getResponse(); // T response; // try { // response = handler.convertString(responseValue); // } catch (ClassHandlerException|IllegalArgumentException ex) { // throw new InvalidConfigException(responseValue+" is not a valid "+responseClassName, ex); // } // // return response; // } // // }
import org.grouchotools.jsrules.config.ResponseConfig; import org.grouchotools.jsrules.exception.InvalidConfigException; import org.grouchotools.jsrules.loader.impl.ResponseLoaderImpl; import org.junit.*; import org.junit.rules.ExpectedException; import static org.junit.Assert.assertEquals;
/* * The MIT License * * Copyright 2015 Paul. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.grouchotools.jsrules.loader; /** * * @author Paul */ public class ResponseLoaderTest { @Rule public ExpectedException exception= ExpectedException.none(); private final ResponseLoader responseLoader = new ResponseLoaderImpl(); public ResponseLoaderTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } @Test public void loadResponseTest() throws Exception { ResponseConfig responseConfig = new ResponseConfig("25", "long"); assertEquals(25l, responseLoader.load(responseConfig)); } @Test public void loadResponseInvalidClassTest() throws Exception {
// Path: src/main/java/org/grouchotools/jsrules/config/ResponseConfig.java // public class ResponseConfig extends JsonBean implements Config { // private String response; // private String responseClass; // // public ResponseConfig() { // // } // // public ResponseConfig(String response, String responseClass) { // this.response = response; // this.responseClass = responseClass; // } // // public String getResponse() { // return response; // } // // public void setResponse(String response) { // this.response = response; // } // // public String getResponseClass() { // return responseClass; // } // // public void setResponseClass(String responseClass) { // this.responseClass = responseClass; // } // // } // // Path: src/main/java/org/grouchotools/jsrules/exception/InvalidConfigException.java // public class InvalidConfigException extends JsRulesException { // // public InvalidConfigException() { // } // // public InvalidConfigException(String message) { // super(message); // } // // public InvalidConfigException(String message, Throwable cause) { // super(message, cause); // } // // public InvalidConfigException(Throwable cause) { // super(cause); // } // // public InvalidConfigException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // // } // // Path: src/main/java/org/grouchotools/jsrules/loader/impl/ResponseLoaderImpl.java // public class ResponseLoaderImpl<T> implements ResponseLoader<T> { // // /** // * // * @param config // * @return // * @throws org.grouchotools.jsrules.exception.InvalidConfigException // */ // @Override // public T load(ResponseConfig config) throws InvalidConfigException { // if (config == null || config.getResponseClass() == null) { // throw new InvalidConfigException("Response class must not be null"); // } // String responseClassName = config.getResponseClass().toUpperCase(); // ClassHandler handler; // try { // handler = ClassHandler.valueOf(responseClassName); // } catch (IllegalArgumentException ex) { // throw new InvalidConfigException(responseClassName+" is not a supported class", ex); // } // // String responseValue = config.getResponse(); // T response; // try { // response = handler.convertString(responseValue); // } catch (ClassHandlerException|IllegalArgumentException ex) { // throw new InvalidConfigException(responseValue+" is not a valid "+responseClassName, ex); // } // // return response; // } // // } // Path: src/test/java/org/grouchotools/jsrules/loader/ResponseLoaderTest.java import org.grouchotools.jsrules.config.ResponseConfig; import org.grouchotools.jsrules.exception.InvalidConfigException; import org.grouchotools.jsrules.loader.impl.ResponseLoaderImpl; import org.junit.*; import org.junit.rules.ExpectedException; import static org.junit.Assert.assertEquals; /* * The MIT License * * Copyright 2015 Paul. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.grouchotools.jsrules.loader; /** * * @author Paul */ public class ResponseLoaderTest { @Rule public ExpectedException exception= ExpectedException.none(); private final ResponseLoader responseLoader = new ResponseLoaderImpl(); public ResponseLoaderTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } @Test public void loadResponseTest() throws Exception { ResponseConfig responseConfig = new ResponseConfig("25", "long"); assertEquals(25l, responseLoader.load(responseConfig)); } @Test public void loadResponseInvalidClassTest() throws Exception {
exception.expect(InvalidConfigException.class);
el-groucho/jsRules
src/main/java/org/grouchotools/jsrules/impl/FirstTrueRulesetExecutorImpl.java
// Path: src/main/java/org/grouchotools/jsrules/Parameter.java // public class Parameter<T> extends JsonBean { // public Parameter(String name, Class<T> klasse) { // this.name = name; // this.klasse = klasse; // this.staticValue = null; // } // // public Parameter(String name, Class<T> klasse, T staticValue) { // this.name = name; // this.klasse = klasse; // this.staticValue = staticValue; // } // // private final String name; // private final Class<T> klasse; // private final T staticValue; // // public String getName() { // return name; // } // // public Class<T> getKlasse() { // return klasse; // } // // public T getStaticValue() { // return staticValue; // } // // } // // Path: src/main/java/org/grouchotools/jsrules/RuleExecutor.java // public abstract class RuleExecutor<T> extends Executor { // public abstract T execute(Object leftParameter, Object rightParameter) throws InvalidParameterException; // // public abstract T execute(Object leftParameter) throws InvalidParameterException; // // public abstract Parameter getLeftParameter(); // // public abstract Parameter getRightParameter(); // // public abstract Rule getRule(); // } // // Path: src/main/java/org/grouchotools/jsrules/RulesetExecutor.java // public abstract class RulesetExecutor<T> extends Executor { // public abstract T execute(Map<String, Object> parameters) throws InvalidParameterException; // // public abstract String getName(); // } // // Path: src/main/java/org/grouchotools/jsrules/exception/InvalidParameterException.java // public class InvalidParameterException extends JsRulesException { // // public InvalidParameterException() { // } // // public InvalidParameterException(String message) { // super(message); // } // // public InvalidParameterException(String message, Throwable cause) { // super(message, cause); // } // // public InvalidParameterException(Throwable cause) { // super(cause); // } // // public InvalidParameterException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // // }
import org.grouchotools.jsrules.Parameter; import org.grouchotools.jsrules.RuleExecutor; import org.grouchotools.jsrules.RulesetExecutor; import org.grouchotools.jsrules.exception.InvalidParameterException; import java.util.List; import java.util.Map;
/* * The MIT License * * Copyright 2015 Paul. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.grouchotools.jsrules.impl; /** * This executor evaluates a series of rules in order. * <p/> * It returns the response of the first rule that evaluates true. * <p/> * If none of the rules are true, it returns a null. * * @param <T> * @author Paul */ public class FirstTrueRulesetExecutorImpl<T> extends RulesetExecutor<T> { private final List<RuleExecutor<T>> ruleSet; private String name; public FirstTrueRulesetExecutorImpl(String name, List<RuleExecutor<T>> ruleSet) { this.name = name; this.ruleSet = ruleSet; } @Override
// Path: src/main/java/org/grouchotools/jsrules/Parameter.java // public class Parameter<T> extends JsonBean { // public Parameter(String name, Class<T> klasse) { // this.name = name; // this.klasse = klasse; // this.staticValue = null; // } // // public Parameter(String name, Class<T> klasse, T staticValue) { // this.name = name; // this.klasse = klasse; // this.staticValue = staticValue; // } // // private final String name; // private final Class<T> klasse; // private final T staticValue; // // public String getName() { // return name; // } // // public Class<T> getKlasse() { // return klasse; // } // // public T getStaticValue() { // return staticValue; // } // // } // // Path: src/main/java/org/grouchotools/jsrules/RuleExecutor.java // public abstract class RuleExecutor<T> extends Executor { // public abstract T execute(Object leftParameter, Object rightParameter) throws InvalidParameterException; // // public abstract T execute(Object leftParameter) throws InvalidParameterException; // // public abstract Parameter getLeftParameter(); // // public abstract Parameter getRightParameter(); // // public abstract Rule getRule(); // } // // Path: src/main/java/org/grouchotools/jsrules/RulesetExecutor.java // public abstract class RulesetExecutor<T> extends Executor { // public abstract T execute(Map<String, Object> parameters) throws InvalidParameterException; // // public abstract String getName(); // } // // Path: src/main/java/org/grouchotools/jsrules/exception/InvalidParameterException.java // public class InvalidParameterException extends JsRulesException { // // public InvalidParameterException() { // } // // public InvalidParameterException(String message) { // super(message); // } // // public InvalidParameterException(String message, Throwable cause) { // super(message, cause); // } // // public InvalidParameterException(Throwable cause) { // super(cause); // } // // public InvalidParameterException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // // } // Path: src/main/java/org/grouchotools/jsrules/impl/FirstTrueRulesetExecutorImpl.java import org.grouchotools.jsrules.Parameter; import org.grouchotools.jsrules.RuleExecutor; import org.grouchotools.jsrules.RulesetExecutor; import org.grouchotools.jsrules.exception.InvalidParameterException; import java.util.List; import java.util.Map; /* * The MIT License * * Copyright 2015 Paul. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.grouchotools.jsrules.impl; /** * This executor evaluates a series of rules in order. * <p/> * It returns the response of the first rule that evaluates true. * <p/> * If none of the rules are true, it returns a null. * * @param <T> * @author Paul */ public class FirstTrueRulesetExecutorImpl<T> extends RulesetExecutor<T> { private final List<RuleExecutor<T>> ruleSet; private String name; public FirstTrueRulesetExecutorImpl(String name, List<RuleExecutor<T>> ruleSet) { this.name = name; this.ruleSet = ruleSet; } @Override
public T execute(Map<String, Object> parameters) throws InvalidParameterException {
el-groucho/jsRules
src/main/java/org/grouchotools/jsrules/impl/FirstTrueRulesetExecutorImpl.java
// Path: src/main/java/org/grouchotools/jsrules/Parameter.java // public class Parameter<T> extends JsonBean { // public Parameter(String name, Class<T> klasse) { // this.name = name; // this.klasse = klasse; // this.staticValue = null; // } // // public Parameter(String name, Class<T> klasse, T staticValue) { // this.name = name; // this.klasse = klasse; // this.staticValue = staticValue; // } // // private final String name; // private final Class<T> klasse; // private final T staticValue; // // public String getName() { // return name; // } // // public Class<T> getKlasse() { // return klasse; // } // // public T getStaticValue() { // return staticValue; // } // // } // // Path: src/main/java/org/grouchotools/jsrules/RuleExecutor.java // public abstract class RuleExecutor<T> extends Executor { // public abstract T execute(Object leftParameter, Object rightParameter) throws InvalidParameterException; // // public abstract T execute(Object leftParameter) throws InvalidParameterException; // // public abstract Parameter getLeftParameter(); // // public abstract Parameter getRightParameter(); // // public abstract Rule getRule(); // } // // Path: src/main/java/org/grouchotools/jsrules/RulesetExecutor.java // public abstract class RulesetExecutor<T> extends Executor { // public abstract T execute(Map<String, Object> parameters) throws InvalidParameterException; // // public abstract String getName(); // } // // Path: src/main/java/org/grouchotools/jsrules/exception/InvalidParameterException.java // public class InvalidParameterException extends JsRulesException { // // public InvalidParameterException() { // } // // public InvalidParameterException(String message) { // super(message); // } // // public InvalidParameterException(String message, Throwable cause) { // super(message, cause); // } // // public InvalidParameterException(Throwable cause) { // super(cause); // } // // public InvalidParameterException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // // }
import org.grouchotools.jsrules.Parameter; import org.grouchotools.jsrules.RuleExecutor; import org.grouchotools.jsrules.RulesetExecutor; import org.grouchotools.jsrules.exception.InvalidParameterException; import java.util.List; import java.util.Map;
/* * The MIT License * * Copyright 2015 Paul. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.grouchotools.jsrules.impl; /** * This executor evaluates a series of rules in order. * <p/> * It returns the response of the first rule that evaluates true. * <p/> * If none of the rules are true, it returns a null. * * @param <T> * @author Paul */ public class FirstTrueRulesetExecutorImpl<T> extends RulesetExecutor<T> { private final List<RuleExecutor<T>> ruleSet; private String name; public FirstTrueRulesetExecutorImpl(String name, List<RuleExecutor<T>> ruleSet) { this.name = name; this.ruleSet = ruleSet; } @Override public T execute(Map<String, Object> parameters) throws InvalidParameterException { T result = null; for (RuleExecutor<T> rule : ruleSet) {
// Path: src/main/java/org/grouchotools/jsrules/Parameter.java // public class Parameter<T> extends JsonBean { // public Parameter(String name, Class<T> klasse) { // this.name = name; // this.klasse = klasse; // this.staticValue = null; // } // // public Parameter(String name, Class<T> klasse, T staticValue) { // this.name = name; // this.klasse = klasse; // this.staticValue = staticValue; // } // // private final String name; // private final Class<T> klasse; // private final T staticValue; // // public String getName() { // return name; // } // // public Class<T> getKlasse() { // return klasse; // } // // public T getStaticValue() { // return staticValue; // } // // } // // Path: src/main/java/org/grouchotools/jsrules/RuleExecutor.java // public abstract class RuleExecutor<T> extends Executor { // public abstract T execute(Object leftParameter, Object rightParameter) throws InvalidParameterException; // // public abstract T execute(Object leftParameter) throws InvalidParameterException; // // public abstract Parameter getLeftParameter(); // // public abstract Parameter getRightParameter(); // // public abstract Rule getRule(); // } // // Path: src/main/java/org/grouchotools/jsrules/RulesetExecutor.java // public abstract class RulesetExecutor<T> extends Executor { // public abstract T execute(Map<String, Object> parameters) throws InvalidParameterException; // // public abstract String getName(); // } // // Path: src/main/java/org/grouchotools/jsrules/exception/InvalidParameterException.java // public class InvalidParameterException extends JsRulesException { // // public InvalidParameterException() { // } // // public InvalidParameterException(String message) { // super(message); // } // // public InvalidParameterException(String message, Throwable cause) { // super(message, cause); // } // // public InvalidParameterException(Throwable cause) { // super(cause); // } // // public InvalidParameterException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // // } // Path: src/main/java/org/grouchotools/jsrules/impl/FirstTrueRulesetExecutorImpl.java import org.grouchotools.jsrules.Parameter; import org.grouchotools.jsrules.RuleExecutor; import org.grouchotools.jsrules.RulesetExecutor; import org.grouchotools.jsrules.exception.InvalidParameterException; import java.util.List; import java.util.Map; /* * The MIT License * * Copyright 2015 Paul. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.grouchotools.jsrules.impl; /** * This executor evaluates a series of rules in order. * <p/> * It returns the response of the first rule that evaluates true. * <p/> * If none of the rules are true, it returns a null. * * @param <T> * @author Paul */ public class FirstTrueRulesetExecutorImpl<T> extends RulesetExecutor<T> { private final List<RuleExecutor<T>> ruleSet; private String name; public FirstTrueRulesetExecutorImpl(String name, List<RuleExecutor<T>> ruleSet) { this.name = name; this.ruleSet = ruleSet; } @Override public T execute(Map<String, Object> parameters) throws InvalidParameterException { T result = null; for (RuleExecutor<T> rule : ruleSet) {
Parameter left = rule.getLeftParameter();
el-groucho/jsRules
src/main/java/org/grouchotools/jsrules/impl/FirstTrueRulesetListExecutorImpl.java
// Path: src/main/java/org/grouchotools/jsrules/RulesetExecutor.java // public abstract class RulesetExecutor<T> extends Executor { // public abstract T execute(Map<String, Object> parameters) throws InvalidParameterException; // // public abstract String getName(); // } // // Path: src/main/java/org/grouchotools/jsrules/RulesetListExecutor.java // public abstract class RulesetListExecutor<T> extends RulesetExecutor<T> { // } // // Path: src/main/java/org/grouchotools/jsrules/exception/InvalidParameterException.java // public class InvalidParameterException extends JsRulesException { // // public InvalidParameterException() { // } // // public InvalidParameterException(String message) { // super(message); // } // // public InvalidParameterException(String message, Throwable cause) { // super(message, cause); // } // // public InvalidParameterException(Throwable cause) { // super(cause); // } // // public InvalidParameterException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // // }
import org.grouchotools.jsrules.RulesetExecutor; import org.grouchotools.jsrules.RulesetListExecutor; import org.grouchotools.jsrules.exception.InvalidParameterException; import java.util.List; import java.util.Map;
/* * The MIT License * * Copyright 2015 Paul. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.grouchotools.jsrules.impl; /** * This executor evaluates a series of rulesets in order. * <p/> * If all rulesets evaluate as true, it returns the given response. Otherwise, the * response is null. * * @param <T> * @author Paul */ public class FirstTrueRulesetListExecutorImpl<T> extends RulesetListExecutor<T> { private final List<RulesetExecutor<T>> rulesetList; private final String name; public FirstTrueRulesetListExecutorImpl(String name, List<RulesetExecutor<T>> rulesetList) { this.name = name; this.rulesetList = rulesetList; } @Override
// Path: src/main/java/org/grouchotools/jsrules/RulesetExecutor.java // public abstract class RulesetExecutor<T> extends Executor { // public abstract T execute(Map<String, Object> parameters) throws InvalidParameterException; // // public abstract String getName(); // } // // Path: src/main/java/org/grouchotools/jsrules/RulesetListExecutor.java // public abstract class RulesetListExecutor<T> extends RulesetExecutor<T> { // } // // Path: src/main/java/org/grouchotools/jsrules/exception/InvalidParameterException.java // public class InvalidParameterException extends JsRulesException { // // public InvalidParameterException() { // } // // public InvalidParameterException(String message) { // super(message); // } // // public InvalidParameterException(String message, Throwable cause) { // super(message, cause); // } // // public InvalidParameterException(Throwable cause) { // super(cause); // } // // public InvalidParameterException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // // } // Path: src/main/java/org/grouchotools/jsrules/impl/FirstTrueRulesetListExecutorImpl.java import org.grouchotools.jsrules.RulesetExecutor; import org.grouchotools.jsrules.RulesetListExecutor; import org.grouchotools.jsrules.exception.InvalidParameterException; import java.util.List; import java.util.Map; /* * The MIT License * * Copyright 2015 Paul. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.grouchotools.jsrules.impl; /** * This executor evaluates a series of rulesets in order. * <p/> * If all rulesets evaluate as true, it returns the given response. Otherwise, the * response is null. * * @param <T> * @author Paul */ public class FirstTrueRulesetListExecutorImpl<T> extends RulesetListExecutor<T> { private final List<RulesetExecutor<T>> rulesetList; private final String name; public FirstTrueRulesetListExecutorImpl(String name, List<RulesetExecutor<T>> rulesetList) { this.name = name; this.rulesetList = rulesetList; } @Override
public T execute(Map<String, Object> parameters) throws InvalidParameterException {
el-groucho/jsRules
src/test/java/org/grouchotools/jsrules/loader/ParamLoaderTest.java
// Path: src/main/java/org/grouchotools/jsrules/Parameter.java // public class Parameter<T> extends JsonBean { // public Parameter(String name, Class<T> klasse) { // this.name = name; // this.klasse = klasse; // this.staticValue = null; // } // // public Parameter(String name, Class<T> klasse, T staticValue) { // this.name = name; // this.klasse = klasse; // this.staticValue = staticValue; // } // // private final String name; // private final Class<T> klasse; // private final T staticValue; // // public String getName() { // return name; // } // // public Class<T> getKlasse() { // return klasse; // } // // public T getStaticValue() { // return staticValue; // } // // } // // Path: src/main/java/org/grouchotools/jsrules/config/ParamConfig.java // public class ParamConfig extends JsonBean implements Config { // private String parameterName; // private String parameterClass; // private String parameterStaticValue; // // public ParamConfig() { // // } // // public ParamConfig(String parameterName, String parameterClass, // String parameterStaticValue) { // this.parameterName = parameterName; // this.parameterClass = parameterClass; // this.parameterStaticValue = parameterStaticValue; // } // // public String getParameterName() { // return parameterName; // } // // public void setParameterName(String parameterName) { // this.parameterName = parameterName; // } // // public String getParameterClass() { // return parameterClass; // } // // public void setParameterClass(String parameterClass) { // this.parameterClass = parameterClass; // } // // public String getParameterStaticValue() { // return parameterStaticValue; // } // // public void setParameterStaticValue(String parameterStaticValue) { // this.parameterStaticValue = parameterStaticValue; // } // // } // // Path: src/main/java/org/grouchotools/jsrules/exception/InvalidConfigException.java // public class InvalidConfigException extends JsRulesException { // // public InvalidConfigException() { // } // // public InvalidConfigException(String message) { // super(message); // } // // public InvalidConfigException(String message, Throwable cause) { // super(message, cause); // } // // public InvalidConfigException(Throwable cause) { // super(cause); // } // // public InvalidConfigException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // // } // // Path: src/main/java/org/grouchotools/jsrules/loader/impl/ParamLoaderImpl.java // public class ParamLoaderImpl implements ParamLoader { // // /** // * // * @param config // * @return // * @throws org.grouchotools.jsrules.exception.InvalidConfigException // */ // @Override // public Parameter load(ParamConfig config) throws InvalidConfigException { // if (config == null || config.getParameterClass() == null) { // throw new InvalidConfigException("Parameter class must not be null"); // } // String parameterClassName = config.getParameterClass().toUpperCase(); // ClassHandler handler; // try { // handler = ClassHandler.valueOf(parameterClassName); // } catch (IllegalArgumentException ex) { // throw new InvalidConfigException(parameterClassName+" is not a supported class", ex); // } // Class paramClass = handler.getMyClass(); // String paramStaticValue = config.getParameterStaticValue(); // Object paramStaticObject = null; // if (paramStaticValue != null) { // try { // paramStaticObject = handler.convertString(paramStaticValue); // } catch (ClassHandlerException|IllegalArgumentException ex) { // throw new InvalidConfigException(paramStaticValue+" is not a valid "+parameterClassName, ex); // } // } // return new Parameter(config.getParameterName(), paramClass, // paramStaticObject); // } // // }
import static org.junit.Assert.assertEquals; import org.grouchotools.jsrules.Parameter; import org.grouchotools.jsrules.config.ParamConfig; import org.grouchotools.jsrules.exception.InvalidConfigException; import org.grouchotools.jsrules.loader.impl.ParamLoaderImpl; import org.junit.*; import org.junit.rules.ExpectedException;
/* * The MIT License * * Copyright 2015 Paul. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.grouchotools.jsrules.loader; /** * * @author Paul */ public class ParamLoaderTest { @Rule public ExpectedException exception= ExpectedException.none();
// Path: src/main/java/org/grouchotools/jsrules/Parameter.java // public class Parameter<T> extends JsonBean { // public Parameter(String name, Class<T> klasse) { // this.name = name; // this.klasse = klasse; // this.staticValue = null; // } // // public Parameter(String name, Class<T> klasse, T staticValue) { // this.name = name; // this.klasse = klasse; // this.staticValue = staticValue; // } // // private final String name; // private final Class<T> klasse; // private final T staticValue; // // public String getName() { // return name; // } // // public Class<T> getKlasse() { // return klasse; // } // // public T getStaticValue() { // return staticValue; // } // // } // // Path: src/main/java/org/grouchotools/jsrules/config/ParamConfig.java // public class ParamConfig extends JsonBean implements Config { // private String parameterName; // private String parameterClass; // private String parameterStaticValue; // // public ParamConfig() { // // } // // public ParamConfig(String parameterName, String parameterClass, // String parameterStaticValue) { // this.parameterName = parameterName; // this.parameterClass = parameterClass; // this.parameterStaticValue = parameterStaticValue; // } // // public String getParameterName() { // return parameterName; // } // // public void setParameterName(String parameterName) { // this.parameterName = parameterName; // } // // public String getParameterClass() { // return parameterClass; // } // // public void setParameterClass(String parameterClass) { // this.parameterClass = parameterClass; // } // // public String getParameterStaticValue() { // return parameterStaticValue; // } // // public void setParameterStaticValue(String parameterStaticValue) { // this.parameterStaticValue = parameterStaticValue; // } // // } // // Path: src/main/java/org/grouchotools/jsrules/exception/InvalidConfigException.java // public class InvalidConfigException extends JsRulesException { // // public InvalidConfigException() { // } // // public InvalidConfigException(String message) { // super(message); // } // // public InvalidConfigException(String message, Throwable cause) { // super(message, cause); // } // // public InvalidConfigException(Throwable cause) { // super(cause); // } // // public InvalidConfigException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // // } // // Path: src/main/java/org/grouchotools/jsrules/loader/impl/ParamLoaderImpl.java // public class ParamLoaderImpl implements ParamLoader { // // /** // * // * @param config // * @return // * @throws org.grouchotools.jsrules.exception.InvalidConfigException // */ // @Override // public Parameter load(ParamConfig config) throws InvalidConfigException { // if (config == null || config.getParameterClass() == null) { // throw new InvalidConfigException("Parameter class must not be null"); // } // String parameterClassName = config.getParameterClass().toUpperCase(); // ClassHandler handler; // try { // handler = ClassHandler.valueOf(parameterClassName); // } catch (IllegalArgumentException ex) { // throw new InvalidConfigException(parameterClassName+" is not a supported class", ex); // } // Class paramClass = handler.getMyClass(); // String paramStaticValue = config.getParameterStaticValue(); // Object paramStaticObject = null; // if (paramStaticValue != null) { // try { // paramStaticObject = handler.convertString(paramStaticValue); // } catch (ClassHandlerException|IllegalArgumentException ex) { // throw new InvalidConfigException(paramStaticValue+" is not a valid "+parameterClassName, ex); // } // } // return new Parameter(config.getParameterName(), paramClass, // paramStaticObject); // } // // } // Path: src/test/java/org/grouchotools/jsrules/loader/ParamLoaderTest.java import static org.junit.Assert.assertEquals; import org.grouchotools.jsrules.Parameter; import org.grouchotools.jsrules.config.ParamConfig; import org.grouchotools.jsrules.exception.InvalidConfigException; import org.grouchotools.jsrules.loader.impl.ParamLoaderImpl; import org.junit.*; import org.junit.rules.ExpectedException; /* * The MIT License * * Copyright 2015 Paul. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.grouchotools.jsrules.loader; /** * * @author Paul */ public class ParamLoaderTest { @Rule public ExpectedException exception= ExpectedException.none();
private final ParamLoader paramLoader = new ParamLoaderImpl();
el-groucho/jsRules
src/test/java/org/grouchotools/jsrules/loader/ParamLoaderTest.java
// Path: src/main/java/org/grouchotools/jsrules/Parameter.java // public class Parameter<T> extends JsonBean { // public Parameter(String name, Class<T> klasse) { // this.name = name; // this.klasse = klasse; // this.staticValue = null; // } // // public Parameter(String name, Class<T> klasse, T staticValue) { // this.name = name; // this.klasse = klasse; // this.staticValue = staticValue; // } // // private final String name; // private final Class<T> klasse; // private final T staticValue; // // public String getName() { // return name; // } // // public Class<T> getKlasse() { // return klasse; // } // // public T getStaticValue() { // return staticValue; // } // // } // // Path: src/main/java/org/grouchotools/jsrules/config/ParamConfig.java // public class ParamConfig extends JsonBean implements Config { // private String parameterName; // private String parameterClass; // private String parameterStaticValue; // // public ParamConfig() { // // } // // public ParamConfig(String parameterName, String parameterClass, // String parameterStaticValue) { // this.parameterName = parameterName; // this.parameterClass = parameterClass; // this.parameterStaticValue = parameterStaticValue; // } // // public String getParameterName() { // return parameterName; // } // // public void setParameterName(String parameterName) { // this.parameterName = parameterName; // } // // public String getParameterClass() { // return parameterClass; // } // // public void setParameterClass(String parameterClass) { // this.parameterClass = parameterClass; // } // // public String getParameterStaticValue() { // return parameterStaticValue; // } // // public void setParameterStaticValue(String parameterStaticValue) { // this.parameterStaticValue = parameterStaticValue; // } // // } // // Path: src/main/java/org/grouchotools/jsrules/exception/InvalidConfigException.java // public class InvalidConfigException extends JsRulesException { // // public InvalidConfigException() { // } // // public InvalidConfigException(String message) { // super(message); // } // // public InvalidConfigException(String message, Throwable cause) { // super(message, cause); // } // // public InvalidConfigException(Throwable cause) { // super(cause); // } // // public InvalidConfigException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // // } // // Path: src/main/java/org/grouchotools/jsrules/loader/impl/ParamLoaderImpl.java // public class ParamLoaderImpl implements ParamLoader { // // /** // * // * @param config // * @return // * @throws org.grouchotools.jsrules.exception.InvalidConfigException // */ // @Override // public Parameter load(ParamConfig config) throws InvalidConfigException { // if (config == null || config.getParameterClass() == null) { // throw new InvalidConfigException("Parameter class must not be null"); // } // String parameterClassName = config.getParameterClass().toUpperCase(); // ClassHandler handler; // try { // handler = ClassHandler.valueOf(parameterClassName); // } catch (IllegalArgumentException ex) { // throw new InvalidConfigException(parameterClassName+" is not a supported class", ex); // } // Class paramClass = handler.getMyClass(); // String paramStaticValue = config.getParameterStaticValue(); // Object paramStaticObject = null; // if (paramStaticValue != null) { // try { // paramStaticObject = handler.convertString(paramStaticValue); // } catch (ClassHandlerException|IllegalArgumentException ex) { // throw new InvalidConfigException(paramStaticValue+" is not a valid "+parameterClassName, ex); // } // } // return new Parameter(config.getParameterName(), paramClass, // paramStaticObject); // } // // }
import static org.junit.Assert.assertEquals; import org.grouchotools.jsrules.Parameter; import org.grouchotools.jsrules.config.ParamConfig; import org.grouchotools.jsrules.exception.InvalidConfigException; import org.grouchotools.jsrules.loader.impl.ParamLoaderImpl; import org.junit.*; import org.junit.rules.ExpectedException;
/* * The MIT License * * Copyright 2015 Paul. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.grouchotools.jsrules.loader; /** * * @author Paul */ public class ParamLoaderTest { @Rule public ExpectedException exception= ExpectedException.none(); private final ParamLoader paramLoader = new ParamLoaderImpl(); private final String paramName = "param"; public ParamLoaderTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } @Test public void loadTest() throws Exception {
// Path: src/main/java/org/grouchotools/jsrules/Parameter.java // public class Parameter<T> extends JsonBean { // public Parameter(String name, Class<T> klasse) { // this.name = name; // this.klasse = klasse; // this.staticValue = null; // } // // public Parameter(String name, Class<T> klasse, T staticValue) { // this.name = name; // this.klasse = klasse; // this.staticValue = staticValue; // } // // private final String name; // private final Class<T> klasse; // private final T staticValue; // // public String getName() { // return name; // } // // public Class<T> getKlasse() { // return klasse; // } // // public T getStaticValue() { // return staticValue; // } // // } // // Path: src/main/java/org/grouchotools/jsrules/config/ParamConfig.java // public class ParamConfig extends JsonBean implements Config { // private String parameterName; // private String parameterClass; // private String parameterStaticValue; // // public ParamConfig() { // // } // // public ParamConfig(String parameterName, String parameterClass, // String parameterStaticValue) { // this.parameterName = parameterName; // this.parameterClass = parameterClass; // this.parameterStaticValue = parameterStaticValue; // } // // public String getParameterName() { // return parameterName; // } // // public void setParameterName(String parameterName) { // this.parameterName = parameterName; // } // // public String getParameterClass() { // return parameterClass; // } // // public void setParameterClass(String parameterClass) { // this.parameterClass = parameterClass; // } // // public String getParameterStaticValue() { // return parameterStaticValue; // } // // public void setParameterStaticValue(String parameterStaticValue) { // this.parameterStaticValue = parameterStaticValue; // } // // } // // Path: src/main/java/org/grouchotools/jsrules/exception/InvalidConfigException.java // public class InvalidConfigException extends JsRulesException { // // public InvalidConfigException() { // } // // public InvalidConfigException(String message) { // super(message); // } // // public InvalidConfigException(String message, Throwable cause) { // super(message, cause); // } // // public InvalidConfigException(Throwable cause) { // super(cause); // } // // public InvalidConfigException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // // } // // Path: src/main/java/org/grouchotools/jsrules/loader/impl/ParamLoaderImpl.java // public class ParamLoaderImpl implements ParamLoader { // // /** // * // * @param config // * @return // * @throws org.grouchotools.jsrules.exception.InvalidConfigException // */ // @Override // public Parameter load(ParamConfig config) throws InvalidConfigException { // if (config == null || config.getParameterClass() == null) { // throw new InvalidConfigException("Parameter class must not be null"); // } // String parameterClassName = config.getParameterClass().toUpperCase(); // ClassHandler handler; // try { // handler = ClassHandler.valueOf(parameterClassName); // } catch (IllegalArgumentException ex) { // throw new InvalidConfigException(parameterClassName+" is not a supported class", ex); // } // Class paramClass = handler.getMyClass(); // String paramStaticValue = config.getParameterStaticValue(); // Object paramStaticObject = null; // if (paramStaticValue != null) { // try { // paramStaticObject = handler.convertString(paramStaticValue); // } catch (ClassHandlerException|IllegalArgumentException ex) { // throw new InvalidConfigException(paramStaticValue+" is not a valid "+parameterClassName, ex); // } // } // return new Parameter(config.getParameterName(), paramClass, // paramStaticObject); // } // // } // Path: src/test/java/org/grouchotools/jsrules/loader/ParamLoaderTest.java import static org.junit.Assert.assertEquals; import org.grouchotools.jsrules.Parameter; import org.grouchotools.jsrules.config.ParamConfig; import org.grouchotools.jsrules.exception.InvalidConfigException; import org.grouchotools.jsrules.loader.impl.ParamLoaderImpl; import org.junit.*; import org.junit.rules.ExpectedException; /* * The MIT License * * Copyright 2015 Paul. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.grouchotools.jsrules.loader; /** * * @author Paul */ public class ParamLoaderTest { @Rule public ExpectedException exception= ExpectedException.none(); private final ParamLoader paramLoader = new ParamLoaderImpl(); private final String paramName = "param"; public ParamLoaderTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } @Test public void loadTest() throws Exception {
ParamConfig paramConfig = new ParamConfig(paramName, "long", "10");
el-groucho/jsRules
src/test/java/org/grouchotools/jsrules/loader/ParamLoaderTest.java
// Path: src/main/java/org/grouchotools/jsrules/Parameter.java // public class Parameter<T> extends JsonBean { // public Parameter(String name, Class<T> klasse) { // this.name = name; // this.klasse = klasse; // this.staticValue = null; // } // // public Parameter(String name, Class<T> klasse, T staticValue) { // this.name = name; // this.klasse = klasse; // this.staticValue = staticValue; // } // // private final String name; // private final Class<T> klasse; // private final T staticValue; // // public String getName() { // return name; // } // // public Class<T> getKlasse() { // return klasse; // } // // public T getStaticValue() { // return staticValue; // } // // } // // Path: src/main/java/org/grouchotools/jsrules/config/ParamConfig.java // public class ParamConfig extends JsonBean implements Config { // private String parameterName; // private String parameterClass; // private String parameterStaticValue; // // public ParamConfig() { // // } // // public ParamConfig(String parameterName, String parameterClass, // String parameterStaticValue) { // this.parameterName = parameterName; // this.parameterClass = parameterClass; // this.parameterStaticValue = parameterStaticValue; // } // // public String getParameterName() { // return parameterName; // } // // public void setParameterName(String parameterName) { // this.parameterName = parameterName; // } // // public String getParameterClass() { // return parameterClass; // } // // public void setParameterClass(String parameterClass) { // this.parameterClass = parameterClass; // } // // public String getParameterStaticValue() { // return parameterStaticValue; // } // // public void setParameterStaticValue(String parameterStaticValue) { // this.parameterStaticValue = parameterStaticValue; // } // // } // // Path: src/main/java/org/grouchotools/jsrules/exception/InvalidConfigException.java // public class InvalidConfigException extends JsRulesException { // // public InvalidConfigException() { // } // // public InvalidConfigException(String message) { // super(message); // } // // public InvalidConfigException(String message, Throwable cause) { // super(message, cause); // } // // public InvalidConfigException(Throwable cause) { // super(cause); // } // // public InvalidConfigException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // // } // // Path: src/main/java/org/grouchotools/jsrules/loader/impl/ParamLoaderImpl.java // public class ParamLoaderImpl implements ParamLoader { // // /** // * // * @param config // * @return // * @throws org.grouchotools.jsrules.exception.InvalidConfigException // */ // @Override // public Parameter load(ParamConfig config) throws InvalidConfigException { // if (config == null || config.getParameterClass() == null) { // throw new InvalidConfigException("Parameter class must not be null"); // } // String parameterClassName = config.getParameterClass().toUpperCase(); // ClassHandler handler; // try { // handler = ClassHandler.valueOf(parameterClassName); // } catch (IllegalArgumentException ex) { // throw new InvalidConfigException(parameterClassName+" is not a supported class", ex); // } // Class paramClass = handler.getMyClass(); // String paramStaticValue = config.getParameterStaticValue(); // Object paramStaticObject = null; // if (paramStaticValue != null) { // try { // paramStaticObject = handler.convertString(paramStaticValue); // } catch (ClassHandlerException|IllegalArgumentException ex) { // throw new InvalidConfigException(paramStaticValue+" is not a valid "+parameterClassName, ex); // } // } // return new Parameter(config.getParameterName(), paramClass, // paramStaticObject); // } // // }
import static org.junit.Assert.assertEquals; import org.grouchotools.jsrules.Parameter; import org.grouchotools.jsrules.config.ParamConfig; import org.grouchotools.jsrules.exception.InvalidConfigException; import org.grouchotools.jsrules.loader.impl.ParamLoaderImpl; import org.junit.*; import org.junit.rules.ExpectedException;
/* * The MIT License * * Copyright 2015 Paul. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.grouchotools.jsrules.loader; /** * * @author Paul */ public class ParamLoaderTest { @Rule public ExpectedException exception= ExpectedException.none(); private final ParamLoader paramLoader = new ParamLoaderImpl(); private final String paramName = "param"; public ParamLoaderTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } @Test public void loadTest() throws Exception { ParamConfig paramConfig = new ParamConfig(paramName, "long", "10");
// Path: src/main/java/org/grouchotools/jsrules/Parameter.java // public class Parameter<T> extends JsonBean { // public Parameter(String name, Class<T> klasse) { // this.name = name; // this.klasse = klasse; // this.staticValue = null; // } // // public Parameter(String name, Class<T> klasse, T staticValue) { // this.name = name; // this.klasse = klasse; // this.staticValue = staticValue; // } // // private final String name; // private final Class<T> klasse; // private final T staticValue; // // public String getName() { // return name; // } // // public Class<T> getKlasse() { // return klasse; // } // // public T getStaticValue() { // return staticValue; // } // // } // // Path: src/main/java/org/grouchotools/jsrules/config/ParamConfig.java // public class ParamConfig extends JsonBean implements Config { // private String parameterName; // private String parameterClass; // private String parameterStaticValue; // // public ParamConfig() { // // } // // public ParamConfig(String parameterName, String parameterClass, // String parameterStaticValue) { // this.parameterName = parameterName; // this.parameterClass = parameterClass; // this.parameterStaticValue = parameterStaticValue; // } // // public String getParameterName() { // return parameterName; // } // // public void setParameterName(String parameterName) { // this.parameterName = parameterName; // } // // public String getParameterClass() { // return parameterClass; // } // // public void setParameterClass(String parameterClass) { // this.parameterClass = parameterClass; // } // // public String getParameterStaticValue() { // return parameterStaticValue; // } // // public void setParameterStaticValue(String parameterStaticValue) { // this.parameterStaticValue = parameterStaticValue; // } // // } // // Path: src/main/java/org/grouchotools/jsrules/exception/InvalidConfigException.java // public class InvalidConfigException extends JsRulesException { // // public InvalidConfigException() { // } // // public InvalidConfigException(String message) { // super(message); // } // // public InvalidConfigException(String message, Throwable cause) { // super(message, cause); // } // // public InvalidConfigException(Throwable cause) { // super(cause); // } // // public InvalidConfigException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // // } // // Path: src/main/java/org/grouchotools/jsrules/loader/impl/ParamLoaderImpl.java // public class ParamLoaderImpl implements ParamLoader { // // /** // * // * @param config // * @return // * @throws org.grouchotools.jsrules.exception.InvalidConfigException // */ // @Override // public Parameter load(ParamConfig config) throws InvalidConfigException { // if (config == null || config.getParameterClass() == null) { // throw new InvalidConfigException("Parameter class must not be null"); // } // String parameterClassName = config.getParameterClass().toUpperCase(); // ClassHandler handler; // try { // handler = ClassHandler.valueOf(parameterClassName); // } catch (IllegalArgumentException ex) { // throw new InvalidConfigException(parameterClassName+" is not a supported class", ex); // } // Class paramClass = handler.getMyClass(); // String paramStaticValue = config.getParameterStaticValue(); // Object paramStaticObject = null; // if (paramStaticValue != null) { // try { // paramStaticObject = handler.convertString(paramStaticValue); // } catch (ClassHandlerException|IllegalArgumentException ex) { // throw new InvalidConfigException(paramStaticValue+" is not a valid "+parameterClassName, ex); // } // } // return new Parameter(config.getParameterName(), paramClass, // paramStaticObject); // } // // } // Path: src/test/java/org/grouchotools/jsrules/loader/ParamLoaderTest.java import static org.junit.Assert.assertEquals; import org.grouchotools.jsrules.Parameter; import org.grouchotools.jsrules.config.ParamConfig; import org.grouchotools.jsrules.exception.InvalidConfigException; import org.grouchotools.jsrules.loader.impl.ParamLoaderImpl; import org.junit.*; import org.junit.rules.ExpectedException; /* * The MIT License * * Copyright 2015 Paul. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.grouchotools.jsrules.loader; /** * * @author Paul */ public class ParamLoaderTest { @Rule public ExpectedException exception= ExpectedException.none(); private final ParamLoader paramLoader = new ParamLoaderImpl(); private final String paramName = "param"; public ParamLoaderTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } @Test public void loadTest() throws Exception { ParamConfig paramConfig = new ParamConfig(paramName, "long", "10");
Parameter mockParam = new Parameter(paramName, Long.class, 10l);
el-groucho/jsRules
src/test/java/org/grouchotools/jsrules/loader/ParamLoaderTest.java
// Path: src/main/java/org/grouchotools/jsrules/Parameter.java // public class Parameter<T> extends JsonBean { // public Parameter(String name, Class<T> klasse) { // this.name = name; // this.klasse = klasse; // this.staticValue = null; // } // // public Parameter(String name, Class<T> klasse, T staticValue) { // this.name = name; // this.klasse = klasse; // this.staticValue = staticValue; // } // // private final String name; // private final Class<T> klasse; // private final T staticValue; // // public String getName() { // return name; // } // // public Class<T> getKlasse() { // return klasse; // } // // public T getStaticValue() { // return staticValue; // } // // } // // Path: src/main/java/org/grouchotools/jsrules/config/ParamConfig.java // public class ParamConfig extends JsonBean implements Config { // private String parameterName; // private String parameterClass; // private String parameterStaticValue; // // public ParamConfig() { // // } // // public ParamConfig(String parameterName, String parameterClass, // String parameterStaticValue) { // this.parameterName = parameterName; // this.parameterClass = parameterClass; // this.parameterStaticValue = parameterStaticValue; // } // // public String getParameterName() { // return parameterName; // } // // public void setParameterName(String parameterName) { // this.parameterName = parameterName; // } // // public String getParameterClass() { // return parameterClass; // } // // public void setParameterClass(String parameterClass) { // this.parameterClass = parameterClass; // } // // public String getParameterStaticValue() { // return parameterStaticValue; // } // // public void setParameterStaticValue(String parameterStaticValue) { // this.parameterStaticValue = parameterStaticValue; // } // // } // // Path: src/main/java/org/grouchotools/jsrules/exception/InvalidConfigException.java // public class InvalidConfigException extends JsRulesException { // // public InvalidConfigException() { // } // // public InvalidConfigException(String message) { // super(message); // } // // public InvalidConfigException(String message, Throwable cause) { // super(message, cause); // } // // public InvalidConfigException(Throwable cause) { // super(cause); // } // // public InvalidConfigException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // // } // // Path: src/main/java/org/grouchotools/jsrules/loader/impl/ParamLoaderImpl.java // public class ParamLoaderImpl implements ParamLoader { // // /** // * // * @param config // * @return // * @throws org.grouchotools.jsrules.exception.InvalidConfigException // */ // @Override // public Parameter load(ParamConfig config) throws InvalidConfigException { // if (config == null || config.getParameterClass() == null) { // throw new InvalidConfigException("Parameter class must not be null"); // } // String parameterClassName = config.getParameterClass().toUpperCase(); // ClassHandler handler; // try { // handler = ClassHandler.valueOf(parameterClassName); // } catch (IllegalArgumentException ex) { // throw new InvalidConfigException(parameterClassName+" is not a supported class", ex); // } // Class paramClass = handler.getMyClass(); // String paramStaticValue = config.getParameterStaticValue(); // Object paramStaticObject = null; // if (paramStaticValue != null) { // try { // paramStaticObject = handler.convertString(paramStaticValue); // } catch (ClassHandlerException|IllegalArgumentException ex) { // throw new InvalidConfigException(paramStaticValue+" is not a valid "+parameterClassName, ex); // } // } // return new Parameter(config.getParameterName(), paramClass, // paramStaticObject); // } // // }
import static org.junit.Assert.assertEquals; import org.grouchotools.jsrules.Parameter; import org.grouchotools.jsrules.config.ParamConfig; import org.grouchotools.jsrules.exception.InvalidConfigException; import org.grouchotools.jsrules.loader.impl.ParamLoaderImpl; import org.junit.*; import org.junit.rules.ExpectedException;
/* * The MIT License * * Copyright 2015 Paul. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.grouchotools.jsrules.loader; /** * * @author Paul */ public class ParamLoaderTest { @Rule public ExpectedException exception= ExpectedException.none(); private final ParamLoader paramLoader = new ParamLoaderImpl(); private final String paramName = "param"; public ParamLoaderTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } @Test public void loadTest() throws Exception { ParamConfig paramConfig = new ParamConfig(paramName, "long", "10"); Parameter mockParam = new Parameter(paramName, Long.class, 10l); assertEquals(mockParam, paramLoader.load(paramConfig)); } @Test public void loadInvalidParamClassTest() throws Exception {
// Path: src/main/java/org/grouchotools/jsrules/Parameter.java // public class Parameter<T> extends JsonBean { // public Parameter(String name, Class<T> klasse) { // this.name = name; // this.klasse = klasse; // this.staticValue = null; // } // // public Parameter(String name, Class<T> klasse, T staticValue) { // this.name = name; // this.klasse = klasse; // this.staticValue = staticValue; // } // // private final String name; // private final Class<T> klasse; // private final T staticValue; // // public String getName() { // return name; // } // // public Class<T> getKlasse() { // return klasse; // } // // public T getStaticValue() { // return staticValue; // } // // } // // Path: src/main/java/org/grouchotools/jsrules/config/ParamConfig.java // public class ParamConfig extends JsonBean implements Config { // private String parameterName; // private String parameterClass; // private String parameterStaticValue; // // public ParamConfig() { // // } // // public ParamConfig(String parameterName, String parameterClass, // String parameterStaticValue) { // this.parameterName = parameterName; // this.parameterClass = parameterClass; // this.parameterStaticValue = parameterStaticValue; // } // // public String getParameterName() { // return parameterName; // } // // public void setParameterName(String parameterName) { // this.parameterName = parameterName; // } // // public String getParameterClass() { // return parameterClass; // } // // public void setParameterClass(String parameterClass) { // this.parameterClass = parameterClass; // } // // public String getParameterStaticValue() { // return parameterStaticValue; // } // // public void setParameterStaticValue(String parameterStaticValue) { // this.parameterStaticValue = parameterStaticValue; // } // // } // // Path: src/main/java/org/grouchotools/jsrules/exception/InvalidConfigException.java // public class InvalidConfigException extends JsRulesException { // // public InvalidConfigException() { // } // // public InvalidConfigException(String message) { // super(message); // } // // public InvalidConfigException(String message, Throwable cause) { // super(message, cause); // } // // public InvalidConfigException(Throwable cause) { // super(cause); // } // // public InvalidConfigException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // // } // // Path: src/main/java/org/grouchotools/jsrules/loader/impl/ParamLoaderImpl.java // public class ParamLoaderImpl implements ParamLoader { // // /** // * // * @param config // * @return // * @throws org.grouchotools.jsrules.exception.InvalidConfigException // */ // @Override // public Parameter load(ParamConfig config) throws InvalidConfigException { // if (config == null || config.getParameterClass() == null) { // throw new InvalidConfigException("Parameter class must not be null"); // } // String parameterClassName = config.getParameterClass().toUpperCase(); // ClassHandler handler; // try { // handler = ClassHandler.valueOf(parameterClassName); // } catch (IllegalArgumentException ex) { // throw new InvalidConfigException(parameterClassName+" is not a supported class", ex); // } // Class paramClass = handler.getMyClass(); // String paramStaticValue = config.getParameterStaticValue(); // Object paramStaticObject = null; // if (paramStaticValue != null) { // try { // paramStaticObject = handler.convertString(paramStaticValue); // } catch (ClassHandlerException|IllegalArgumentException ex) { // throw new InvalidConfigException(paramStaticValue+" is not a valid "+parameterClassName, ex); // } // } // return new Parameter(config.getParameterName(), paramClass, // paramStaticObject); // } // // } // Path: src/test/java/org/grouchotools/jsrules/loader/ParamLoaderTest.java import static org.junit.Assert.assertEquals; import org.grouchotools.jsrules.Parameter; import org.grouchotools.jsrules.config.ParamConfig; import org.grouchotools.jsrules.exception.InvalidConfigException; import org.grouchotools.jsrules.loader.impl.ParamLoaderImpl; import org.junit.*; import org.junit.rules.ExpectedException; /* * The MIT License * * Copyright 2015 Paul. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.grouchotools.jsrules.loader; /** * * @author Paul */ public class ParamLoaderTest { @Rule public ExpectedException exception= ExpectedException.none(); private final ParamLoader paramLoader = new ParamLoaderImpl(); private final String paramName = "param"; public ParamLoaderTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } @Test public void loadTest() throws Exception { ParamConfig paramConfig = new ParamConfig(paramName, "long", "10"); Parameter mockParam = new Parameter(paramName, Long.class, 10l); assertEquals(mockParam, paramLoader.load(paramConfig)); } @Test public void loadInvalidParamClassTest() throws Exception {
exception.expect(InvalidConfigException.class);
el-groucho/jsRules
src/main/java/org/grouchotools/jsrules/Operator.java
// Path: src/main/java/org/grouchotools/jsrules/exception/InvalidParameterException.java // public class InvalidParameterException extends JsRulesException { // // public InvalidParameterException() { // } // // public InvalidParameterException(String message) { // super(message); // } // // public InvalidParameterException(String message, Throwable cause) { // super(message, cause); // } // // public InvalidParameterException(Throwable cause) { // super(cause); // } // // public InvalidParameterException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // // }
import org.grouchotools.jsrules.exception.InvalidParameterException; import org.joda.time.DateTime; import java.util.ArrayList; import java.util.List; import java.util.Set;
/* * 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 org.grouchotools.jsrules; /** * @author Paul */ public enum Operator { GT { @Override
// Path: src/main/java/org/grouchotools/jsrules/exception/InvalidParameterException.java // public class InvalidParameterException extends JsRulesException { // // public InvalidParameterException() { // } // // public InvalidParameterException(String message) { // super(message); // } // // public InvalidParameterException(String message, Throwable cause) { // super(message, cause); // } // // public InvalidParameterException(Throwable cause) { // super(cause); // } // // public InvalidParameterException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // // } // Path: src/main/java/org/grouchotools/jsrules/Operator.java import org.grouchotools.jsrules.exception.InvalidParameterException; import org.joda.time.DateTime; import java.util.ArrayList; import java.util.List; import java.util.Set; /* * 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 org.grouchotools.jsrules; /** * @author Paul */ public enum Operator { GT { @Override
public Boolean compare(Object left, Object right) throws InvalidParameterException {
el-groucho/jsRules
src/main/java/org/grouchotools/jsrules/impl/RuleExecutorImpl.java
// Path: src/main/java/org/grouchotools/jsrules/Parameter.java // public class Parameter<T> extends JsonBean { // public Parameter(String name, Class<T> klasse) { // this.name = name; // this.klasse = klasse; // this.staticValue = null; // } // // public Parameter(String name, Class<T> klasse, T staticValue) { // this.name = name; // this.klasse = klasse; // this.staticValue = staticValue; // } // // private final String name; // private final Class<T> klasse; // private final T staticValue; // // public String getName() { // return name; // } // // public Class<T> getKlasse() { // return klasse; // } // // public T getStaticValue() { // return staticValue; // } // // } // // Path: src/main/java/org/grouchotools/jsrules/Rule.java // public class Rule<T, P> extends JsonBean { // // private final String ruleName; // // private final Parameter<P> leftParameter; // private final Operator operator; // private final Parameter<P> rightParameter; // // private final T response; // // public Rule(String ruleName, Parameter<P> leftParameter, Operator operator, // Parameter<P> rightParameter, T response) { // this.ruleName = ruleName; // this.leftParameter = leftParameter; // this.operator = operator; // this.rightParameter = rightParameter; // this.response = response; // } // // public String getRuleName() { // return ruleName; // } // // public Operator getOperator() { // return operator; // } // // public Parameter getLeftParameter() { // return leftParameter; // } // // public Parameter getRightParameter() { // return rightParameter; // } // // public T getResponse() { // return response; // } // // } // // Path: src/main/java/org/grouchotools/jsrules/RuleExecutor.java // public abstract class RuleExecutor<T> extends Executor { // public abstract T execute(Object leftParameter, Object rightParameter) throws InvalidParameterException; // // public abstract T execute(Object leftParameter) throws InvalidParameterException; // // public abstract Parameter getLeftParameter(); // // public abstract Parameter getRightParameter(); // // public abstract Rule getRule(); // } // // Path: src/main/java/org/grouchotools/jsrules/exception/InvalidParameterException.java // public class InvalidParameterException extends JsRulesException { // // public InvalidParameterException() { // } // // public InvalidParameterException(String message) { // super(message); // } // // public InvalidParameterException(String message, Throwable cause) { // super(message, cause); // } // // public InvalidParameterException(Throwable cause) { // super(cause); // } // // public InvalidParameterException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // // }
import org.grouchotools.jsrules.Parameter; import org.grouchotools.jsrules.Rule; import org.grouchotools.jsrules.RuleExecutor; import org.grouchotools.jsrules.exception.InvalidParameterException; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
/* * 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 org.grouchotools.jsrules.impl; /** * * @author Paul * @param <T> * @param <P> */ public class RuleExecutorImpl<T, P> extends RuleExecutor<T> { private static final Logger LOG = LoggerFactory.getLogger(RuleExecutorImpl.class);
// Path: src/main/java/org/grouchotools/jsrules/Parameter.java // public class Parameter<T> extends JsonBean { // public Parameter(String name, Class<T> klasse) { // this.name = name; // this.klasse = klasse; // this.staticValue = null; // } // // public Parameter(String name, Class<T> klasse, T staticValue) { // this.name = name; // this.klasse = klasse; // this.staticValue = staticValue; // } // // private final String name; // private final Class<T> klasse; // private final T staticValue; // // public String getName() { // return name; // } // // public Class<T> getKlasse() { // return klasse; // } // // public T getStaticValue() { // return staticValue; // } // // } // // Path: src/main/java/org/grouchotools/jsrules/Rule.java // public class Rule<T, P> extends JsonBean { // // private final String ruleName; // // private final Parameter<P> leftParameter; // private final Operator operator; // private final Parameter<P> rightParameter; // // private final T response; // // public Rule(String ruleName, Parameter<P> leftParameter, Operator operator, // Parameter<P> rightParameter, T response) { // this.ruleName = ruleName; // this.leftParameter = leftParameter; // this.operator = operator; // this.rightParameter = rightParameter; // this.response = response; // } // // public String getRuleName() { // return ruleName; // } // // public Operator getOperator() { // return operator; // } // // public Parameter getLeftParameter() { // return leftParameter; // } // // public Parameter getRightParameter() { // return rightParameter; // } // // public T getResponse() { // return response; // } // // } // // Path: src/main/java/org/grouchotools/jsrules/RuleExecutor.java // public abstract class RuleExecutor<T> extends Executor { // public abstract T execute(Object leftParameter, Object rightParameter) throws InvalidParameterException; // // public abstract T execute(Object leftParameter) throws InvalidParameterException; // // public abstract Parameter getLeftParameter(); // // public abstract Parameter getRightParameter(); // // public abstract Rule getRule(); // } // // Path: src/main/java/org/grouchotools/jsrules/exception/InvalidParameterException.java // public class InvalidParameterException extends JsRulesException { // // public InvalidParameterException() { // } // // public InvalidParameterException(String message) { // super(message); // } // // public InvalidParameterException(String message, Throwable cause) { // super(message, cause); // } // // public InvalidParameterException(Throwable cause) { // super(cause); // } // // public InvalidParameterException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // // } // Path: src/main/java/org/grouchotools/jsrules/impl/RuleExecutorImpl.java import org.grouchotools.jsrules.Parameter; import org.grouchotools.jsrules.Rule; import org.grouchotools.jsrules.RuleExecutor; import org.grouchotools.jsrules.exception.InvalidParameterException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /* * 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 org.grouchotools.jsrules.impl; /** * * @author Paul * @param <T> * @param <P> */ public class RuleExecutorImpl<T, P> extends RuleExecutor<T> { private static final Logger LOG = LoggerFactory.getLogger(RuleExecutorImpl.class);
private final Rule<T, P> rule;
el-groucho/jsRules
src/main/java/org/grouchotools/jsrules/impl/RuleExecutorImpl.java
// Path: src/main/java/org/grouchotools/jsrules/Parameter.java // public class Parameter<T> extends JsonBean { // public Parameter(String name, Class<T> klasse) { // this.name = name; // this.klasse = klasse; // this.staticValue = null; // } // // public Parameter(String name, Class<T> klasse, T staticValue) { // this.name = name; // this.klasse = klasse; // this.staticValue = staticValue; // } // // private final String name; // private final Class<T> klasse; // private final T staticValue; // // public String getName() { // return name; // } // // public Class<T> getKlasse() { // return klasse; // } // // public T getStaticValue() { // return staticValue; // } // // } // // Path: src/main/java/org/grouchotools/jsrules/Rule.java // public class Rule<T, P> extends JsonBean { // // private final String ruleName; // // private final Parameter<P> leftParameter; // private final Operator operator; // private final Parameter<P> rightParameter; // // private final T response; // // public Rule(String ruleName, Parameter<P> leftParameter, Operator operator, // Parameter<P> rightParameter, T response) { // this.ruleName = ruleName; // this.leftParameter = leftParameter; // this.operator = operator; // this.rightParameter = rightParameter; // this.response = response; // } // // public String getRuleName() { // return ruleName; // } // // public Operator getOperator() { // return operator; // } // // public Parameter getLeftParameter() { // return leftParameter; // } // // public Parameter getRightParameter() { // return rightParameter; // } // // public T getResponse() { // return response; // } // // } // // Path: src/main/java/org/grouchotools/jsrules/RuleExecutor.java // public abstract class RuleExecutor<T> extends Executor { // public abstract T execute(Object leftParameter, Object rightParameter) throws InvalidParameterException; // // public abstract T execute(Object leftParameter) throws InvalidParameterException; // // public abstract Parameter getLeftParameter(); // // public abstract Parameter getRightParameter(); // // public abstract Rule getRule(); // } // // Path: src/main/java/org/grouchotools/jsrules/exception/InvalidParameterException.java // public class InvalidParameterException extends JsRulesException { // // public InvalidParameterException() { // } // // public InvalidParameterException(String message) { // super(message); // } // // public InvalidParameterException(String message, Throwable cause) { // super(message, cause); // } // // public InvalidParameterException(Throwable cause) { // super(cause); // } // // public InvalidParameterException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // // }
import org.grouchotools.jsrules.Parameter; import org.grouchotools.jsrules.Rule; import org.grouchotools.jsrules.RuleExecutor; import org.grouchotools.jsrules.exception.InvalidParameterException; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
/* * 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 org.grouchotools.jsrules.impl; /** * * @author Paul * @param <T> * @param <P> */ public class RuleExecutorImpl<T, P> extends RuleExecutor<T> { private static final Logger LOG = LoggerFactory.getLogger(RuleExecutorImpl.class); private final Rule<T, P> rule; public RuleExecutorImpl(Rule<T, P> rule) { this.rule = rule; } @Override
// Path: src/main/java/org/grouchotools/jsrules/Parameter.java // public class Parameter<T> extends JsonBean { // public Parameter(String name, Class<T> klasse) { // this.name = name; // this.klasse = klasse; // this.staticValue = null; // } // // public Parameter(String name, Class<T> klasse, T staticValue) { // this.name = name; // this.klasse = klasse; // this.staticValue = staticValue; // } // // private final String name; // private final Class<T> klasse; // private final T staticValue; // // public String getName() { // return name; // } // // public Class<T> getKlasse() { // return klasse; // } // // public T getStaticValue() { // return staticValue; // } // // } // // Path: src/main/java/org/grouchotools/jsrules/Rule.java // public class Rule<T, P> extends JsonBean { // // private final String ruleName; // // private final Parameter<P> leftParameter; // private final Operator operator; // private final Parameter<P> rightParameter; // // private final T response; // // public Rule(String ruleName, Parameter<P> leftParameter, Operator operator, // Parameter<P> rightParameter, T response) { // this.ruleName = ruleName; // this.leftParameter = leftParameter; // this.operator = operator; // this.rightParameter = rightParameter; // this.response = response; // } // // public String getRuleName() { // return ruleName; // } // // public Operator getOperator() { // return operator; // } // // public Parameter getLeftParameter() { // return leftParameter; // } // // public Parameter getRightParameter() { // return rightParameter; // } // // public T getResponse() { // return response; // } // // } // // Path: src/main/java/org/grouchotools/jsrules/RuleExecutor.java // public abstract class RuleExecutor<T> extends Executor { // public abstract T execute(Object leftParameter, Object rightParameter) throws InvalidParameterException; // // public abstract T execute(Object leftParameter) throws InvalidParameterException; // // public abstract Parameter getLeftParameter(); // // public abstract Parameter getRightParameter(); // // public abstract Rule getRule(); // } // // Path: src/main/java/org/grouchotools/jsrules/exception/InvalidParameterException.java // public class InvalidParameterException extends JsRulesException { // // public InvalidParameterException() { // } // // public InvalidParameterException(String message) { // super(message); // } // // public InvalidParameterException(String message, Throwable cause) { // super(message, cause); // } // // public InvalidParameterException(Throwable cause) { // super(cause); // } // // public InvalidParameterException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // // } // Path: src/main/java/org/grouchotools/jsrules/impl/RuleExecutorImpl.java import org.grouchotools.jsrules.Parameter; import org.grouchotools.jsrules.Rule; import org.grouchotools.jsrules.RuleExecutor; import org.grouchotools.jsrules.exception.InvalidParameterException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /* * 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 org.grouchotools.jsrules.impl; /** * * @author Paul * @param <T> * @param <P> */ public class RuleExecutorImpl<T, P> extends RuleExecutor<T> { private static final Logger LOG = LoggerFactory.getLogger(RuleExecutorImpl.class); private final Rule<T, P> rule; public RuleExecutorImpl(Rule<T, P> rule) { this.rule = rule; } @Override
public T execute(Object leftParameter, Object rightParameter) throws InvalidParameterException {
el-groucho/jsRules
src/main/java/org/grouchotools/jsrules/impl/RuleExecutorImpl.java
// Path: src/main/java/org/grouchotools/jsrules/Parameter.java // public class Parameter<T> extends JsonBean { // public Parameter(String name, Class<T> klasse) { // this.name = name; // this.klasse = klasse; // this.staticValue = null; // } // // public Parameter(String name, Class<T> klasse, T staticValue) { // this.name = name; // this.klasse = klasse; // this.staticValue = staticValue; // } // // private final String name; // private final Class<T> klasse; // private final T staticValue; // // public String getName() { // return name; // } // // public Class<T> getKlasse() { // return klasse; // } // // public T getStaticValue() { // return staticValue; // } // // } // // Path: src/main/java/org/grouchotools/jsrules/Rule.java // public class Rule<T, P> extends JsonBean { // // private final String ruleName; // // private final Parameter<P> leftParameter; // private final Operator operator; // private final Parameter<P> rightParameter; // // private final T response; // // public Rule(String ruleName, Parameter<P> leftParameter, Operator operator, // Parameter<P> rightParameter, T response) { // this.ruleName = ruleName; // this.leftParameter = leftParameter; // this.operator = operator; // this.rightParameter = rightParameter; // this.response = response; // } // // public String getRuleName() { // return ruleName; // } // // public Operator getOperator() { // return operator; // } // // public Parameter getLeftParameter() { // return leftParameter; // } // // public Parameter getRightParameter() { // return rightParameter; // } // // public T getResponse() { // return response; // } // // } // // Path: src/main/java/org/grouchotools/jsrules/RuleExecutor.java // public abstract class RuleExecutor<T> extends Executor { // public abstract T execute(Object leftParameter, Object rightParameter) throws InvalidParameterException; // // public abstract T execute(Object leftParameter) throws InvalidParameterException; // // public abstract Parameter getLeftParameter(); // // public abstract Parameter getRightParameter(); // // public abstract Rule getRule(); // } // // Path: src/main/java/org/grouchotools/jsrules/exception/InvalidParameterException.java // public class InvalidParameterException extends JsRulesException { // // public InvalidParameterException() { // } // // public InvalidParameterException(String message) { // super(message); // } // // public InvalidParameterException(String message, Throwable cause) { // super(message, cause); // } // // public InvalidParameterException(Throwable cause) { // super(cause); // } // // public InvalidParameterException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // // }
import org.grouchotools.jsrules.Parameter; import org.grouchotools.jsrules.Rule; import org.grouchotools.jsrules.RuleExecutor; import org.grouchotools.jsrules.exception.InvalidParameterException; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
/* * 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 org.grouchotools.jsrules.impl; /** * * @author Paul * @param <T> * @param <P> */ public class RuleExecutorImpl<T, P> extends RuleExecutor<T> { private static final Logger LOG = LoggerFactory.getLogger(RuleExecutorImpl.class); private final Rule<T, P> rule; public RuleExecutorImpl(Rule<T, P> rule) { this.rule = rule; } @Override public T execute(Object leftParameter, Object rightParameter) throws InvalidParameterException { Object staticValue = rule.getRightParameter().getStaticValue(); if (staticValue != null) { LOG.error("Right parameter has a static value of {} and should not be specified", staticValue); throw new InvalidParameterException(); } return executeRule(leftParameter, rightParameter); } @Override public T execute(Object leftParameter) throws InvalidParameterException { Object rightParameter = rule.getRightParameter().getStaticValue(); if (rightParameter == null) { LOG.error("Right parameter must be specified"); throw new InvalidParameterException(); } return executeRule(leftParameter, rightParameter); } @Override
// Path: src/main/java/org/grouchotools/jsrules/Parameter.java // public class Parameter<T> extends JsonBean { // public Parameter(String name, Class<T> klasse) { // this.name = name; // this.klasse = klasse; // this.staticValue = null; // } // // public Parameter(String name, Class<T> klasse, T staticValue) { // this.name = name; // this.klasse = klasse; // this.staticValue = staticValue; // } // // private final String name; // private final Class<T> klasse; // private final T staticValue; // // public String getName() { // return name; // } // // public Class<T> getKlasse() { // return klasse; // } // // public T getStaticValue() { // return staticValue; // } // // } // // Path: src/main/java/org/grouchotools/jsrules/Rule.java // public class Rule<T, P> extends JsonBean { // // private final String ruleName; // // private final Parameter<P> leftParameter; // private final Operator operator; // private final Parameter<P> rightParameter; // // private final T response; // // public Rule(String ruleName, Parameter<P> leftParameter, Operator operator, // Parameter<P> rightParameter, T response) { // this.ruleName = ruleName; // this.leftParameter = leftParameter; // this.operator = operator; // this.rightParameter = rightParameter; // this.response = response; // } // // public String getRuleName() { // return ruleName; // } // // public Operator getOperator() { // return operator; // } // // public Parameter getLeftParameter() { // return leftParameter; // } // // public Parameter getRightParameter() { // return rightParameter; // } // // public T getResponse() { // return response; // } // // } // // Path: src/main/java/org/grouchotools/jsrules/RuleExecutor.java // public abstract class RuleExecutor<T> extends Executor { // public abstract T execute(Object leftParameter, Object rightParameter) throws InvalidParameterException; // // public abstract T execute(Object leftParameter) throws InvalidParameterException; // // public abstract Parameter getLeftParameter(); // // public abstract Parameter getRightParameter(); // // public abstract Rule getRule(); // } // // Path: src/main/java/org/grouchotools/jsrules/exception/InvalidParameterException.java // public class InvalidParameterException extends JsRulesException { // // public InvalidParameterException() { // } // // public InvalidParameterException(String message) { // super(message); // } // // public InvalidParameterException(String message, Throwable cause) { // super(message, cause); // } // // public InvalidParameterException(Throwable cause) { // super(cause); // } // // public InvalidParameterException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { // super(message, cause, enableSuppression, writableStackTrace); // } // // } // Path: src/main/java/org/grouchotools/jsrules/impl/RuleExecutorImpl.java import org.grouchotools.jsrules.Parameter; import org.grouchotools.jsrules.Rule; import org.grouchotools.jsrules.RuleExecutor; import org.grouchotools.jsrules.exception.InvalidParameterException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /* * 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 org.grouchotools.jsrules.impl; /** * * @author Paul * @param <T> * @param <P> */ public class RuleExecutorImpl<T, P> extends RuleExecutor<T> { private static final Logger LOG = LoggerFactory.getLogger(RuleExecutorImpl.class); private final Rule<T, P> rule; public RuleExecutorImpl(Rule<T, P> rule) { this.rule = rule; } @Override public T execute(Object leftParameter, Object rightParameter) throws InvalidParameterException { Object staticValue = rule.getRightParameter().getStaticValue(); if (staticValue != null) { LOG.error("Right parameter has a static value of {} and should not be specified", staticValue); throw new InvalidParameterException(); } return executeRule(leftParameter, rightParameter); } @Override public T execute(Object leftParameter) throws InvalidParameterException { Object rightParameter = rule.getRightParameter().getStaticValue(); if (rightParameter == null) { LOG.error("Right parameter must be specified"); throw new InvalidParameterException(); } return executeRule(leftParameter, rightParameter); } @Override
public Parameter getLeftParameter() {
ceylon/ceylon-js
src/main/java/com/redhat/ceylon/compiler/js/util/Options.java
// Path: src/main/java/com/redhat/ceylon/compiler/js/DiagnosticListener.java // public interface DiagnosticListener { // void error(File file, long line, long column, String message); // void warning(File file, long line, long column, String message); // // // FIXME: special API for default module? Else specify version for default module. // void moduleCompiled(String module, String version); // }
import java.io.File; import java.io.Writer; import java.util.ArrayList; import java.util.Arrays; import java.util.EnumSet; import java.util.Iterator; import java.util.List; import com.redhat.ceylon.common.config.DefaultToolOptions; import com.redhat.ceylon.common.log.Logger; import com.redhat.ceylon.compiler.js.DiagnosticListener; import com.redhat.ceylon.compiler.typechecker.analyzer.Warning;
package com.redhat.ceylon.compiler.js.util; /** Represents all the options for compiling. * * @author Enrique Zamudio */ public class Options { private File cwd; private List<String> repos = new ArrayList<String>(); private String systemRepo; private String user; private String pass; private List<File> srcDirs = new ArrayList<File>(); private List<File> resourceDirs = new ArrayList<File>(); private String resourceRoot = DefaultToolOptions.getCompilerResourceRootName(); private String outRepo = DefaultToolOptions.getCompilerOutputRepo(); private boolean optimize = true; private boolean modulify = true; private boolean comment = true; private String verbose; private boolean profile; private boolean help; private boolean version; private boolean stdin; private boolean gensrc = true; private boolean offline; private boolean srcmap; private boolean minify; private String encoding = System.getProperty("file.encoding"); private Logger logger; private Writer outWriter;
// Path: src/main/java/com/redhat/ceylon/compiler/js/DiagnosticListener.java // public interface DiagnosticListener { // void error(File file, long line, long column, String message); // void warning(File file, long line, long column, String message); // // // FIXME: special API for default module? Else specify version for default module. // void moduleCompiled(String module, String version); // } // Path: src/main/java/com/redhat/ceylon/compiler/js/util/Options.java import java.io.File; import java.io.Writer; import java.util.ArrayList; import java.util.Arrays; import java.util.EnumSet; import java.util.Iterator; import java.util.List; import com.redhat.ceylon.common.config.DefaultToolOptions; import com.redhat.ceylon.common.log.Logger; import com.redhat.ceylon.compiler.js.DiagnosticListener; import com.redhat.ceylon.compiler.typechecker.analyzer.Warning; package com.redhat.ceylon.compiler.js.util; /** Represents all the options for compiling. * * @author Enrique Zamudio */ public class Options { private File cwd; private List<String> repos = new ArrayList<String>(); private String systemRepo; private String user; private String pass; private List<File> srcDirs = new ArrayList<File>(); private List<File> resourceDirs = new ArrayList<File>(); private String resourceRoot = DefaultToolOptions.getCompilerResourceRootName(); private String outRepo = DefaultToolOptions.getCompilerOutputRepo(); private boolean optimize = true; private boolean modulify = true; private boolean comment = true; private String verbose; private boolean profile; private boolean help; private boolean version; private boolean stdin; private boolean gensrc = true; private boolean offline; private boolean srcmap; private boolean minify; private String encoding = System.getProperty("file.encoding"); private Logger logger; private Writer outWriter;
private DiagnosticListener diagnosticListener;
ceylon/ceylon-js
src/main/java/com/redhat/ceylon/compiler/js/util/ContinueBreakVisitor.java
// Path: src/main/java/com/redhat/ceylon/compiler/js/BlockWithCaptureVisitor.java // public class BlockWithCaptureVisitor extends Visitor { // // private boolean hasCapture; // private final Scope scope; // // public BlockWithCaptureVisitor(Tree.Block block) { // scope = ModelUtil.getRealScope(block.getScope()); // block.visit(this); // } // // public void visit(Tree.Declaration that) { // if (that.getDeclarationModel() != null && that.getDeclarationModel().isCaptured()) { // hasCapture |= scope == ModelUtil.getRealScope(that.getDeclarationModel().getScope()); // } // super.visit(that); // } // // public void visit(Tree.BaseMemberExpression that) { // if (that.getDeclaration() != null && that.getDeclaration().isCaptured()) { // hasCapture |= scope == ModelUtil.getRealScope(that.getDeclaration().getScope()); // } // super.visit(that); // } // // public boolean hasCapture() { // return hasCapture; // } // }
import java.util.IdentityHashMap; import com.redhat.ceylon.compiler.js.BlockWithCaptureVisitor; import com.redhat.ceylon.compiler.typechecker.tree.Tree; import com.redhat.ceylon.compiler.typechecker.tree.Visitor; import com.redhat.ceylon.model.typechecker.model.Scope;
package com.redhat.ceylon.compiler.js.util; public class ContinueBreakVisitor extends Visitor { private boolean breaks; private boolean continues; private boolean returns; private final Scope scope; private final JsIdentifierNames names; private String bname; private String cname; private String rname; private int level; private boolean ignore; private final IdentityHashMap<Tree.Directive, Boolean> dirs = new IdentityHashMap<>(); public ContinueBreakVisitor(Tree.Block n, JsIdentifierNames names) { scope = n.getScope(); this.names = names; n.visit(this); } public void visit(Tree.Block that) { level++; if (level>1) {
// Path: src/main/java/com/redhat/ceylon/compiler/js/BlockWithCaptureVisitor.java // public class BlockWithCaptureVisitor extends Visitor { // // private boolean hasCapture; // private final Scope scope; // // public BlockWithCaptureVisitor(Tree.Block block) { // scope = ModelUtil.getRealScope(block.getScope()); // block.visit(this); // } // // public void visit(Tree.Declaration that) { // if (that.getDeclarationModel() != null && that.getDeclarationModel().isCaptured()) { // hasCapture |= scope == ModelUtil.getRealScope(that.getDeclarationModel().getScope()); // } // super.visit(that); // } // // public void visit(Tree.BaseMemberExpression that) { // if (that.getDeclaration() != null && that.getDeclaration().isCaptured()) { // hasCapture |= scope == ModelUtil.getRealScope(that.getDeclaration().getScope()); // } // super.visit(that); // } // // public boolean hasCapture() { // return hasCapture; // } // } // Path: src/main/java/com/redhat/ceylon/compiler/js/util/ContinueBreakVisitor.java import java.util.IdentityHashMap; import com.redhat.ceylon.compiler.js.BlockWithCaptureVisitor; import com.redhat.ceylon.compiler.typechecker.tree.Tree; import com.redhat.ceylon.compiler.typechecker.tree.Visitor; import com.redhat.ceylon.model.typechecker.model.Scope; package com.redhat.ceylon.compiler.js.util; public class ContinueBreakVisitor extends Visitor { private boolean breaks; private boolean continues; private boolean returns; private final Scope scope; private final JsIdentifierNames names; private String bname; private String cname; private String rname; private int level; private boolean ignore; private final IdentityHashMap<Tree.Directive, Boolean> dirs = new IdentityHashMap<>(); public ContinueBreakVisitor(Tree.Block n, JsIdentifierNames names) { scope = n.getScope(); this.names = names; n.visit(this); } public void visit(Tree.Block that) { level++; if (level>1) {
ignore=new BlockWithCaptureVisitor(that).hasCapture();
ceylon/ceylon-js
src/main/java/com/redhat/ceylon/compiler/js/loader/JsModuleSourceMapper.java
// Path: src/main/java/com/redhat/ceylon/compiler/js/CeylonRunJsException.java // public class CeylonRunJsException extends ToolError { // // private static final long serialVersionUID = 1L; // // public CeylonRunJsException(String message) { // super(message); // } // // public CeylonRunJsException(String message, int exitCode) { // super(message, exitCode); // } // } // // Path: src/main/java/com/redhat/ceylon/compiler/js/CompilerErrorException.java // public class CompilerErrorException extends ToolError { // // private static final long serialVersionUID = 5L; // // public CompilerErrorException(String message) { // super(message); // } // }
import java.io.File; import java.io.IOException; import java.util.LinkedList; import java.util.List; import java.util.Map; import com.redhat.ceylon.cmr.api.ArtifactContext; import com.redhat.ceylon.cmr.impl.JSUtils; import com.redhat.ceylon.common.Backends; import com.redhat.ceylon.common.config.CeylonConfig; import com.redhat.ceylon.common.config.DefaultToolOptions; import com.redhat.ceylon.compiler.js.CeylonRunJsException; import com.redhat.ceylon.compiler.js.CompilerErrorException; import com.redhat.ceylon.compiler.typechecker.analyzer.ModuleSourceMapper; import com.redhat.ceylon.compiler.typechecker.context.Context; import com.redhat.ceylon.compiler.typechecker.context.PhasedUnits; import com.redhat.ceylon.model.cmr.ArtifactResult; import com.redhat.ceylon.model.typechecker.model.Module; import com.redhat.ceylon.model.typechecker.model.ModuleImport; import com.redhat.ceylon.model.typechecker.util.ModuleManager;
package com.redhat.ceylon.compiler.js.loader; public class JsModuleSourceMapper extends ModuleSourceMapper { /** Tells whether the language module has been loaded yet. */ private boolean clLoaded; private String encoding; public JsModuleSourceMapper(Context context, ModuleManager moduleManager, String encoding) { super(context, moduleManager); this.encoding = encoding; } protected void loadModuleFromMap(ArtifactResult artifact, Module module, LinkedList<Module> dependencyTree, List<PhasedUnits> phasedUnitsOfDependencies, boolean forCompiledModule, Map<String, Object> model) { @SuppressWarnings("unchecked") List<Object> deps = (List<Object>)model.get("$mod-deps"); if (deps != null) { for (Object dep : deps) { final String s; boolean optional = false; boolean export = false; if (dep instanceof Map) { @SuppressWarnings("unchecked") final Map<String,Object> depmap = (Map<String,Object>)dep; s = (String)depmap.get("path"); optional = depmap.containsKey("opt"); export = depmap.containsKey("exp"); } else { s = (String)dep; } int p = s.indexOf('/'); String depname = null; String depv = null; if (p > 0) { depname = s.substring(0,p); depv = s.substring(p+1); if (depv.isEmpty()) { depv = null; } //TODO Remove this hack after next bin compat breaks if (Module.LANGUAGE_MODULE_NAME.equals(depname) && "1.1.0".equals(depv)) { depv = "1.2.0"; } } else { depname = s; } //This will cause the dependency to be loaded later JsonModule mod = (JsonModule)getModuleManager().getOrCreateModule( ModuleManager.splitModuleName(depname), depv); Backends backends = mod.getNativeBackends(); ModuleImport imp = new ModuleImport(mod, optional, export, backends); module.addImport(imp); } model.remove("$mod-deps"); } ((JsonModule)module).setModel(model); for (ModuleImport imp : module.getImports()) { if (!imp.getModule().getNameAsString().equals(Module.LANGUAGE_MODULE_NAME)) { ArtifactContext ac = new ArtifactContext(imp.getModule().getNameAsString(), imp.getModule().getVersion(), ArtifactContext.JS_MODEL); artifact = getContext().getRepositoryManager().getArtifactResult(ac); if (artifact != null) { resolveModule(artifact, imp.getModule(), imp, dependencyTree, phasedUnitsOfDependencies, forCompiledModule & imp.isExport()); } } } ((JsonModule)module).loadDeclarations(); return; } /** Read the metamodel declaration from a js file, * check it's the right version and return the model as a Map. */ public static Map<String,Object> loadJsonModel(File jsFile) { try { Map<String,Object> model = JSUtils.readJsonModel(jsFile); if (model == null) {
// Path: src/main/java/com/redhat/ceylon/compiler/js/CeylonRunJsException.java // public class CeylonRunJsException extends ToolError { // // private static final long serialVersionUID = 1L; // // public CeylonRunJsException(String message) { // super(message); // } // // public CeylonRunJsException(String message, int exitCode) { // super(message, exitCode); // } // } // // Path: src/main/java/com/redhat/ceylon/compiler/js/CompilerErrorException.java // public class CompilerErrorException extends ToolError { // // private static final long serialVersionUID = 5L; // // public CompilerErrorException(String message) { // super(message); // } // } // Path: src/main/java/com/redhat/ceylon/compiler/js/loader/JsModuleSourceMapper.java import java.io.File; import java.io.IOException; import java.util.LinkedList; import java.util.List; import java.util.Map; import com.redhat.ceylon.cmr.api.ArtifactContext; import com.redhat.ceylon.cmr.impl.JSUtils; import com.redhat.ceylon.common.Backends; import com.redhat.ceylon.common.config.CeylonConfig; import com.redhat.ceylon.common.config.DefaultToolOptions; import com.redhat.ceylon.compiler.js.CeylonRunJsException; import com.redhat.ceylon.compiler.js.CompilerErrorException; import com.redhat.ceylon.compiler.typechecker.analyzer.ModuleSourceMapper; import com.redhat.ceylon.compiler.typechecker.context.Context; import com.redhat.ceylon.compiler.typechecker.context.PhasedUnits; import com.redhat.ceylon.model.cmr.ArtifactResult; import com.redhat.ceylon.model.typechecker.model.Module; import com.redhat.ceylon.model.typechecker.model.ModuleImport; import com.redhat.ceylon.model.typechecker.util.ModuleManager; package com.redhat.ceylon.compiler.js.loader; public class JsModuleSourceMapper extends ModuleSourceMapper { /** Tells whether the language module has been loaded yet. */ private boolean clLoaded; private String encoding; public JsModuleSourceMapper(Context context, ModuleManager moduleManager, String encoding) { super(context, moduleManager); this.encoding = encoding; } protected void loadModuleFromMap(ArtifactResult artifact, Module module, LinkedList<Module> dependencyTree, List<PhasedUnits> phasedUnitsOfDependencies, boolean forCompiledModule, Map<String, Object> model) { @SuppressWarnings("unchecked") List<Object> deps = (List<Object>)model.get("$mod-deps"); if (deps != null) { for (Object dep : deps) { final String s; boolean optional = false; boolean export = false; if (dep instanceof Map) { @SuppressWarnings("unchecked") final Map<String,Object> depmap = (Map<String,Object>)dep; s = (String)depmap.get("path"); optional = depmap.containsKey("opt"); export = depmap.containsKey("exp"); } else { s = (String)dep; } int p = s.indexOf('/'); String depname = null; String depv = null; if (p > 0) { depname = s.substring(0,p); depv = s.substring(p+1); if (depv.isEmpty()) { depv = null; } //TODO Remove this hack after next bin compat breaks if (Module.LANGUAGE_MODULE_NAME.equals(depname) && "1.1.0".equals(depv)) { depv = "1.2.0"; } } else { depname = s; } //This will cause the dependency to be loaded later JsonModule mod = (JsonModule)getModuleManager().getOrCreateModule( ModuleManager.splitModuleName(depname), depv); Backends backends = mod.getNativeBackends(); ModuleImport imp = new ModuleImport(mod, optional, export, backends); module.addImport(imp); } model.remove("$mod-deps"); } ((JsonModule)module).setModel(model); for (ModuleImport imp : module.getImports()) { if (!imp.getModule().getNameAsString().equals(Module.LANGUAGE_MODULE_NAME)) { ArtifactContext ac = new ArtifactContext(imp.getModule().getNameAsString(), imp.getModule().getVersion(), ArtifactContext.JS_MODEL); artifact = getContext().getRepositoryManager().getArtifactResult(ac); if (artifact != null) { resolveModule(artifact, imp.getModule(), imp, dependencyTree, phasedUnitsOfDependencies, forCompiledModule & imp.isExport()); } } } ((JsonModule)module).loadDeclarations(); return; } /** Read the metamodel declaration from a js file, * check it's the right version and return the model as a Map. */ public static Map<String,Object> loadJsonModel(File jsFile) { try { Map<String,Object> model = JSUtils.readJsonModel(jsFile); if (model == null) {
throw new CompilerErrorException("Can't find metamodel definition in " + jsFile.getAbsolutePath());
ceylon/ceylon-js
src/main/java/com/redhat/ceylon/compiler/js/loader/JsModuleSourceMapper.java
// Path: src/main/java/com/redhat/ceylon/compiler/js/CeylonRunJsException.java // public class CeylonRunJsException extends ToolError { // // private static final long serialVersionUID = 1L; // // public CeylonRunJsException(String message) { // super(message); // } // // public CeylonRunJsException(String message, int exitCode) { // super(message, exitCode); // } // } // // Path: src/main/java/com/redhat/ceylon/compiler/js/CompilerErrorException.java // public class CompilerErrorException extends ToolError { // // private static final long serialVersionUID = 5L; // // public CompilerErrorException(String message) { // super(message); // } // }
import java.io.File; import java.io.IOException; import java.util.LinkedList; import java.util.List; import java.util.Map; import com.redhat.ceylon.cmr.api.ArtifactContext; import com.redhat.ceylon.cmr.impl.JSUtils; import com.redhat.ceylon.common.Backends; import com.redhat.ceylon.common.config.CeylonConfig; import com.redhat.ceylon.common.config.DefaultToolOptions; import com.redhat.ceylon.compiler.js.CeylonRunJsException; import com.redhat.ceylon.compiler.js.CompilerErrorException; import com.redhat.ceylon.compiler.typechecker.analyzer.ModuleSourceMapper; import com.redhat.ceylon.compiler.typechecker.context.Context; import com.redhat.ceylon.compiler.typechecker.context.PhasedUnits; import com.redhat.ceylon.model.cmr.ArtifactResult; import com.redhat.ceylon.model.typechecker.model.Module; import com.redhat.ceylon.model.typechecker.model.ModuleImport; import com.redhat.ceylon.model.typechecker.util.ModuleManager;
package com.redhat.ceylon.compiler.js.loader; public class JsModuleSourceMapper extends ModuleSourceMapper { /** Tells whether the language module has been loaded yet. */ private boolean clLoaded; private String encoding; public JsModuleSourceMapper(Context context, ModuleManager moduleManager, String encoding) { super(context, moduleManager); this.encoding = encoding; } protected void loadModuleFromMap(ArtifactResult artifact, Module module, LinkedList<Module> dependencyTree, List<PhasedUnits> phasedUnitsOfDependencies, boolean forCompiledModule, Map<String, Object> model) { @SuppressWarnings("unchecked") List<Object> deps = (List<Object>)model.get("$mod-deps"); if (deps != null) { for (Object dep : deps) { final String s; boolean optional = false; boolean export = false; if (dep instanceof Map) { @SuppressWarnings("unchecked") final Map<String,Object> depmap = (Map<String,Object>)dep; s = (String)depmap.get("path"); optional = depmap.containsKey("opt"); export = depmap.containsKey("exp"); } else { s = (String)dep; } int p = s.indexOf('/'); String depname = null; String depv = null; if (p > 0) { depname = s.substring(0,p); depv = s.substring(p+1); if (depv.isEmpty()) { depv = null; } //TODO Remove this hack after next bin compat breaks if (Module.LANGUAGE_MODULE_NAME.equals(depname) && "1.1.0".equals(depv)) { depv = "1.2.0"; } } else { depname = s; } //This will cause the dependency to be loaded later JsonModule mod = (JsonModule)getModuleManager().getOrCreateModule( ModuleManager.splitModuleName(depname), depv); Backends backends = mod.getNativeBackends(); ModuleImport imp = new ModuleImport(mod, optional, export, backends); module.addImport(imp); } model.remove("$mod-deps"); } ((JsonModule)module).setModel(model); for (ModuleImport imp : module.getImports()) { if (!imp.getModule().getNameAsString().equals(Module.LANGUAGE_MODULE_NAME)) { ArtifactContext ac = new ArtifactContext(imp.getModule().getNameAsString(), imp.getModule().getVersion(), ArtifactContext.JS_MODEL); artifact = getContext().getRepositoryManager().getArtifactResult(ac); if (artifact != null) { resolveModule(artifact, imp.getModule(), imp, dependencyTree, phasedUnitsOfDependencies, forCompiledModule & imp.isExport()); } } } ((JsonModule)module).loadDeclarations(); return; } /** Read the metamodel declaration from a js file, * check it's the right version and return the model as a Map. */ public static Map<String,Object> loadJsonModel(File jsFile) { try { Map<String,Object> model = JSUtils.readJsonModel(jsFile); if (model == null) { throw new CompilerErrorException("Can't find metamodel definition in " + jsFile.getAbsolutePath()); } if (!model.containsKey("$mod-bin")) {
// Path: src/main/java/com/redhat/ceylon/compiler/js/CeylonRunJsException.java // public class CeylonRunJsException extends ToolError { // // private static final long serialVersionUID = 1L; // // public CeylonRunJsException(String message) { // super(message); // } // // public CeylonRunJsException(String message, int exitCode) { // super(message, exitCode); // } // } // // Path: src/main/java/com/redhat/ceylon/compiler/js/CompilerErrorException.java // public class CompilerErrorException extends ToolError { // // private static final long serialVersionUID = 5L; // // public CompilerErrorException(String message) { // super(message); // } // } // Path: src/main/java/com/redhat/ceylon/compiler/js/loader/JsModuleSourceMapper.java import java.io.File; import java.io.IOException; import java.util.LinkedList; import java.util.List; import java.util.Map; import com.redhat.ceylon.cmr.api.ArtifactContext; import com.redhat.ceylon.cmr.impl.JSUtils; import com.redhat.ceylon.common.Backends; import com.redhat.ceylon.common.config.CeylonConfig; import com.redhat.ceylon.common.config.DefaultToolOptions; import com.redhat.ceylon.compiler.js.CeylonRunJsException; import com.redhat.ceylon.compiler.js.CompilerErrorException; import com.redhat.ceylon.compiler.typechecker.analyzer.ModuleSourceMapper; import com.redhat.ceylon.compiler.typechecker.context.Context; import com.redhat.ceylon.compiler.typechecker.context.PhasedUnits; import com.redhat.ceylon.model.cmr.ArtifactResult; import com.redhat.ceylon.model.typechecker.model.Module; import com.redhat.ceylon.model.typechecker.model.ModuleImport; import com.redhat.ceylon.model.typechecker.util.ModuleManager; package com.redhat.ceylon.compiler.js.loader; public class JsModuleSourceMapper extends ModuleSourceMapper { /** Tells whether the language module has been loaded yet. */ private boolean clLoaded; private String encoding; public JsModuleSourceMapper(Context context, ModuleManager moduleManager, String encoding) { super(context, moduleManager); this.encoding = encoding; } protected void loadModuleFromMap(ArtifactResult artifact, Module module, LinkedList<Module> dependencyTree, List<PhasedUnits> phasedUnitsOfDependencies, boolean forCompiledModule, Map<String, Object> model) { @SuppressWarnings("unchecked") List<Object> deps = (List<Object>)model.get("$mod-deps"); if (deps != null) { for (Object dep : deps) { final String s; boolean optional = false; boolean export = false; if (dep instanceof Map) { @SuppressWarnings("unchecked") final Map<String,Object> depmap = (Map<String,Object>)dep; s = (String)depmap.get("path"); optional = depmap.containsKey("opt"); export = depmap.containsKey("exp"); } else { s = (String)dep; } int p = s.indexOf('/'); String depname = null; String depv = null; if (p > 0) { depname = s.substring(0,p); depv = s.substring(p+1); if (depv.isEmpty()) { depv = null; } //TODO Remove this hack after next bin compat breaks if (Module.LANGUAGE_MODULE_NAME.equals(depname) && "1.1.0".equals(depv)) { depv = "1.2.0"; } } else { depname = s; } //This will cause the dependency to be loaded later JsonModule mod = (JsonModule)getModuleManager().getOrCreateModule( ModuleManager.splitModuleName(depname), depv); Backends backends = mod.getNativeBackends(); ModuleImport imp = new ModuleImport(mod, optional, export, backends); module.addImport(imp); } model.remove("$mod-deps"); } ((JsonModule)module).setModel(model); for (ModuleImport imp : module.getImports()) { if (!imp.getModule().getNameAsString().equals(Module.LANGUAGE_MODULE_NAME)) { ArtifactContext ac = new ArtifactContext(imp.getModule().getNameAsString(), imp.getModule().getVersion(), ArtifactContext.JS_MODEL); artifact = getContext().getRepositoryManager().getArtifactResult(ac); if (artifact != null) { resolveModule(artifact, imp.getModule(), imp, dependencyTree, phasedUnitsOfDependencies, forCompiledModule & imp.isExport()); } } } ((JsonModule)module).loadDeclarations(); return; } /** Read the metamodel declaration from a js file, * check it's the right version and return the model as a Map. */ public static Map<String,Object> loadJsonModel(File jsFile) { try { Map<String,Object> model = JSUtils.readJsonModel(jsFile); if (model == null) { throw new CompilerErrorException("Can't find metamodel definition in " + jsFile.getAbsolutePath()); } if (!model.containsKey("$mod-bin")) {
throw new CeylonRunJsException("The JavaScript module " + jsFile +
ceylon/ceylon-js
src/main/java/com/redhat/ceylon/compiler/js/loader/JsonPackage.java
// Path: src/main/java/com/redhat/ceylon/compiler/js/CompilerErrorException.java // public class CompilerErrorException extends ToolError { // // private static final long serialVersionUID = 5L; // // public CompilerErrorException(String message) { // super(message); // } // }
import static com.redhat.ceylon.model.typechecker.model.ModelUtil.getSignature; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import com.redhat.ceylon.common.Backend; import com.redhat.ceylon.common.Backends; import com.redhat.ceylon.compiler.js.CompilerErrorException; import com.redhat.ceylon.model.typechecker.model.Annotation; import com.redhat.ceylon.model.typechecker.model.ClassOrInterface; import com.redhat.ceylon.model.typechecker.model.Constructor; import com.redhat.ceylon.model.typechecker.model.Declaration; import com.redhat.ceylon.model.typechecker.model.Function; import com.redhat.ceylon.model.typechecker.model.FunctionOrValue; import com.redhat.ceylon.model.typechecker.model.Generic; import com.redhat.ceylon.model.typechecker.model.Interface; import com.redhat.ceylon.model.typechecker.model.InterfaceAlias; import com.redhat.ceylon.model.typechecker.model.IntersectionType; import com.redhat.ceylon.model.typechecker.model.Module; import com.redhat.ceylon.model.typechecker.model.NothingType; import com.redhat.ceylon.model.typechecker.model.Parameter; import com.redhat.ceylon.model.typechecker.model.ParameterList; import com.redhat.ceylon.model.typechecker.model.Scope; import com.redhat.ceylon.model.typechecker.model.Setter; import com.redhat.ceylon.model.typechecker.model.SiteVariance; import com.redhat.ceylon.model.typechecker.model.Type; import com.redhat.ceylon.model.typechecker.model.TypeAlias; import com.redhat.ceylon.model.typechecker.model.TypeDeclaration; import com.redhat.ceylon.model.typechecker.model.TypeParameter; import com.redhat.ceylon.model.typechecker.model.UnionType; import com.redhat.ceylon.model.typechecker.model.Unit; import com.redhat.ceylon.model.typechecker.model.UnknownType; import com.redhat.ceylon.model.typechecker.model.Value; import com.redhat.ceylon.model.typechecker.util.ModuleManager;
for (TypeParameter typeParam : typeParams) { if (typeParam.getName().equals(tname)) { td = typeParam; } } } } else { String mname = (String)m.get(MetamodelGenerator.KEY_MODULE); if ("$".equals(mname)) { mname = Module.LANGUAGE_MODULE_NAME; } com.redhat.ceylon.model.typechecker.model.Package rp; if ("$".equals(pname)) { //Language module package rp = Module.LANGUAGE_MODULE_NAME.equals(getNameAsString())? this : getModule().getLanguageModule().getDirectPackage(Module.LANGUAGE_MODULE_NAME); } else if (mname == null) { //local type if (".".equals(pname)) { rp = this; if (container instanceof TypeDeclaration && tname.equals(container.getName())) { td = (TypeDeclaration)container; } } else { rp = getModule().getDirectPackage(pname); } } else { rp = getModule().getPackage(pname); } if (rp == null) {
// Path: src/main/java/com/redhat/ceylon/compiler/js/CompilerErrorException.java // public class CompilerErrorException extends ToolError { // // private static final long serialVersionUID = 5L; // // public CompilerErrorException(String message) { // super(message); // } // } // Path: src/main/java/com/redhat/ceylon/compiler/js/loader/JsonPackage.java import static com.redhat.ceylon.model.typechecker.model.ModelUtil.getSignature; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import com.redhat.ceylon.common.Backend; import com.redhat.ceylon.common.Backends; import com.redhat.ceylon.compiler.js.CompilerErrorException; import com.redhat.ceylon.model.typechecker.model.Annotation; import com.redhat.ceylon.model.typechecker.model.ClassOrInterface; import com.redhat.ceylon.model.typechecker.model.Constructor; import com.redhat.ceylon.model.typechecker.model.Declaration; import com.redhat.ceylon.model.typechecker.model.Function; import com.redhat.ceylon.model.typechecker.model.FunctionOrValue; import com.redhat.ceylon.model.typechecker.model.Generic; import com.redhat.ceylon.model.typechecker.model.Interface; import com.redhat.ceylon.model.typechecker.model.InterfaceAlias; import com.redhat.ceylon.model.typechecker.model.IntersectionType; import com.redhat.ceylon.model.typechecker.model.Module; import com.redhat.ceylon.model.typechecker.model.NothingType; import com.redhat.ceylon.model.typechecker.model.Parameter; import com.redhat.ceylon.model.typechecker.model.ParameterList; import com.redhat.ceylon.model.typechecker.model.Scope; import com.redhat.ceylon.model.typechecker.model.Setter; import com.redhat.ceylon.model.typechecker.model.SiteVariance; import com.redhat.ceylon.model.typechecker.model.Type; import com.redhat.ceylon.model.typechecker.model.TypeAlias; import com.redhat.ceylon.model.typechecker.model.TypeDeclaration; import com.redhat.ceylon.model.typechecker.model.TypeParameter; import com.redhat.ceylon.model.typechecker.model.UnionType; import com.redhat.ceylon.model.typechecker.model.Unit; import com.redhat.ceylon.model.typechecker.model.UnknownType; import com.redhat.ceylon.model.typechecker.model.Value; import com.redhat.ceylon.model.typechecker.util.ModuleManager; for (TypeParameter typeParam : typeParams) { if (typeParam.getName().equals(tname)) { td = typeParam; } } } } else { String mname = (String)m.get(MetamodelGenerator.KEY_MODULE); if ("$".equals(mname)) { mname = Module.LANGUAGE_MODULE_NAME; } com.redhat.ceylon.model.typechecker.model.Package rp; if ("$".equals(pname)) { //Language module package rp = Module.LANGUAGE_MODULE_NAME.equals(getNameAsString())? this : getModule().getLanguageModule().getDirectPackage(Module.LANGUAGE_MODULE_NAME); } else if (mname == null) { //local type if (".".equals(pname)) { rp = this; if (container instanceof TypeDeclaration && tname.equals(container.getName())) { td = (TypeDeclaration)container; } } else { rp = getModule().getDirectPackage(pname); } } else { rp = getModule().getPackage(pname); } if (rp == null) {
throw new CompilerErrorException("Package not found: " + pname);
srcdeps/srcdeps-core
srcdeps-core/src/main/java/org/srcdeps/core/config/tree/walk/DefaultsAndInheritanceVisitor.java
// Path: srcdeps-core/src/main/java/org/srcdeps/core/config/tree/ContainerNode.java // public interface ContainerNode<C extends Node> extends Node { // /** // * @return a map of child nodes // */ // Map<String, C> getChildren(); // // } // // Path: srcdeps-core/src/main/java/org/srcdeps/core/config/tree/ListNode.java // public interface ListNode<E extends Node> extends Node { // /** // * @return the elements of this {@link ListNode} // */ // List<E> getElements(); // } // // Path: srcdeps-core/src/main/java/org/srcdeps/core/config/tree/Node.java // public interface Node { // /** // * Apply the defaults or apply some kind of inheritance in case the values of some attributes were not set // * explicitly. See also {@link DefaultsAndInheritanceVisitor}. // * // * @param configurationStack the stack of ancestor configuration nodes. Can be queried to inherit values. // */ // void applyDefaultsAndInheritance(Stack<Node> configurationStack); // // /** // * @return a list of comment lines that should appear before this node // */ // List<String> getCommentBefore(); // // /** // * @return the name of the present node that is supposed to be unique within the parent node. Can be {@code null} in // * case this {@link Node} is an element of a {@link NodeList}. // */ // String getName(); // // /** // * Fully reset the state of this {@link Node} using the given {@code source} {@link Node}. // * // * @param source the {@link Node} to take the values from // */ // void init(Node source); // // /** // * @param stack the ancestor hierarchy of this {@link Node} // * @return {@code true} if this {@link Node}'s internal state has not been set yet or if the state is in the // * instance or implementation specific default state. Otherwise returns {@code false} // */ // boolean isInDefaultState(Stack<Node> stack); // // /** // * @return {@code true} if the name of the node will commonly contain special characters, esp. periods. Otherwise // * returns {@code false} // */ // boolean shouldEscapeName(); // } // // Path: srcdeps-core/src/main/java/org/srcdeps/core/config/tree/ScalarNode.java // public interface ScalarNode<T> extends Node { // /** // * @return the default value to be used if the value of this {@link ScalarNode} is not set explicitly // */ // T getDefaultValue(); // // /** // * @return the type of the value // */ // Class<T> getType(); // // /** // * @return the value stored in this {@link ScalarNode} // */ // T getValue(); // // /** // * Sets the value stored in this {@link ScalarNode}. // * // * @param value the value to set // */ // void setValue(T value); // } // // Path: srcdeps-core/src/main/java/org/srcdeps/core/config/tree/Visitor.java // public interface Visitor { // // /** // * Check whether the children of the given {@link ContainerNode} should be visited. // * // * @param node the current {@link ContainerNode} // * @return {@code true} if the calling walker should traverse the children of the given {@code node}; {@code false} // * otherwise // */ // boolean containerBegin(ContainerNode<? extends Node> node); // // /** // * Called just after {@link #containerBegin(ContainerNode)} if it returned {@code true} or after the children of a // * {@link ContainerNode} were visited. // */ // void containerEnd(); // // /** // * Check whether the elements of the given {@link ListNode} should be visited. // * // * @param node the current {@link ListNode} // * @return {@code true} if the calling walker should traverse the elements of the given {@code node}; {@code false} // * otherwise // */ // boolean listBegin(ListNode<? extends Node> node); // // /** // * Called just after {@link #containerBegin(ContainerNode)} if it returned {@code true} or after the children of a // * {@link ListNode} were visited. // */ // void listEnd(); // // /** // * Visit the given {@link ScalarNode}. // * // * @param node the {@link ScalarNode} to visit // */ // void scalar(ScalarNode<Object> node); // // }
import java.util.List; import org.srcdeps.core.config.tree.ContainerNode; import org.srcdeps.core.config.tree.ListNode; import org.srcdeps.core.config.tree.Node; import org.srcdeps.core.config.tree.ScalarNode; import org.srcdeps.core.config.tree.Visitor;
/** * Copyright 2015-2016 Maven Source Dependencies * Plugin contributors as indicated by the @author tags. * * 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.srcdeps.core.config.tree.walk; /** * A {@link Visitor} that calls {@link DefaultsAndInheritanceReceiver#applyDefaultsAndInheritance(List)} for each node * of a tree. * * @author <a href="https://github.com/ppalaga">Peter Palaga</a> */ public class DefaultsAndInheritanceVisitor extends AbstractVisitor { @Override
// Path: srcdeps-core/src/main/java/org/srcdeps/core/config/tree/ContainerNode.java // public interface ContainerNode<C extends Node> extends Node { // /** // * @return a map of child nodes // */ // Map<String, C> getChildren(); // // } // // Path: srcdeps-core/src/main/java/org/srcdeps/core/config/tree/ListNode.java // public interface ListNode<E extends Node> extends Node { // /** // * @return the elements of this {@link ListNode} // */ // List<E> getElements(); // } // // Path: srcdeps-core/src/main/java/org/srcdeps/core/config/tree/Node.java // public interface Node { // /** // * Apply the defaults or apply some kind of inheritance in case the values of some attributes were not set // * explicitly. See also {@link DefaultsAndInheritanceVisitor}. // * // * @param configurationStack the stack of ancestor configuration nodes. Can be queried to inherit values. // */ // void applyDefaultsAndInheritance(Stack<Node> configurationStack); // // /** // * @return a list of comment lines that should appear before this node // */ // List<String> getCommentBefore(); // // /** // * @return the name of the present node that is supposed to be unique within the parent node. Can be {@code null} in // * case this {@link Node} is an element of a {@link NodeList}. // */ // String getName(); // // /** // * Fully reset the state of this {@link Node} using the given {@code source} {@link Node}. // * // * @param source the {@link Node} to take the values from // */ // void init(Node source); // // /** // * @param stack the ancestor hierarchy of this {@link Node} // * @return {@code true} if this {@link Node}'s internal state has not been set yet or if the state is in the // * instance or implementation specific default state. Otherwise returns {@code false} // */ // boolean isInDefaultState(Stack<Node> stack); // // /** // * @return {@code true} if the name of the node will commonly contain special characters, esp. periods. Otherwise // * returns {@code false} // */ // boolean shouldEscapeName(); // } // // Path: srcdeps-core/src/main/java/org/srcdeps/core/config/tree/ScalarNode.java // public interface ScalarNode<T> extends Node { // /** // * @return the default value to be used if the value of this {@link ScalarNode} is not set explicitly // */ // T getDefaultValue(); // // /** // * @return the type of the value // */ // Class<T> getType(); // // /** // * @return the value stored in this {@link ScalarNode} // */ // T getValue(); // // /** // * Sets the value stored in this {@link ScalarNode}. // * // * @param value the value to set // */ // void setValue(T value); // } // // Path: srcdeps-core/src/main/java/org/srcdeps/core/config/tree/Visitor.java // public interface Visitor { // // /** // * Check whether the children of the given {@link ContainerNode} should be visited. // * // * @param node the current {@link ContainerNode} // * @return {@code true} if the calling walker should traverse the children of the given {@code node}; {@code false} // * otherwise // */ // boolean containerBegin(ContainerNode<? extends Node> node); // // /** // * Called just after {@link #containerBegin(ContainerNode)} if it returned {@code true} or after the children of a // * {@link ContainerNode} were visited. // */ // void containerEnd(); // // /** // * Check whether the elements of the given {@link ListNode} should be visited. // * // * @param node the current {@link ListNode} // * @return {@code true} if the calling walker should traverse the elements of the given {@code node}; {@code false} // * otherwise // */ // boolean listBegin(ListNode<? extends Node> node); // // /** // * Called just after {@link #containerBegin(ContainerNode)} if it returned {@code true} or after the children of a // * {@link ListNode} were visited. // */ // void listEnd(); // // /** // * Visit the given {@link ScalarNode}. // * // * @param node the {@link ScalarNode} to visit // */ // void scalar(ScalarNode<Object> node); // // } // Path: srcdeps-core/src/main/java/org/srcdeps/core/config/tree/walk/DefaultsAndInheritanceVisitor.java import java.util.List; import org.srcdeps.core.config.tree.ContainerNode; import org.srcdeps.core.config.tree.ListNode; import org.srcdeps.core.config.tree.Node; import org.srcdeps.core.config.tree.ScalarNode; import org.srcdeps.core.config.tree.Visitor; /** * Copyright 2015-2016 Maven Source Dependencies * Plugin contributors as indicated by the @author tags. * * 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.srcdeps.core.config.tree.walk; /** * A {@link Visitor} that calls {@link DefaultsAndInheritanceReceiver#applyDefaultsAndInheritance(List)} for each node * of a tree. * * @author <a href="https://github.com/ppalaga">Peter Palaga</a> */ public class DefaultsAndInheritanceVisitor extends AbstractVisitor { @Override
public boolean containerBegin(ContainerNode<? extends Node> node) {
srcdeps/srcdeps-core
srcdeps-core/src/main/java/org/srcdeps/core/config/tree/walk/DefaultsAndInheritanceVisitor.java
// Path: srcdeps-core/src/main/java/org/srcdeps/core/config/tree/ContainerNode.java // public interface ContainerNode<C extends Node> extends Node { // /** // * @return a map of child nodes // */ // Map<String, C> getChildren(); // // } // // Path: srcdeps-core/src/main/java/org/srcdeps/core/config/tree/ListNode.java // public interface ListNode<E extends Node> extends Node { // /** // * @return the elements of this {@link ListNode} // */ // List<E> getElements(); // } // // Path: srcdeps-core/src/main/java/org/srcdeps/core/config/tree/Node.java // public interface Node { // /** // * Apply the defaults or apply some kind of inheritance in case the values of some attributes were not set // * explicitly. See also {@link DefaultsAndInheritanceVisitor}. // * // * @param configurationStack the stack of ancestor configuration nodes. Can be queried to inherit values. // */ // void applyDefaultsAndInheritance(Stack<Node> configurationStack); // // /** // * @return a list of comment lines that should appear before this node // */ // List<String> getCommentBefore(); // // /** // * @return the name of the present node that is supposed to be unique within the parent node. Can be {@code null} in // * case this {@link Node} is an element of a {@link NodeList}. // */ // String getName(); // // /** // * Fully reset the state of this {@link Node} using the given {@code source} {@link Node}. // * // * @param source the {@link Node} to take the values from // */ // void init(Node source); // // /** // * @param stack the ancestor hierarchy of this {@link Node} // * @return {@code true} if this {@link Node}'s internal state has not been set yet or if the state is in the // * instance or implementation specific default state. Otherwise returns {@code false} // */ // boolean isInDefaultState(Stack<Node> stack); // // /** // * @return {@code true} if the name of the node will commonly contain special characters, esp. periods. Otherwise // * returns {@code false} // */ // boolean shouldEscapeName(); // } // // Path: srcdeps-core/src/main/java/org/srcdeps/core/config/tree/ScalarNode.java // public interface ScalarNode<T> extends Node { // /** // * @return the default value to be used if the value of this {@link ScalarNode} is not set explicitly // */ // T getDefaultValue(); // // /** // * @return the type of the value // */ // Class<T> getType(); // // /** // * @return the value stored in this {@link ScalarNode} // */ // T getValue(); // // /** // * Sets the value stored in this {@link ScalarNode}. // * // * @param value the value to set // */ // void setValue(T value); // } // // Path: srcdeps-core/src/main/java/org/srcdeps/core/config/tree/Visitor.java // public interface Visitor { // // /** // * Check whether the children of the given {@link ContainerNode} should be visited. // * // * @param node the current {@link ContainerNode} // * @return {@code true} if the calling walker should traverse the children of the given {@code node}; {@code false} // * otherwise // */ // boolean containerBegin(ContainerNode<? extends Node> node); // // /** // * Called just after {@link #containerBegin(ContainerNode)} if it returned {@code true} or after the children of a // * {@link ContainerNode} were visited. // */ // void containerEnd(); // // /** // * Check whether the elements of the given {@link ListNode} should be visited. // * // * @param node the current {@link ListNode} // * @return {@code true} if the calling walker should traverse the elements of the given {@code node}; {@code false} // * otherwise // */ // boolean listBegin(ListNode<? extends Node> node); // // /** // * Called just after {@link #containerBegin(ContainerNode)} if it returned {@code true} or after the children of a // * {@link ListNode} were visited. // */ // void listEnd(); // // /** // * Visit the given {@link ScalarNode}. // * // * @param node the {@link ScalarNode} to visit // */ // void scalar(ScalarNode<Object> node); // // }
import java.util.List; import org.srcdeps.core.config.tree.ContainerNode; import org.srcdeps.core.config.tree.ListNode; import org.srcdeps.core.config.tree.Node; import org.srcdeps.core.config.tree.ScalarNode; import org.srcdeps.core.config.tree.Visitor;
/** * Copyright 2015-2016 Maven Source Dependencies * Plugin contributors as indicated by the @author tags. * * 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.srcdeps.core.config.tree.walk; /** * A {@link Visitor} that calls {@link DefaultsAndInheritanceReceiver#applyDefaultsAndInheritance(List)} for each node * of a tree. * * @author <a href="https://github.com/ppalaga">Peter Palaga</a> */ public class DefaultsAndInheritanceVisitor extends AbstractVisitor { @Override
// Path: srcdeps-core/src/main/java/org/srcdeps/core/config/tree/ContainerNode.java // public interface ContainerNode<C extends Node> extends Node { // /** // * @return a map of child nodes // */ // Map<String, C> getChildren(); // // } // // Path: srcdeps-core/src/main/java/org/srcdeps/core/config/tree/ListNode.java // public interface ListNode<E extends Node> extends Node { // /** // * @return the elements of this {@link ListNode} // */ // List<E> getElements(); // } // // Path: srcdeps-core/src/main/java/org/srcdeps/core/config/tree/Node.java // public interface Node { // /** // * Apply the defaults or apply some kind of inheritance in case the values of some attributes were not set // * explicitly. See also {@link DefaultsAndInheritanceVisitor}. // * // * @param configurationStack the stack of ancestor configuration nodes. Can be queried to inherit values. // */ // void applyDefaultsAndInheritance(Stack<Node> configurationStack); // // /** // * @return a list of comment lines that should appear before this node // */ // List<String> getCommentBefore(); // // /** // * @return the name of the present node that is supposed to be unique within the parent node. Can be {@code null} in // * case this {@link Node} is an element of a {@link NodeList}. // */ // String getName(); // // /** // * Fully reset the state of this {@link Node} using the given {@code source} {@link Node}. // * // * @param source the {@link Node} to take the values from // */ // void init(Node source); // // /** // * @param stack the ancestor hierarchy of this {@link Node} // * @return {@code true} if this {@link Node}'s internal state has not been set yet or if the state is in the // * instance or implementation specific default state. Otherwise returns {@code false} // */ // boolean isInDefaultState(Stack<Node> stack); // // /** // * @return {@code true} if the name of the node will commonly contain special characters, esp. periods. Otherwise // * returns {@code false} // */ // boolean shouldEscapeName(); // } // // Path: srcdeps-core/src/main/java/org/srcdeps/core/config/tree/ScalarNode.java // public interface ScalarNode<T> extends Node { // /** // * @return the default value to be used if the value of this {@link ScalarNode} is not set explicitly // */ // T getDefaultValue(); // // /** // * @return the type of the value // */ // Class<T> getType(); // // /** // * @return the value stored in this {@link ScalarNode} // */ // T getValue(); // // /** // * Sets the value stored in this {@link ScalarNode}. // * // * @param value the value to set // */ // void setValue(T value); // } // // Path: srcdeps-core/src/main/java/org/srcdeps/core/config/tree/Visitor.java // public interface Visitor { // // /** // * Check whether the children of the given {@link ContainerNode} should be visited. // * // * @param node the current {@link ContainerNode} // * @return {@code true} if the calling walker should traverse the children of the given {@code node}; {@code false} // * otherwise // */ // boolean containerBegin(ContainerNode<? extends Node> node); // // /** // * Called just after {@link #containerBegin(ContainerNode)} if it returned {@code true} or after the children of a // * {@link ContainerNode} were visited. // */ // void containerEnd(); // // /** // * Check whether the elements of the given {@link ListNode} should be visited. // * // * @param node the current {@link ListNode} // * @return {@code true} if the calling walker should traverse the elements of the given {@code node}; {@code false} // * otherwise // */ // boolean listBegin(ListNode<? extends Node> node); // // /** // * Called just after {@link #containerBegin(ContainerNode)} if it returned {@code true} or after the children of a // * {@link ListNode} were visited. // */ // void listEnd(); // // /** // * Visit the given {@link ScalarNode}. // * // * @param node the {@link ScalarNode} to visit // */ // void scalar(ScalarNode<Object> node); // // } // Path: srcdeps-core/src/main/java/org/srcdeps/core/config/tree/walk/DefaultsAndInheritanceVisitor.java import java.util.List; import org.srcdeps.core.config.tree.ContainerNode; import org.srcdeps.core.config.tree.ListNode; import org.srcdeps.core.config.tree.Node; import org.srcdeps.core.config.tree.ScalarNode; import org.srcdeps.core.config.tree.Visitor; /** * Copyright 2015-2016 Maven Source Dependencies * Plugin contributors as indicated by the @author tags. * * 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.srcdeps.core.config.tree.walk; /** * A {@link Visitor} that calls {@link DefaultsAndInheritanceReceiver#applyDefaultsAndInheritance(List)} for each node * of a tree. * * @author <a href="https://github.com/ppalaga">Peter Palaga</a> */ public class DefaultsAndInheritanceVisitor extends AbstractVisitor { @Override
public boolean containerBegin(ContainerNode<? extends Node> node) {
srcdeps/srcdeps-core
srcdeps-core/src/main/java/org/srcdeps/core/config/tree/walk/DefaultsAndInheritanceVisitor.java
// Path: srcdeps-core/src/main/java/org/srcdeps/core/config/tree/ContainerNode.java // public interface ContainerNode<C extends Node> extends Node { // /** // * @return a map of child nodes // */ // Map<String, C> getChildren(); // // } // // Path: srcdeps-core/src/main/java/org/srcdeps/core/config/tree/ListNode.java // public interface ListNode<E extends Node> extends Node { // /** // * @return the elements of this {@link ListNode} // */ // List<E> getElements(); // } // // Path: srcdeps-core/src/main/java/org/srcdeps/core/config/tree/Node.java // public interface Node { // /** // * Apply the defaults or apply some kind of inheritance in case the values of some attributes were not set // * explicitly. See also {@link DefaultsAndInheritanceVisitor}. // * // * @param configurationStack the stack of ancestor configuration nodes. Can be queried to inherit values. // */ // void applyDefaultsAndInheritance(Stack<Node> configurationStack); // // /** // * @return a list of comment lines that should appear before this node // */ // List<String> getCommentBefore(); // // /** // * @return the name of the present node that is supposed to be unique within the parent node. Can be {@code null} in // * case this {@link Node} is an element of a {@link NodeList}. // */ // String getName(); // // /** // * Fully reset the state of this {@link Node} using the given {@code source} {@link Node}. // * // * @param source the {@link Node} to take the values from // */ // void init(Node source); // // /** // * @param stack the ancestor hierarchy of this {@link Node} // * @return {@code true} if this {@link Node}'s internal state has not been set yet or if the state is in the // * instance or implementation specific default state. Otherwise returns {@code false} // */ // boolean isInDefaultState(Stack<Node> stack); // // /** // * @return {@code true} if the name of the node will commonly contain special characters, esp. periods. Otherwise // * returns {@code false} // */ // boolean shouldEscapeName(); // } // // Path: srcdeps-core/src/main/java/org/srcdeps/core/config/tree/ScalarNode.java // public interface ScalarNode<T> extends Node { // /** // * @return the default value to be used if the value of this {@link ScalarNode} is not set explicitly // */ // T getDefaultValue(); // // /** // * @return the type of the value // */ // Class<T> getType(); // // /** // * @return the value stored in this {@link ScalarNode} // */ // T getValue(); // // /** // * Sets the value stored in this {@link ScalarNode}. // * // * @param value the value to set // */ // void setValue(T value); // } // // Path: srcdeps-core/src/main/java/org/srcdeps/core/config/tree/Visitor.java // public interface Visitor { // // /** // * Check whether the children of the given {@link ContainerNode} should be visited. // * // * @param node the current {@link ContainerNode} // * @return {@code true} if the calling walker should traverse the children of the given {@code node}; {@code false} // * otherwise // */ // boolean containerBegin(ContainerNode<? extends Node> node); // // /** // * Called just after {@link #containerBegin(ContainerNode)} if it returned {@code true} or after the children of a // * {@link ContainerNode} were visited. // */ // void containerEnd(); // // /** // * Check whether the elements of the given {@link ListNode} should be visited. // * // * @param node the current {@link ListNode} // * @return {@code true} if the calling walker should traverse the elements of the given {@code node}; {@code false} // * otherwise // */ // boolean listBegin(ListNode<? extends Node> node); // // /** // * Called just after {@link #containerBegin(ContainerNode)} if it returned {@code true} or after the children of a // * {@link ListNode} were visited. // */ // void listEnd(); // // /** // * Visit the given {@link ScalarNode}. // * // * @param node the {@link ScalarNode} to visit // */ // void scalar(ScalarNode<Object> node); // // }
import java.util.List; import org.srcdeps.core.config.tree.ContainerNode; import org.srcdeps.core.config.tree.ListNode; import org.srcdeps.core.config.tree.Node; import org.srcdeps.core.config.tree.ScalarNode; import org.srcdeps.core.config.tree.Visitor;
/** * Copyright 2015-2016 Maven Source Dependencies * Plugin contributors as indicated by the @author tags. * * 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.srcdeps.core.config.tree.walk; /** * A {@link Visitor} that calls {@link DefaultsAndInheritanceReceiver#applyDefaultsAndInheritance(List)} for each node * of a tree. * * @author <a href="https://github.com/ppalaga">Peter Palaga</a> */ public class DefaultsAndInheritanceVisitor extends AbstractVisitor { @Override public boolean containerBegin(ContainerNode<? extends Node> node) { super.containerBegin(node); node.applyDefaultsAndInheritance(stack); return true; } @Override
// Path: srcdeps-core/src/main/java/org/srcdeps/core/config/tree/ContainerNode.java // public interface ContainerNode<C extends Node> extends Node { // /** // * @return a map of child nodes // */ // Map<String, C> getChildren(); // // } // // Path: srcdeps-core/src/main/java/org/srcdeps/core/config/tree/ListNode.java // public interface ListNode<E extends Node> extends Node { // /** // * @return the elements of this {@link ListNode} // */ // List<E> getElements(); // } // // Path: srcdeps-core/src/main/java/org/srcdeps/core/config/tree/Node.java // public interface Node { // /** // * Apply the defaults or apply some kind of inheritance in case the values of some attributes were not set // * explicitly. See also {@link DefaultsAndInheritanceVisitor}. // * // * @param configurationStack the stack of ancestor configuration nodes. Can be queried to inherit values. // */ // void applyDefaultsAndInheritance(Stack<Node> configurationStack); // // /** // * @return a list of comment lines that should appear before this node // */ // List<String> getCommentBefore(); // // /** // * @return the name of the present node that is supposed to be unique within the parent node. Can be {@code null} in // * case this {@link Node} is an element of a {@link NodeList}. // */ // String getName(); // // /** // * Fully reset the state of this {@link Node} using the given {@code source} {@link Node}. // * // * @param source the {@link Node} to take the values from // */ // void init(Node source); // // /** // * @param stack the ancestor hierarchy of this {@link Node} // * @return {@code true} if this {@link Node}'s internal state has not been set yet or if the state is in the // * instance or implementation specific default state. Otherwise returns {@code false} // */ // boolean isInDefaultState(Stack<Node> stack); // // /** // * @return {@code true} if the name of the node will commonly contain special characters, esp. periods. Otherwise // * returns {@code false} // */ // boolean shouldEscapeName(); // } // // Path: srcdeps-core/src/main/java/org/srcdeps/core/config/tree/ScalarNode.java // public interface ScalarNode<T> extends Node { // /** // * @return the default value to be used if the value of this {@link ScalarNode} is not set explicitly // */ // T getDefaultValue(); // // /** // * @return the type of the value // */ // Class<T> getType(); // // /** // * @return the value stored in this {@link ScalarNode} // */ // T getValue(); // // /** // * Sets the value stored in this {@link ScalarNode}. // * // * @param value the value to set // */ // void setValue(T value); // } // // Path: srcdeps-core/src/main/java/org/srcdeps/core/config/tree/Visitor.java // public interface Visitor { // // /** // * Check whether the children of the given {@link ContainerNode} should be visited. // * // * @param node the current {@link ContainerNode} // * @return {@code true} if the calling walker should traverse the children of the given {@code node}; {@code false} // * otherwise // */ // boolean containerBegin(ContainerNode<? extends Node> node); // // /** // * Called just after {@link #containerBegin(ContainerNode)} if it returned {@code true} or after the children of a // * {@link ContainerNode} were visited. // */ // void containerEnd(); // // /** // * Check whether the elements of the given {@link ListNode} should be visited. // * // * @param node the current {@link ListNode} // * @return {@code true} if the calling walker should traverse the elements of the given {@code node}; {@code false} // * otherwise // */ // boolean listBegin(ListNode<? extends Node> node); // // /** // * Called just after {@link #containerBegin(ContainerNode)} if it returned {@code true} or after the children of a // * {@link ListNode} were visited. // */ // void listEnd(); // // /** // * Visit the given {@link ScalarNode}. // * // * @param node the {@link ScalarNode} to visit // */ // void scalar(ScalarNode<Object> node); // // } // Path: srcdeps-core/src/main/java/org/srcdeps/core/config/tree/walk/DefaultsAndInheritanceVisitor.java import java.util.List; import org.srcdeps.core.config.tree.ContainerNode; import org.srcdeps.core.config.tree.ListNode; import org.srcdeps.core.config.tree.Node; import org.srcdeps.core.config.tree.ScalarNode; import org.srcdeps.core.config.tree.Visitor; /** * Copyright 2015-2016 Maven Source Dependencies * Plugin contributors as indicated by the @author tags. * * 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.srcdeps.core.config.tree.walk; /** * A {@link Visitor} that calls {@link DefaultsAndInheritanceReceiver#applyDefaultsAndInheritance(List)} for each node * of a tree. * * @author <a href="https://github.com/ppalaga">Peter Palaga</a> */ public class DefaultsAndInheritanceVisitor extends AbstractVisitor { @Override public boolean containerBegin(ContainerNode<? extends Node> node) { super.containerBegin(node); node.applyDefaultsAndInheritance(stack); return true; } @Override
public boolean listBegin(ListNode<? extends Node> node) {
srcdeps/srcdeps-core
srcdeps-core/src/main/java/org/srcdeps/core/config/tree/walk/DefaultsAndInheritanceVisitor.java
// Path: srcdeps-core/src/main/java/org/srcdeps/core/config/tree/ContainerNode.java // public interface ContainerNode<C extends Node> extends Node { // /** // * @return a map of child nodes // */ // Map<String, C> getChildren(); // // } // // Path: srcdeps-core/src/main/java/org/srcdeps/core/config/tree/ListNode.java // public interface ListNode<E extends Node> extends Node { // /** // * @return the elements of this {@link ListNode} // */ // List<E> getElements(); // } // // Path: srcdeps-core/src/main/java/org/srcdeps/core/config/tree/Node.java // public interface Node { // /** // * Apply the defaults or apply some kind of inheritance in case the values of some attributes were not set // * explicitly. See also {@link DefaultsAndInheritanceVisitor}. // * // * @param configurationStack the stack of ancestor configuration nodes. Can be queried to inherit values. // */ // void applyDefaultsAndInheritance(Stack<Node> configurationStack); // // /** // * @return a list of comment lines that should appear before this node // */ // List<String> getCommentBefore(); // // /** // * @return the name of the present node that is supposed to be unique within the parent node. Can be {@code null} in // * case this {@link Node} is an element of a {@link NodeList}. // */ // String getName(); // // /** // * Fully reset the state of this {@link Node} using the given {@code source} {@link Node}. // * // * @param source the {@link Node} to take the values from // */ // void init(Node source); // // /** // * @param stack the ancestor hierarchy of this {@link Node} // * @return {@code true} if this {@link Node}'s internal state has not been set yet or if the state is in the // * instance or implementation specific default state. Otherwise returns {@code false} // */ // boolean isInDefaultState(Stack<Node> stack); // // /** // * @return {@code true} if the name of the node will commonly contain special characters, esp. periods. Otherwise // * returns {@code false} // */ // boolean shouldEscapeName(); // } // // Path: srcdeps-core/src/main/java/org/srcdeps/core/config/tree/ScalarNode.java // public interface ScalarNode<T> extends Node { // /** // * @return the default value to be used if the value of this {@link ScalarNode} is not set explicitly // */ // T getDefaultValue(); // // /** // * @return the type of the value // */ // Class<T> getType(); // // /** // * @return the value stored in this {@link ScalarNode} // */ // T getValue(); // // /** // * Sets the value stored in this {@link ScalarNode}. // * // * @param value the value to set // */ // void setValue(T value); // } // // Path: srcdeps-core/src/main/java/org/srcdeps/core/config/tree/Visitor.java // public interface Visitor { // // /** // * Check whether the children of the given {@link ContainerNode} should be visited. // * // * @param node the current {@link ContainerNode} // * @return {@code true} if the calling walker should traverse the children of the given {@code node}; {@code false} // * otherwise // */ // boolean containerBegin(ContainerNode<? extends Node> node); // // /** // * Called just after {@link #containerBegin(ContainerNode)} if it returned {@code true} or after the children of a // * {@link ContainerNode} were visited. // */ // void containerEnd(); // // /** // * Check whether the elements of the given {@link ListNode} should be visited. // * // * @param node the current {@link ListNode} // * @return {@code true} if the calling walker should traverse the elements of the given {@code node}; {@code false} // * otherwise // */ // boolean listBegin(ListNode<? extends Node> node); // // /** // * Called just after {@link #containerBegin(ContainerNode)} if it returned {@code true} or after the children of a // * {@link ListNode} were visited. // */ // void listEnd(); // // /** // * Visit the given {@link ScalarNode}. // * // * @param node the {@link ScalarNode} to visit // */ // void scalar(ScalarNode<Object> node); // // }
import java.util.List; import org.srcdeps.core.config.tree.ContainerNode; import org.srcdeps.core.config.tree.ListNode; import org.srcdeps.core.config.tree.Node; import org.srcdeps.core.config.tree.ScalarNode; import org.srcdeps.core.config.tree.Visitor;
/** * Copyright 2015-2016 Maven Source Dependencies * Plugin contributors as indicated by the @author tags. * * 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.srcdeps.core.config.tree.walk; /** * A {@link Visitor} that calls {@link DefaultsAndInheritanceReceiver#applyDefaultsAndInheritance(List)} for each node * of a tree. * * @author <a href="https://github.com/ppalaga">Peter Palaga</a> */ public class DefaultsAndInheritanceVisitor extends AbstractVisitor { @Override public boolean containerBegin(ContainerNode<? extends Node> node) { super.containerBegin(node); node.applyDefaultsAndInheritance(stack); return true; } @Override public boolean listBegin(ListNode<? extends Node> node) { super.listBegin(node); node.applyDefaultsAndInheritance(stack); return true; } @Override
// Path: srcdeps-core/src/main/java/org/srcdeps/core/config/tree/ContainerNode.java // public interface ContainerNode<C extends Node> extends Node { // /** // * @return a map of child nodes // */ // Map<String, C> getChildren(); // // } // // Path: srcdeps-core/src/main/java/org/srcdeps/core/config/tree/ListNode.java // public interface ListNode<E extends Node> extends Node { // /** // * @return the elements of this {@link ListNode} // */ // List<E> getElements(); // } // // Path: srcdeps-core/src/main/java/org/srcdeps/core/config/tree/Node.java // public interface Node { // /** // * Apply the defaults or apply some kind of inheritance in case the values of some attributes were not set // * explicitly. See also {@link DefaultsAndInheritanceVisitor}. // * // * @param configurationStack the stack of ancestor configuration nodes. Can be queried to inherit values. // */ // void applyDefaultsAndInheritance(Stack<Node> configurationStack); // // /** // * @return a list of comment lines that should appear before this node // */ // List<String> getCommentBefore(); // // /** // * @return the name of the present node that is supposed to be unique within the parent node. Can be {@code null} in // * case this {@link Node} is an element of a {@link NodeList}. // */ // String getName(); // // /** // * Fully reset the state of this {@link Node} using the given {@code source} {@link Node}. // * // * @param source the {@link Node} to take the values from // */ // void init(Node source); // // /** // * @param stack the ancestor hierarchy of this {@link Node} // * @return {@code true} if this {@link Node}'s internal state has not been set yet or if the state is in the // * instance or implementation specific default state. Otherwise returns {@code false} // */ // boolean isInDefaultState(Stack<Node> stack); // // /** // * @return {@code true} if the name of the node will commonly contain special characters, esp. periods. Otherwise // * returns {@code false} // */ // boolean shouldEscapeName(); // } // // Path: srcdeps-core/src/main/java/org/srcdeps/core/config/tree/ScalarNode.java // public interface ScalarNode<T> extends Node { // /** // * @return the default value to be used if the value of this {@link ScalarNode} is not set explicitly // */ // T getDefaultValue(); // // /** // * @return the type of the value // */ // Class<T> getType(); // // /** // * @return the value stored in this {@link ScalarNode} // */ // T getValue(); // // /** // * Sets the value stored in this {@link ScalarNode}. // * // * @param value the value to set // */ // void setValue(T value); // } // // Path: srcdeps-core/src/main/java/org/srcdeps/core/config/tree/Visitor.java // public interface Visitor { // // /** // * Check whether the children of the given {@link ContainerNode} should be visited. // * // * @param node the current {@link ContainerNode} // * @return {@code true} if the calling walker should traverse the children of the given {@code node}; {@code false} // * otherwise // */ // boolean containerBegin(ContainerNode<? extends Node> node); // // /** // * Called just after {@link #containerBegin(ContainerNode)} if it returned {@code true} or after the children of a // * {@link ContainerNode} were visited. // */ // void containerEnd(); // // /** // * Check whether the elements of the given {@link ListNode} should be visited. // * // * @param node the current {@link ListNode} // * @return {@code true} if the calling walker should traverse the elements of the given {@code node}; {@code false} // * otherwise // */ // boolean listBegin(ListNode<? extends Node> node); // // /** // * Called just after {@link #containerBegin(ContainerNode)} if it returned {@code true} or after the children of a // * {@link ListNode} were visited. // */ // void listEnd(); // // /** // * Visit the given {@link ScalarNode}. // * // * @param node the {@link ScalarNode} to visit // */ // void scalar(ScalarNode<Object> node); // // } // Path: srcdeps-core/src/main/java/org/srcdeps/core/config/tree/walk/DefaultsAndInheritanceVisitor.java import java.util.List; import org.srcdeps.core.config.tree.ContainerNode; import org.srcdeps.core.config.tree.ListNode; import org.srcdeps.core.config.tree.Node; import org.srcdeps.core.config.tree.ScalarNode; import org.srcdeps.core.config.tree.Visitor; /** * Copyright 2015-2016 Maven Source Dependencies * Plugin contributors as indicated by the @author tags. * * 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.srcdeps.core.config.tree.walk; /** * A {@link Visitor} that calls {@link DefaultsAndInheritanceReceiver#applyDefaultsAndInheritance(List)} for each node * of a tree. * * @author <a href="https://github.com/ppalaga">Peter Palaga</a> */ public class DefaultsAndInheritanceVisitor extends AbstractVisitor { @Override public boolean containerBegin(ContainerNode<? extends Node> node) { super.containerBegin(node); node.applyDefaultsAndInheritance(stack); return true; } @Override public boolean listBegin(ListNode<? extends Node> node) { super.listBegin(node); node.applyDefaultsAndInheritance(stack); return true; } @Override
public void scalar(ScalarNode<Object> node) {
srcdeps/srcdeps-core
srcdeps-core/src/main/java/org/srcdeps/core/config/tree/impl/DefaultScalarNode.java
// Path: srcdeps-core/src/main/java/org/srcdeps/core/config/tree/Node.java // public interface Node { // /** // * Apply the defaults or apply some kind of inheritance in case the values of some attributes were not set // * explicitly. See also {@link DefaultsAndInheritanceVisitor}. // * // * @param configurationStack the stack of ancestor configuration nodes. Can be queried to inherit values. // */ // void applyDefaultsAndInheritance(Stack<Node> configurationStack); // // /** // * @return a list of comment lines that should appear before this node // */ // List<String> getCommentBefore(); // // /** // * @return the name of the present node that is supposed to be unique within the parent node. Can be {@code null} in // * case this {@link Node} is an element of a {@link NodeList}. // */ // String getName(); // // /** // * Fully reset the state of this {@link Node} using the given {@code source} {@link Node}. // * // * @param source the {@link Node} to take the values from // */ // void init(Node source); // // /** // * @param stack the ancestor hierarchy of this {@link Node} // * @return {@code true} if this {@link Node}'s internal state has not been set yet or if the state is in the // * instance or implementation specific default state. Otherwise returns {@code false} // */ // boolean isInDefaultState(Stack<Node> stack); // // /** // * @return {@code true} if the name of the node will commonly contain special characters, esp. periods. Otherwise // * returns {@code false} // */ // boolean shouldEscapeName(); // } // // Path: srcdeps-core/src/main/java/org/srcdeps/core/config/tree/ScalarNode.java // public interface ScalarNode<T> extends Node { // /** // * @return the default value to be used if the value of this {@link ScalarNode} is not set explicitly // */ // T getDefaultValue(); // // /** // * @return the type of the value // */ // Class<T> getType(); // // /** // * @return the value stored in this {@link ScalarNode} // */ // T getValue(); // // /** // * Sets the value stored in this {@link ScalarNode}. // * // * @param value the value to set // */ // void setValue(T value); // } // // Path: srcdeps-core/src/main/java/org/srcdeps/core/util/Equals.java // public interface Equals<T> { // class EqualsImplementations { // private static final Equals<Object> DEFAULT = new Equals<Object>() { // // @Override // public boolean test(Object value1, Object value2) { // return value1 == value2 || (value1 != null && value1.equals(value2)); // } // // }; // private static final Equals<Pattern> PATTERN = new Equals<Pattern>() { // // @Override // public boolean test(Pattern value1, Pattern value2) { // return value1 == value2 // || (value1 != null && value1.pattern().equals(value2 == null ? null : value2.pattern())); // } // // }; // // /** // * @return a default {@link Equals} implementation that works for any type {@code T} which overrides // * {@link Object#equals(Object)}. // */ // @SuppressWarnings("unchecked") // public static <T> Equals<T> equals() { // return (Equals<T>) DEFAULT; // } // // /** // * @return an {@link Equals} implementation that compares based on {@link Pattern#pattern()}. // */ // public static Equals<Pattern> equalsPattern() { // return PATTERN; // } // } // // /** // * As long as type {@code T} overrides {@link Object#equals(Object)}, must be equivalent to {@code value1 == value2 // * || (value1 != null && value1.pattern().equals(value2 == null ? null : value2.pattern()))} // * otherwise the implementations have to come up with some alternative which obey the contact of // * {@link Object#equals(Object)}. // * // * @param value1 the first value to compare // * @param value2 the second value to compare // * @return {@code true} of {@code value1} and {@code value2} are equal // */ // boolean test(T value1, T value2); // }
import java.util.ArrayList; import java.util.List; import java.util.Stack; import org.srcdeps.core.config.tree.Node; import org.srcdeps.core.config.tree.ScalarNode; import org.srcdeps.core.util.Equals;
/** * Copyright 2015-2018 Maven Source Dependencies * Plugin contributors as indicated by the @author tags. * * 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.srcdeps.core.config.tree.impl; /** * The default implementation of {@link ScalarNode}. * * @author <a href="https://github.com/ppalaga">Peter Palaga</a> * * @param <T> the type of the value stored in this {@link ScalarNode}. */ public class DefaultScalarNode<T> implements ScalarNode<T> { public static <V> ScalarNode<V> of(V value) { @SuppressWarnings("unchecked") DefaultScalarNode<V> result = new DefaultScalarNode<>((String) null, (Class<V>) value.getClass()); result.setValue(value); return result; } private final List<String> commentBefore = new ArrayList<>(); private T defaultValue; private final String name; private final Class<T> type; private T value;
// Path: srcdeps-core/src/main/java/org/srcdeps/core/config/tree/Node.java // public interface Node { // /** // * Apply the defaults or apply some kind of inheritance in case the values of some attributes were not set // * explicitly. See also {@link DefaultsAndInheritanceVisitor}. // * // * @param configurationStack the stack of ancestor configuration nodes. Can be queried to inherit values. // */ // void applyDefaultsAndInheritance(Stack<Node> configurationStack); // // /** // * @return a list of comment lines that should appear before this node // */ // List<String> getCommentBefore(); // // /** // * @return the name of the present node that is supposed to be unique within the parent node. Can be {@code null} in // * case this {@link Node} is an element of a {@link NodeList}. // */ // String getName(); // // /** // * Fully reset the state of this {@link Node} using the given {@code source} {@link Node}. // * // * @param source the {@link Node} to take the values from // */ // void init(Node source); // // /** // * @param stack the ancestor hierarchy of this {@link Node} // * @return {@code true} if this {@link Node}'s internal state has not been set yet or if the state is in the // * instance or implementation specific default state. Otherwise returns {@code false} // */ // boolean isInDefaultState(Stack<Node> stack); // // /** // * @return {@code true} if the name of the node will commonly contain special characters, esp. periods. Otherwise // * returns {@code false} // */ // boolean shouldEscapeName(); // } // // Path: srcdeps-core/src/main/java/org/srcdeps/core/config/tree/ScalarNode.java // public interface ScalarNode<T> extends Node { // /** // * @return the default value to be used if the value of this {@link ScalarNode} is not set explicitly // */ // T getDefaultValue(); // // /** // * @return the type of the value // */ // Class<T> getType(); // // /** // * @return the value stored in this {@link ScalarNode} // */ // T getValue(); // // /** // * Sets the value stored in this {@link ScalarNode}. // * // * @param value the value to set // */ // void setValue(T value); // } // // Path: srcdeps-core/src/main/java/org/srcdeps/core/util/Equals.java // public interface Equals<T> { // class EqualsImplementations { // private static final Equals<Object> DEFAULT = new Equals<Object>() { // // @Override // public boolean test(Object value1, Object value2) { // return value1 == value2 || (value1 != null && value1.equals(value2)); // } // // }; // private static final Equals<Pattern> PATTERN = new Equals<Pattern>() { // // @Override // public boolean test(Pattern value1, Pattern value2) { // return value1 == value2 // || (value1 != null && value1.pattern().equals(value2 == null ? null : value2.pattern())); // } // // }; // // /** // * @return a default {@link Equals} implementation that works for any type {@code T} which overrides // * {@link Object#equals(Object)}. // */ // @SuppressWarnings("unchecked") // public static <T> Equals<T> equals() { // return (Equals<T>) DEFAULT; // } // // /** // * @return an {@link Equals} implementation that compares based on {@link Pattern#pattern()}. // */ // public static Equals<Pattern> equalsPattern() { // return PATTERN; // } // } // // /** // * As long as type {@code T} overrides {@link Object#equals(Object)}, must be equivalent to {@code value1 == value2 // * || (value1 != null && value1.pattern().equals(value2 == null ? null : value2.pattern()))} // * otherwise the implementations have to come up with some alternative which obey the contact of // * {@link Object#equals(Object)}. // * // * @param value1 the first value to compare // * @param value2 the second value to compare // * @return {@code true} of {@code value1} and {@code value2} are equal // */ // boolean test(T value1, T value2); // } // Path: srcdeps-core/src/main/java/org/srcdeps/core/config/tree/impl/DefaultScalarNode.java import java.util.ArrayList; import java.util.List; import java.util.Stack; import org.srcdeps.core.config.tree.Node; import org.srcdeps.core.config.tree.ScalarNode; import org.srcdeps.core.util.Equals; /** * Copyright 2015-2018 Maven Source Dependencies * Plugin contributors as indicated by the @author tags. * * 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.srcdeps.core.config.tree.impl; /** * The default implementation of {@link ScalarNode}. * * @author <a href="https://github.com/ppalaga">Peter Palaga</a> * * @param <T> the type of the value stored in this {@link ScalarNode}. */ public class DefaultScalarNode<T> implements ScalarNode<T> { public static <V> ScalarNode<V> of(V value) { @SuppressWarnings("unchecked") DefaultScalarNode<V> result = new DefaultScalarNode<>((String) null, (Class<V>) value.getClass()); result.setValue(value); return result; } private final List<String> commentBefore = new ArrayList<>(); private T defaultValue; private final String name; private final Class<T> type; private T value;
private final Equals<T> equals;
srcdeps/srcdeps-core
srcdeps-core/src/main/java/org/srcdeps/core/config/tree/impl/DefaultScalarNode.java
// Path: srcdeps-core/src/main/java/org/srcdeps/core/config/tree/Node.java // public interface Node { // /** // * Apply the defaults or apply some kind of inheritance in case the values of some attributes were not set // * explicitly. See also {@link DefaultsAndInheritanceVisitor}. // * // * @param configurationStack the stack of ancestor configuration nodes. Can be queried to inherit values. // */ // void applyDefaultsAndInheritance(Stack<Node> configurationStack); // // /** // * @return a list of comment lines that should appear before this node // */ // List<String> getCommentBefore(); // // /** // * @return the name of the present node that is supposed to be unique within the parent node. Can be {@code null} in // * case this {@link Node} is an element of a {@link NodeList}. // */ // String getName(); // // /** // * Fully reset the state of this {@link Node} using the given {@code source} {@link Node}. // * // * @param source the {@link Node} to take the values from // */ // void init(Node source); // // /** // * @param stack the ancestor hierarchy of this {@link Node} // * @return {@code true} if this {@link Node}'s internal state has not been set yet or if the state is in the // * instance or implementation specific default state. Otherwise returns {@code false} // */ // boolean isInDefaultState(Stack<Node> stack); // // /** // * @return {@code true} if the name of the node will commonly contain special characters, esp. periods. Otherwise // * returns {@code false} // */ // boolean shouldEscapeName(); // } // // Path: srcdeps-core/src/main/java/org/srcdeps/core/config/tree/ScalarNode.java // public interface ScalarNode<T> extends Node { // /** // * @return the default value to be used if the value of this {@link ScalarNode} is not set explicitly // */ // T getDefaultValue(); // // /** // * @return the type of the value // */ // Class<T> getType(); // // /** // * @return the value stored in this {@link ScalarNode} // */ // T getValue(); // // /** // * Sets the value stored in this {@link ScalarNode}. // * // * @param value the value to set // */ // void setValue(T value); // } // // Path: srcdeps-core/src/main/java/org/srcdeps/core/util/Equals.java // public interface Equals<T> { // class EqualsImplementations { // private static final Equals<Object> DEFAULT = new Equals<Object>() { // // @Override // public boolean test(Object value1, Object value2) { // return value1 == value2 || (value1 != null && value1.equals(value2)); // } // // }; // private static final Equals<Pattern> PATTERN = new Equals<Pattern>() { // // @Override // public boolean test(Pattern value1, Pattern value2) { // return value1 == value2 // || (value1 != null && value1.pattern().equals(value2 == null ? null : value2.pattern())); // } // // }; // // /** // * @return a default {@link Equals} implementation that works for any type {@code T} which overrides // * {@link Object#equals(Object)}. // */ // @SuppressWarnings("unchecked") // public static <T> Equals<T> equals() { // return (Equals<T>) DEFAULT; // } // // /** // * @return an {@link Equals} implementation that compares based on {@link Pattern#pattern()}. // */ // public static Equals<Pattern> equalsPattern() { // return PATTERN; // } // } // // /** // * As long as type {@code T} overrides {@link Object#equals(Object)}, must be equivalent to {@code value1 == value2 // * || (value1 != null && value1.pattern().equals(value2 == null ? null : value2.pattern()))} // * otherwise the implementations have to come up with some alternative which obey the contact of // * {@link Object#equals(Object)}. // * // * @param value1 the first value to compare // * @param value2 the second value to compare // * @return {@code true} of {@code value1} and {@code value2} are equal // */ // boolean test(T value1, T value2); // }
import java.util.ArrayList; import java.util.List; import java.util.Stack; import org.srcdeps.core.config.tree.Node; import org.srcdeps.core.config.tree.ScalarNode; import org.srcdeps.core.util.Equals;
private final List<String> commentBefore = new ArrayList<>(); private T defaultValue; private final String name; private final Class<T> type; private T value; private final Equals<T> equals; public DefaultScalarNode(String name, Class<T> type) { this(name, null, type); } @SuppressWarnings("unchecked") public DefaultScalarNode(String name, T defaultValue) { this(name, defaultValue, (Class<T>) defaultValue.getClass()); } public DefaultScalarNode(String name, T defaultValue, Class<T> type) { this(name, defaultValue, type, Equals.EqualsImplementations.<T>equals()); } public DefaultScalarNode(String name, T defaultValue, Class<T> type, Equals<T> equals) { super(); this.name = name; this.defaultValue = defaultValue; this.type = type; this.equals = equals; } /** {@inheritDoc} */ @Override
// Path: srcdeps-core/src/main/java/org/srcdeps/core/config/tree/Node.java // public interface Node { // /** // * Apply the defaults or apply some kind of inheritance in case the values of some attributes were not set // * explicitly. See also {@link DefaultsAndInheritanceVisitor}. // * // * @param configurationStack the stack of ancestor configuration nodes. Can be queried to inherit values. // */ // void applyDefaultsAndInheritance(Stack<Node> configurationStack); // // /** // * @return a list of comment lines that should appear before this node // */ // List<String> getCommentBefore(); // // /** // * @return the name of the present node that is supposed to be unique within the parent node. Can be {@code null} in // * case this {@link Node} is an element of a {@link NodeList}. // */ // String getName(); // // /** // * Fully reset the state of this {@link Node} using the given {@code source} {@link Node}. // * // * @param source the {@link Node} to take the values from // */ // void init(Node source); // // /** // * @param stack the ancestor hierarchy of this {@link Node} // * @return {@code true} if this {@link Node}'s internal state has not been set yet or if the state is in the // * instance or implementation specific default state. Otherwise returns {@code false} // */ // boolean isInDefaultState(Stack<Node> stack); // // /** // * @return {@code true} if the name of the node will commonly contain special characters, esp. periods. Otherwise // * returns {@code false} // */ // boolean shouldEscapeName(); // } // // Path: srcdeps-core/src/main/java/org/srcdeps/core/config/tree/ScalarNode.java // public interface ScalarNode<T> extends Node { // /** // * @return the default value to be used if the value of this {@link ScalarNode} is not set explicitly // */ // T getDefaultValue(); // // /** // * @return the type of the value // */ // Class<T> getType(); // // /** // * @return the value stored in this {@link ScalarNode} // */ // T getValue(); // // /** // * Sets the value stored in this {@link ScalarNode}. // * // * @param value the value to set // */ // void setValue(T value); // } // // Path: srcdeps-core/src/main/java/org/srcdeps/core/util/Equals.java // public interface Equals<T> { // class EqualsImplementations { // private static final Equals<Object> DEFAULT = new Equals<Object>() { // // @Override // public boolean test(Object value1, Object value2) { // return value1 == value2 || (value1 != null && value1.equals(value2)); // } // // }; // private static final Equals<Pattern> PATTERN = new Equals<Pattern>() { // // @Override // public boolean test(Pattern value1, Pattern value2) { // return value1 == value2 // || (value1 != null && value1.pattern().equals(value2 == null ? null : value2.pattern())); // } // // }; // // /** // * @return a default {@link Equals} implementation that works for any type {@code T} which overrides // * {@link Object#equals(Object)}. // */ // @SuppressWarnings("unchecked") // public static <T> Equals<T> equals() { // return (Equals<T>) DEFAULT; // } // // /** // * @return an {@link Equals} implementation that compares based on {@link Pattern#pattern()}. // */ // public static Equals<Pattern> equalsPattern() { // return PATTERN; // } // } // // /** // * As long as type {@code T} overrides {@link Object#equals(Object)}, must be equivalent to {@code value1 == value2 // * || (value1 != null && value1.pattern().equals(value2 == null ? null : value2.pattern()))} // * otherwise the implementations have to come up with some alternative which obey the contact of // * {@link Object#equals(Object)}. // * // * @param value1 the first value to compare // * @param value2 the second value to compare // * @return {@code true} of {@code value1} and {@code value2} are equal // */ // boolean test(T value1, T value2); // } // Path: srcdeps-core/src/main/java/org/srcdeps/core/config/tree/impl/DefaultScalarNode.java import java.util.ArrayList; import java.util.List; import java.util.Stack; import org.srcdeps.core.config.tree.Node; import org.srcdeps.core.config.tree.ScalarNode; import org.srcdeps.core.util.Equals; private final List<String> commentBefore = new ArrayList<>(); private T defaultValue; private final String name; private final Class<T> type; private T value; private final Equals<T> equals; public DefaultScalarNode(String name, Class<T> type) { this(name, null, type); } @SuppressWarnings("unchecked") public DefaultScalarNode(String name, T defaultValue) { this(name, defaultValue, (Class<T>) defaultValue.getClass()); } public DefaultScalarNode(String name, T defaultValue, Class<T> type) { this(name, defaultValue, type, Equals.EqualsImplementations.<T>equals()); } public DefaultScalarNode(String name, T defaultValue, Class<T> type, Equals<T> equals) { super(); this.name = name; this.defaultValue = defaultValue; this.type = type; this.equals = equals; } /** {@inheritDoc} */ @Override
public void applyDefaultsAndInheritance(Stack<Node> configurationStack) {
srcdeps/srcdeps-core
srcdeps-core/src/test/java/org/srcdeps/core/BuildRequestTest.java
// Path: srcdeps-core/src/main/java/org/srcdeps/core/BuildRequest.java // public enum Verbosity { // debug, error, info, trace, warn; // // public static Verbosity fastValueOf(String level) { // SrcdepsCoreUtils.assertArgNotNull(level, "Verbosity name"); // switch (level.toLowerCase(Locale.ROOT)) { // case "trace": // return trace; // case "debug": // return debug; // case "info": // return info; // case "warn": // return warn; // case "error": // return error; // default: // throw new IllegalStateException("No such " + Verbosity.class.getName() + " with name [" + level + "]"); // } // } // // }
import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; import org.junit.Assert; import org.junit.Test; import org.srcdeps.core.BuildRequest.Verbosity;
/** * Copyright 2015-2019 Maven Source Dependencies * Plugin contributors as indicated by the @author tags. * * 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.srcdeps.core; public class BuildRequestTest { @Test public void getHash() { final Map<String, String> env1 = new HashMap<>(); env1.put("k1", "v1"); env1.put("k2", "v2"); final Set<String> props = new HashSet<>(); props.add("prop1"); props.add("prop2"); String id1 = BuildRequest.computeHash(true, true, Arrays.<String>asList("arg1", "arg2"), env1, props, StandardCharsets.UTF_8, GavSet.builder().include("org.mygroup").exclude("other-group").build(), Arrays.asList("url1", "url2"), true, SrcVersion.parse("1.2.3-SRC-revision-deadbeef"), "1.2.3", true,
// Path: srcdeps-core/src/main/java/org/srcdeps/core/BuildRequest.java // public enum Verbosity { // debug, error, info, trace, warn; // // public static Verbosity fastValueOf(String level) { // SrcdepsCoreUtils.assertArgNotNull(level, "Verbosity name"); // switch (level.toLowerCase(Locale.ROOT)) { // case "trace": // return trace; // case "debug": // return debug; // case "info": // return info; // case "warn": // return warn; // case "error": // return error; // default: // throw new IllegalStateException("No such " + Verbosity.class.getName() + " with name [" + level + "]"); // } // } // // } // Path: srcdeps-core/src/test/java/org/srcdeps/core/BuildRequestTest.java import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; import org.junit.Assert; import org.junit.Test; import org.srcdeps.core.BuildRequest.Verbosity; /** * Copyright 2015-2019 Maven Source Dependencies * Plugin contributors as indicated by the @author tags. * * 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.srcdeps.core; public class BuildRequestTest { @Test public void getHash() { final Map<String, String> env1 = new HashMap<>(); env1.put("k1", "v1"); env1.put("k2", "v2"); final Set<String> props = new HashSet<>(); props.add("prop1"); props.add("prop2"); String id1 = BuildRequest.computeHash(true, true, Arrays.<String>asList("arg1", "arg2"), env1, props, StandardCharsets.UTF_8, GavSet.builder().include("org.mygroup").exclude("other-group").build(), Arrays.asList("url1", "url2"), true, SrcVersion.parse("1.2.3-SRC-revision-deadbeef"), "1.2.3", true,
Collections.singleton(Ga.of("org:a")), false, 50000, Verbosity.error);
srcdeps/srcdeps-core
srcdeps-core/src/main/java/org/srcdeps/core/config/tree/walk/AbstractVisitor.java
// Path: srcdeps-core/src/main/java/org/srcdeps/core/config/tree/ContainerNode.java // public interface ContainerNode<C extends Node> extends Node { // /** // * @return a map of child nodes // */ // Map<String, C> getChildren(); // // } // // Path: srcdeps-core/src/main/java/org/srcdeps/core/config/tree/ListNode.java // public interface ListNode<E extends Node> extends Node { // /** // * @return the elements of this {@link ListNode} // */ // List<E> getElements(); // } // // Path: srcdeps-core/src/main/java/org/srcdeps/core/config/tree/Node.java // public interface Node { // /** // * Apply the defaults or apply some kind of inheritance in case the values of some attributes were not set // * explicitly. See also {@link DefaultsAndInheritanceVisitor}. // * // * @param configurationStack the stack of ancestor configuration nodes. Can be queried to inherit values. // */ // void applyDefaultsAndInheritance(Stack<Node> configurationStack); // // /** // * @return a list of comment lines that should appear before this node // */ // List<String> getCommentBefore(); // // /** // * @return the name of the present node that is supposed to be unique within the parent node. Can be {@code null} in // * case this {@link Node} is an element of a {@link NodeList}. // */ // String getName(); // // /** // * Fully reset the state of this {@link Node} using the given {@code source} {@link Node}. // * // * @param source the {@link Node} to take the values from // */ // void init(Node source); // // /** // * @param stack the ancestor hierarchy of this {@link Node} // * @return {@code true} if this {@link Node}'s internal state has not been set yet or if the state is in the // * instance or implementation specific default state. Otherwise returns {@code false} // */ // boolean isInDefaultState(Stack<Node> stack); // // /** // * @return {@code true} if the name of the node will commonly contain special characters, esp. periods. Otherwise // * returns {@code false} // */ // boolean shouldEscapeName(); // } // // Path: srcdeps-core/src/main/java/org/srcdeps/core/config/tree/ScalarNode.java // public interface ScalarNode<T> extends Node { // /** // * @return the default value to be used if the value of this {@link ScalarNode} is not set explicitly // */ // T getDefaultValue(); // // /** // * @return the type of the value // */ // Class<T> getType(); // // /** // * @return the value stored in this {@link ScalarNode} // */ // T getValue(); // // /** // * Sets the value stored in this {@link ScalarNode}. // * // * @param value the value to set // */ // void setValue(T value); // } // // Path: srcdeps-core/src/main/java/org/srcdeps/core/config/tree/Visitor.java // public interface Visitor { // // /** // * Check whether the children of the given {@link ContainerNode} should be visited. // * // * @param node the current {@link ContainerNode} // * @return {@code true} if the calling walker should traverse the children of the given {@code node}; {@code false} // * otherwise // */ // boolean containerBegin(ContainerNode<? extends Node> node); // // /** // * Called just after {@link #containerBegin(ContainerNode)} if it returned {@code true} or after the children of a // * {@link ContainerNode} were visited. // */ // void containerEnd(); // // /** // * Check whether the elements of the given {@link ListNode} should be visited. // * // * @param node the current {@link ListNode} // * @return {@code true} if the calling walker should traverse the elements of the given {@code node}; {@code false} // * otherwise // */ // boolean listBegin(ListNode<? extends Node> node); // // /** // * Called just after {@link #containerBegin(ContainerNode)} if it returned {@code true} or after the children of a // * {@link ListNode} were visited. // */ // void listEnd(); // // /** // * Visit the given {@link ScalarNode}. // * // * @param node the {@link ScalarNode} to visit // */ // void scalar(ScalarNode<Object> node); // // }
import java.util.Stack; import org.srcdeps.core.config.tree.ContainerNode; import org.srcdeps.core.config.tree.ListNode; import org.srcdeps.core.config.tree.Node; import org.srcdeps.core.config.tree.ScalarNode; import org.srcdeps.core.config.tree.Visitor;
/** * Copyright 2015-2018 Maven Source Dependencies * Plugin contributors as indicated by the @author tags. * * 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.srcdeps.core.config.tree.walk; /** * A base for several other {@link Visitor}s that maintains the {@link #stack} of {@link Node}s. * * @author <a href="https://github.com/ppalaga">Peter Palaga</a> */ public abstract class AbstractVisitor implements Visitor { protected final Stack<Node> stack = new Stack<>(); /** * Pushes the given node to the {@link #stack}. * * @param node {@inheritDoc} * @return {@inheritDoc} */ @Override
// Path: srcdeps-core/src/main/java/org/srcdeps/core/config/tree/ContainerNode.java // public interface ContainerNode<C extends Node> extends Node { // /** // * @return a map of child nodes // */ // Map<String, C> getChildren(); // // } // // Path: srcdeps-core/src/main/java/org/srcdeps/core/config/tree/ListNode.java // public interface ListNode<E extends Node> extends Node { // /** // * @return the elements of this {@link ListNode} // */ // List<E> getElements(); // } // // Path: srcdeps-core/src/main/java/org/srcdeps/core/config/tree/Node.java // public interface Node { // /** // * Apply the defaults or apply some kind of inheritance in case the values of some attributes were not set // * explicitly. See also {@link DefaultsAndInheritanceVisitor}. // * // * @param configurationStack the stack of ancestor configuration nodes. Can be queried to inherit values. // */ // void applyDefaultsAndInheritance(Stack<Node> configurationStack); // // /** // * @return a list of comment lines that should appear before this node // */ // List<String> getCommentBefore(); // // /** // * @return the name of the present node that is supposed to be unique within the parent node. Can be {@code null} in // * case this {@link Node} is an element of a {@link NodeList}. // */ // String getName(); // // /** // * Fully reset the state of this {@link Node} using the given {@code source} {@link Node}. // * // * @param source the {@link Node} to take the values from // */ // void init(Node source); // // /** // * @param stack the ancestor hierarchy of this {@link Node} // * @return {@code true} if this {@link Node}'s internal state has not been set yet or if the state is in the // * instance or implementation specific default state. Otherwise returns {@code false} // */ // boolean isInDefaultState(Stack<Node> stack); // // /** // * @return {@code true} if the name of the node will commonly contain special characters, esp. periods. Otherwise // * returns {@code false} // */ // boolean shouldEscapeName(); // } // // Path: srcdeps-core/src/main/java/org/srcdeps/core/config/tree/ScalarNode.java // public interface ScalarNode<T> extends Node { // /** // * @return the default value to be used if the value of this {@link ScalarNode} is not set explicitly // */ // T getDefaultValue(); // // /** // * @return the type of the value // */ // Class<T> getType(); // // /** // * @return the value stored in this {@link ScalarNode} // */ // T getValue(); // // /** // * Sets the value stored in this {@link ScalarNode}. // * // * @param value the value to set // */ // void setValue(T value); // } // // Path: srcdeps-core/src/main/java/org/srcdeps/core/config/tree/Visitor.java // public interface Visitor { // // /** // * Check whether the children of the given {@link ContainerNode} should be visited. // * // * @param node the current {@link ContainerNode} // * @return {@code true} if the calling walker should traverse the children of the given {@code node}; {@code false} // * otherwise // */ // boolean containerBegin(ContainerNode<? extends Node> node); // // /** // * Called just after {@link #containerBegin(ContainerNode)} if it returned {@code true} or after the children of a // * {@link ContainerNode} were visited. // */ // void containerEnd(); // // /** // * Check whether the elements of the given {@link ListNode} should be visited. // * // * @param node the current {@link ListNode} // * @return {@code true} if the calling walker should traverse the elements of the given {@code node}; {@code false} // * otherwise // */ // boolean listBegin(ListNode<? extends Node> node); // // /** // * Called just after {@link #containerBegin(ContainerNode)} if it returned {@code true} or after the children of a // * {@link ListNode} were visited. // */ // void listEnd(); // // /** // * Visit the given {@link ScalarNode}. // * // * @param node the {@link ScalarNode} to visit // */ // void scalar(ScalarNode<Object> node); // // } // Path: srcdeps-core/src/main/java/org/srcdeps/core/config/tree/walk/AbstractVisitor.java import java.util.Stack; import org.srcdeps.core.config.tree.ContainerNode; import org.srcdeps.core.config.tree.ListNode; import org.srcdeps.core.config.tree.Node; import org.srcdeps.core.config.tree.ScalarNode; import org.srcdeps.core.config.tree.Visitor; /** * Copyright 2015-2018 Maven Source Dependencies * Plugin contributors as indicated by the @author tags. * * 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.srcdeps.core.config.tree.walk; /** * A base for several other {@link Visitor}s that maintains the {@link #stack} of {@link Node}s. * * @author <a href="https://github.com/ppalaga">Peter Palaga</a> */ public abstract class AbstractVisitor implements Visitor { protected final Stack<Node> stack = new Stack<>(); /** * Pushes the given node to the {@link #stack}. * * @param node {@inheritDoc} * @return {@inheritDoc} */ @Override
public boolean containerBegin(ContainerNode<? extends Node> node) {
srcdeps/srcdeps-core
srcdeps-core/src/test/java/org/srcdeps/core/config/scalar/CharStreamSourceTest.java
// Path: srcdeps-core/src/main/java/org/srcdeps/core/config/scalar/CharStreamSource.java // public enum Scheme { // classpath { // @Override // public Reader openReader(String resource, Charset encoding, Path resolveAgainst) { // return new InputStreamReader(getClass().getResourceAsStream(resource), encoding); // } // }, // // file { // @Override // public Reader openReader(String resource, Charset encoding, Path resolveAgainst) throws IOException { // return Files.newBufferedReader(resolveAgainst.resolve(Paths.get(resource)), encoding); // } // }, // // literal { // @Override // public Reader openReader(String resource, Charset encoding, Path resolveAgainst) { // return new StringReader(resource); // } // }; // public abstract Reader openReader(String resource, Charset encoding, Path resolveAgainst) throws IOException; // }
import org.junit.Assert; import org.junit.Test; import org.srcdeps.core.config.scalar.CharStreamSource.Scheme;
/** * Copyright 2015-2018 Maven Source Dependencies * Plugin contributors as indicated by the @author tags. * * 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.srcdeps.core.config.scalar; public class CharStreamSourceTest { @Test public void of() {
// Path: srcdeps-core/src/main/java/org/srcdeps/core/config/scalar/CharStreamSource.java // public enum Scheme { // classpath { // @Override // public Reader openReader(String resource, Charset encoding, Path resolveAgainst) { // return new InputStreamReader(getClass().getResourceAsStream(resource), encoding); // } // }, // // file { // @Override // public Reader openReader(String resource, Charset encoding, Path resolveAgainst) throws IOException { // return Files.newBufferedReader(resolveAgainst.resolve(Paths.get(resource)), encoding); // } // }, // // literal { // @Override // public Reader openReader(String resource, Charset encoding, Path resolveAgainst) { // return new StringReader(resource); // } // }; // public abstract Reader openReader(String resource, Charset encoding, Path resolveAgainst) throws IOException; // } // Path: srcdeps-core/src/test/java/org/srcdeps/core/config/scalar/CharStreamSourceTest.java import org.junit.Assert; import org.junit.Test; import org.srcdeps.core.config.scalar.CharStreamSource.Scheme; /** * Copyright 2015-2018 Maven Source Dependencies * Plugin contributors as indicated by the @author tags. * * 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.srcdeps.core.config.scalar; public class CharStreamSourceTest { @Test public void of() {
Assert.assertEquals(new CharStreamSource(Scheme.classpath, "/my/path"),
srcdeps/srcdeps-core
srcdeps-core/src/main/java/org/srcdeps/core/config/tree/walk/TreeWalker.java
// Path: srcdeps-core/src/main/java/org/srcdeps/core/config/tree/ContainerNode.java // public interface ContainerNode<C extends Node> extends Node { // /** // * @return a map of child nodes // */ // Map<String, C> getChildren(); // // } // // Path: srcdeps-core/src/main/java/org/srcdeps/core/config/tree/ListNode.java // public interface ListNode<E extends Node> extends Node { // /** // * @return the elements of this {@link ListNode} // */ // List<E> getElements(); // } // // Path: srcdeps-core/src/main/java/org/srcdeps/core/config/tree/Node.java // public interface Node { // /** // * Apply the defaults or apply some kind of inheritance in case the values of some attributes were not set // * explicitly. See also {@link DefaultsAndInheritanceVisitor}. // * // * @param configurationStack the stack of ancestor configuration nodes. Can be queried to inherit values. // */ // void applyDefaultsAndInheritance(Stack<Node> configurationStack); // // /** // * @return a list of comment lines that should appear before this node // */ // List<String> getCommentBefore(); // // /** // * @return the name of the present node that is supposed to be unique within the parent node. Can be {@code null} in // * case this {@link Node} is an element of a {@link NodeList}. // */ // String getName(); // // /** // * Fully reset the state of this {@link Node} using the given {@code source} {@link Node}. // * // * @param source the {@link Node} to take the values from // */ // void init(Node source); // // /** // * @param stack the ancestor hierarchy of this {@link Node} // * @return {@code true} if this {@link Node}'s internal state has not been set yet or if the state is in the // * instance or implementation specific default state. Otherwise returns {@code false} // */ // boolean isInDefaultState(Stack<Node> stack); // // /** // * @return {@code true} if the name of the node will commonly contain special characters, esp. periods. Otherwise // * returns {@code false} // */ // boolean shouldEscapeName(); // } // // Path: srcdeps-core/src/main/java/org/srcdeps/core/config/tree/ScalarNode.java // public interface ScalarNode<T> extends Node { // /** // * @return the default value to be used if the value of this {@link ScalarNode} is not set explicitly // */ // T getDefaultValue(); // // /** // * @return the type of the value // */ // Class<T> getType(); // // /** // * @return the value stored in this {@link ScalarNode} // */ // T getValue(); // // /** // * Sets the value stored in this {@link ScalarNode}. // * // * @param value the value to set // */ // void setValue(T value); // } // // Path: srcdeps-core/src/main/java/org/srcdeps/core/config/tree/Visitor.java // public interface Visitor { // // /** // * Check whether the children of the given {@link ContainerNode} should be visited. // * // * @param node the current {@link ContainerNode} // * @return {@code true} if the calling walker should traverse the children of the given {@code node}; {@code false} // * otherwise // */ // boolean containerBegin(ContainerNode<? extends Node> node); // // /** // * Called just after {@link #containerBegin(ContainerNode)} if it returned {@code true} or after the children of a // * {@link ContainerNode} were visited. // */ // void containerEnd(); // // /** // * Check whether the elements of the given {@link ListNode} should be visited. // * // * @param node the current {@link ListNode} // * @return {@code true} if the calling walker should traverse the elements of the given {@code node}; {@code false} // * otherwise // */ // boolean listBegin(ListNode<? extends Node> node); // // /** // * Called just after {@link #containerBegin(ContainerNode)} if it returned {@code true} or after the children of a // * {@link ListNode} were visited. // */ // void listEnd(); // // /** // * Visit the given {@link ScalarNode}. // * // * @param node the {@link ScalarNode} to visit // */ // void scalar(ScalarNode<Object> node); // // }
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.srcdeps.core.config.tree.ContainerNode; import org.srcdeps.core.config.tree.ListNode; import org.srcdeps.core.config.tree.Node; import org.srcdeps.core.config.tree.ScalarNode; import org.srcdeps.core.config.tree.Visitor;
/** * Copyright 2015-2018 Maven Source Dependencies * Plugin contributors as indicated by the @author tags. * * 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.srcdeps.core.config.tree.walk; /** * A simple configuration tree walker. * * @author <a href="https://github.com/ppalaga">Peter Palaga</a> */ public class TreeWalker { @SuppressWarnings("unused") private static final Logger log = LoggerFactory.getLogger(TreeWalker.class); public TreeWalker() { super(); } /** * Walks a tree starting at the given {@code node} notifying the {@code visitor}. * * @param node the node to start at * @param visitor the visitor to notify */ @SuppressWarnings("unchecked")
// Path: srcdeps-core/src/main/java/org/srcdeps/core/config/tree/ContainerNode.java // public interface ContainerNode<C extends Node> extends Node { // /** // * @return a map of child nodes // */ // Map<String, C> getChildren(); // // } // // Path: srcdeps-core/src/main/java/org/srcdeps/core/config/tree/ListNode.java // public interface ListNode<E extends Node> extends Node { // /** // * @return the elements of this {@link ListNode} // */ // List<E> getElements(); // } // // Path: srcdeps-core/src/main/java/org/srcdeps/core/config/tree/Node.java // public interface Node { // /** // * Apply the defaults or apply some kind of inheritance in case the values of some attributes were not set // * explicitly. See also {@link DefaultsAndInheritanceVisitor}. // * // * @param configurationStack the stack of ancestor configuration nodes. Can be queried to inherit values. // */ // void applyDefaultsAndInheritance(Stack<Node> configurationStack); // // /** // * @return a list of comment lines that should appear before this node // */ // List<String> getCommentBefore(); // // /** // * @return the name of the present node that is supposed to be unique within the parent node. Can be {@code null} in // * case this {@link Node} is an element of a {@link NodeList}. // */ // String getName(); // // /** // * Fully reset the state of this {@link Node} using the given {@code source} {@link Node}. // * // * @param source the {@link Node} to take the values from // */ // void init(Node source); // // /** // * @param stack the ancestor hierarchy of this {@link Node} // * @return {@code true} if this {@link Node}'s internal state has not been set yet or if the state is in the // * instance or implementation specific default state. Otherwise returns {@code false} // */ // boolean isInDefaultState(Stack<Node> stack); // // /** // * @return {@code true} if the name of the node will commonly contain special characters, esp. periods. Otherwise // * returns {@code false} // */ // boolean shouldEscapeName(); // } // // Path: srcdeps-core/src/main/java/org/srcdeps/core/config/tree/ScalarNode.java // public interface ScalarNode<T> extends Node { // /** // * @return the default value to be used if the value of this {@link ScalarNode} is not set explicitly // */ // T getDefaultValue(); // // /** // * @return the type of the value // */ // Class<T> getType(); // // /** // * @return the value stored in this {@link ScalarNode} // */ // T getValue(); // // /** // * Sets the value stored in this {@link ScalarNode}. // * // * @param value the value to set // */ // void setValue(T value); // } // // Path: srcdeps-core/src/main/java/org/srcdeps/core/config/tree/Visitor.java // public interface Visitor { // // /** // * Check whether the children of the given {@link ContainerNode} should be visited. // * // * @param node the current {@link ContainerNode} // * @return {@code true} if the calling walker should traverse the children of the given {@code node}; {@code false} // * otherwise // */ // boolean containerBegin(ContainerNode<? extends Node> node); // // /** // * Called just after {@link #containerBegin(ContainerNode)} if it returned {@code true} or after the children of a // * {@link ContainerNode} were visited. // */ // void containerEnd(); // // /** // * Check whether the elements of the given {@link ListNode} should be visited. // * // * @param node the current {@link ListNode} // * @return {@code true} if the calling walker should traverse the elements of the given {@code node}; {@code false} // * otherwise // */ // boolean listBegin(ListNode<? extends Node> node); // // /** // * Called just after {@link #containerBegin(ContainerNode)} if it returned {@code true} or after the children of a // * {@link ListNode} were visited. // */ // void listEnd(); // // /** // * Visit the given {@link ScalarNode}. // * // * @param node the {@link ScalarNode} to visit // */ // void scalar(ScalarNode<Object> node); // // } // Path: srcdeps-core/src/main/java/org/srcdeps/core/config/tree/walk/TreeWalker.java import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.srcdeps.core.config.tree.ContainerNode; import org.srcdeps.core.config.tree.ListNode; import org.srcdeps.core.config.tree.Node; import org.srcdeps.core.config.tree.ScalarNode; import org.srcdeps.core.config.tree.Visitor; /** * Copyright 2015-2018 Maven Source Dependencies * Plugin contributors as indicated by the @author tags. * * 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.srcdeps.core.config.tree.walk; /** * A simple configuration tree walker. * * @author <a href="https://github.com/ppalaga">Peter Palaga</a> */ public class TreeWalker { @SuppressWarnings("unused") private static final Logger log = LoggerFactory.getLogger(TreeWalker.class); public TreeWalker() { super(); } /** * Walks a tree starting at the given {@code node} notifying the {@code visitor}. * * @param node the node to start at * @param visitor the visitor to notify */ @SuppressWarnings("unchecked")
public void walk(Node node, Visitor visitor) {
srcdeps/srcdeps-core
srcdeps-core/src/main/java/org/srcdeps/core/config/tree/walk/TreeWalker.java
// Path: srcdeps-core/src/main/java/org/srcdeps/core/config/tree/ContainerNode.java // public interface ContainerNode<C extends Node> extends Node { // /** // * @return a map of child nodes // */ // Map<String, C> getChildren(); // // } // // Path: srcdeps-core/src/main/java/org/srcdeps/core/config/tree/ListNode.java // public interface ListNode<E extends Node> extends Node { // /** // * @return the elements of this {@link ListNode} // */ // List<E> getElements(); // } // // Path: srcdeps-core/src/main/java/org/srcdeps/core/config/tree/Node.java // public interface Node { // /** // * Apply the defaults or apply some kind of inheritance in case the values of some attributes were not set // * explicitly. See also {@link DefaultsAndInheritanceVisitor}. // * // * @param configurationStack the stack of ancestor configuration nodes. Can be queried to inherit values. // */ // void applyDefaultsAndInheritance(Stack<Node> configurationStack); // // /** // * @return a list of comment lines that should appear before this node // */ // List<String> getCommentBefore(); // // /** // * @return the name of the present node that is supposed to be unique within the parent node. Can be {@code null} in // * case this {@link Node} is an element of a {@link NodeList}. // */ // String getName(); // // /** // * Fully reset the state of this {@link Node} using the given {@code source} {@link Node}. // * // * @param source the {@link Node} to take the values from // */ // void init(Node source); // // /** // * @param stack the ancestor hierarchy of this {@link Node} // * @return {@code true} if this {@link Node}'s internal state has not been set yet or if the state is in the // * instance or implementation specific default state. Otherwise returns {@code false} // */ // boolean isInDefaultState(Stack<Node> stack); // // /** // * @return {@code true} if the name of the node will commonly contain special characters, esp. periods. Otherwise // * returns {@code false} // */ // boolean shouldEscapeName(); // } // // Path: srcdeps-core/src/main/java/org/srcdeps/core/config/tree/ScalarNode.java // public interface ScalarNode<T> extends Node { // /** // * @return the default value to be used if the value of this {@link ScalarNode} is not set explicitly // */ // T getDefaultValue(); // // /** // * @return the type of the value // */ // Class<T> getType(); // // /** // * @return the value stored in this {@link ScalarNode} // */ // T getValue(); // // /** // * Sets the value stored in this {@link ScalarNode}. // * // * @param value the value to set // */ // void setValue(T value); // } // // Path: srcdeps-core/src/main/java/org/srcdeps/core/config/tree/Visitor.java // public interface Visitor { // // /** // * Check whether the children of the given {@link ContainerNode} should be visited. // * // * @param node the current {@link ContainerNode} // * @return {@code true} if the calling walker should traverse the children of the given {@code node}; {@code false} // * otherwise // */ // boolean containerBegin(ContainerNode<? extends Node> node); // // /** // * Called just after {@link #containerBegin(ContainerNode)} if it returned {@code true} or after the children of a // * {@link ContainerNode} were visited. // */ // void containerEnd(); // // /** // * Check whether the elements of the given {@link ListNode} should be visited. // * // * @param node the current {@link ListNode} // * @return {@code true} if the calling walker should traverse the elements of the given {@code node}; {@code false} // * otherwise // */ // boolean listBegin(ListNode<? extends Node> node); // // /** // * Called just after {@link #containerBegin(ContainerNode)} if it returned {@code true} or after the children of a // * {@link ListNode} were visited. // */ // void listEnd(); // // /** // * Visit the given {@link ScalarNode}. // * // * @param node the {@link ScalarNode} to visit // */ // void scalar(ScalarNode<Object> node); // // }
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.srcdeps.core.config.tree.ContainerNode; import org.srcdeps.core.config.tree.ListNode; import org.srcdeps.core.config.tree.Node; import org.srcdeps.core.config.tree.ScalarNode; import org.srcdeps.core.config.tree.Visitor;
/** * Copyright 2015-2018 Maven Source Dependencies * Plugin contributors as indicated by the @author tags. * * 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.srcdeps.core.config.tree.walk; /** * A simple configuration tree walker. * * @author <a href="https://github.com/ppalaga">Peter Palaga</a> */ public class TreeWalker { @SuppressWarnings("unused") private static final Logger log = LoggerFactory.getLogger(TreeWalker.class); public TreeWalker() { super(); } /** * Walks a tree starting at the given {@code node} notifying the {@code visitor}. * * @param node the node to start at * @param visitor the visitor to notify */ @SuppressWarnings("unchecked")
// Path: srcdeps-core/src/main/java/org/srcdeps/core/config/tree/ContainerNode.java // public interface ContainerNode<C extends Node> extends Node { // /** // * @return a map of child nodes // */ // Map<String, C> getChildren(); // // } // // Path: srcdeps-core/src/main/java/org/srcdeps/core/config/tree/ListNode.java // public interface ListNode<E extends Node> extends Node { // /** // * @return the elements of this {@link ListNode} // */ // List<E> getElements(); // } // // Path: srcdeps-core/src/main/java/org/srcdeps/core/config/tree/Node.java // public interface Node { // /** // * Apply the defaults or apply some kind of inheritance in case the values of some attributes were not set // * explicitly. See also {@link DefaultsAndInheritanceVisitor}. // * // * @param configurationStack the stack of ancestor configuration nodes. Can be queried to inherit values. // */ // void applyDefaultsAndInheritance(Stack<Node> configurationStack); // // /** // * @return a list of comment lines that should appear before this node // */ // List<String> getCommentBefore(); // // /** // * @return the name of the present node that is supposed to be unique within the parent node. Can be {@code null} in // * case this {@link Node} is an element of a {@link NodeList}. // */ // String getName(); // // /** // * Fully reset the state of this {@link Node} using the given {@code source} {@link Node}. // * // * @param source the {@link Node} to take the values from // */ // void init(Node source); // // /** // * @param stack the ancestor hierarchy of this {@link Node} // * @return {@code true} if this {@link Node}'s internal state has not been set yet or if the state is in the // * instance or implementation specific default state. Otherwise returns {@code false} // */ // boolean isInDefaultState(Stack<Node> stack); // // /** // * @return {@code true} if the name of the node will commonly contain special characters, esp. periods. Otherwise // * returns {@code false} // */ // boolean shouldEscapeName(); // } // // Path: srcdeps-core/src/main/java/org/srcdeps/core/config/tree/ScalarNode.java // public interface ScalarNode<T> extends Node { // /** // * @return the default value to be used if the value of this {@link ScalarNode} is not set explicitly // */ // T getDefaultValue(); // // /** // * @return the type of the value // */ // Class<T> getType(); // // /** // * @return the value stored in this {@link ScalarNode} // */ // T getValue(); // // /** // * Sets the value stored in this {@link ScalarNode}. // * // * @param value the value to set // */ // void setValue(T value); // } // // Path: srcdeps-core/src/main/java/org/srcdeps/core/config/tree/Visitor.java // public interface Visitor { // // /** // * Check whether the children of the given {@link ContainerNode} should be visited. // * // * @param node the current {@link ContainerNode} // * @return {@code true} if the calling walker should traverse the children of the given {@code node}; {@code false} // * otherwise // */ // boolean containerBegin(ContainerNode<? extends Node> node); // // /** // * Called just after {@link #containerBegin(ContainerNode)} if it returned {@code true} or after the children of a // * {@link ContainerNode} were visited. // */ // void containerEnd(); // // /** // * Check whether the elements of the given {@link ListNode} should be visited. // * // * @param node the current {@link ListNode} // * @return {@code true} if the calling walker should traverse the elements of the given {@code node}; {@code false} // * otherwise // */ // boolean listBegin(ListNode<? extends Node> node); // // /** // * Called just after {@link #containerBegin(ContainerNode)} if it returned {@code true} or after the children of a // * {@link ListNode} were visited. // */ // void listEnd(); // // /** // * Visit the given {@link ScalarNode}. // * // * @param node the {@link ScalarNode} to visit // */ // void scalar(ScalarNode<Object> node); // // } // Path: srcdeps-core/src/main/java/org/srcdeps/core/config/tree/walk/TreeWalker.java import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.srcdeps.core.config.tree.ContainerNode; import org.srcdeps.core.config.tree.ListNode; import org.srcdeps.core.config.tree.Node; import org.srcdeps.core.config.tree.ScalarNode; import org.srcdeps.core.config.tree.Visitor; /** * Copyright 2015-2018 Maven Source Dependencies * Plugin contributors as indicated by the @author tags. * * 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.srcdeps.core.config.tree.walk; /** * A simple configuration tree walker. * * @author <a href="https://github.com/ppalaga">Peter Palaga</a> */ public class TreeWalker { @SuppressWarnings("unused") private static final Logger log = LoggerFactory.getLogger(TreeWalker.class); public TreeWalker() { super(); } /** * Walks a tree starting at the given {@code node} notifying the {@code visitor}. * * @param node the node to start at * @param visitor the visitor to notify */ @SuppressWarnings("unchecked")
public void walk(Node node, Visitor visitor) {
srcdeps/srcdeps-core
srcdeps-core/src/main/java/org/srcdeps/core/config/tree/walk/TreeWalker.java
// Path: srcdeps-core/src/main/java/org/srcdeps/core/config/tree/ContainerNode.java // public interface ContainerNode<C extends Node> extends Node { // /** // * @return a map of child nodes // */ // Map<String, C> getChildren(); // // } // // Path: srcdeps-core/src/main/java/org/srcdeps/core/config/tree/ListNode.java // public interface ListNode<E extends Node> extends Node { // /** // * @return the elements of this {@link ListNode} // */ // List<E> getElements(); // } // // Path: srcdeps-core/src/main/java/org/srcdeps/core/config/tree/Node.java // public interface Node { // /** // * Apply the defaults or apply some kind of inheritance in case the values of some attributes were not set // * explicitly. See also {@link DefaultsAndInheritanceVisitor}. // * // * @param configurationStack the stack of ancestor configuration nodes. Can be queried to inherit values. // */ // void applyDefaultsAndInheritance(Stack<Node> configurationStack); // // /** // * @return a list of comment lines that should appear before this node // */ // List<String> getCommentBefore(); // // /** // * @return the name of the present node that is supposed to be unique within the parent node. Can be {@code null} in // * case this {@link Node} is an element of a {@link NodeList}. // */ // String getName(); // // /** // * Fully reset the state of this {@link Node} using the given {@code source} {@link Node}. // * // * @param source the {@link Node} to take the values from // */ // void init(Node source); // // /** // * @param stack the ancestor hierarchy of this {@link Node} // * @return {@code true} if this {@link Node}'s internal state has not been set yet or if the state is in the // * instance or implementation specific default state. Otherwise returns {@code false} // */ // boolean isInDefaultState(Stack<Node> stack); // // /** // * @return {@code true} if the name of the node will commonly contain special characters, esp. periods. Otherwise // * returns {@code false} // */ // boolean shouldEscapeName(); // } // // Path: srcdeps-core/src/main/java/org/srcdeps/core/config/tree/ScalarNode.java // public interface ScalarNode<T> extends Node { // /** // * @return the default value to be used if the value of this {@link ScalarNode} is not set explicitly // */ // T getDefaultValue(); // // /** // * @return the type of the value // */ // Class<T> getType(); // // /** // * @return the value stored in this {@link ScalarNode} // */ // T getValue(); // // /** // * Sets the value stored in this {@link ScalarNode}. // * // * @param value the value to set // */ // void setValue(T value); // } // // Path: srcdeps-core/src/main/java/org/srcdeps/core/config/tree/Visitor.java // public interface Visitor { // // /** // * Check whether the children of the given {@link ContainerNode} should be visited. // * // * @param node the current {@link ContainerNode} // * @return {@code true} if the calling walker should traverse the children of the given {@code node}; {@code false} // * otherwise // */ // boolean containerBegin(ContainerNode<? extends Node> node); // // /** // * Called just after {@link #containerBegin(ContainerNode)} if it returned {@code true} or after the children of a // * {@link ContainerNode} were visited. // */ // void containerEnd(); // // /** // * Check whether the elements of the given {@link ListNode} should be visited. // * // * @param node the current {@link ListNode} // * @return {@code true} if the calling walker should traverse the elements of the given {@code node}; {@code false} // * otherwise // */ // boolean listBegin(ListNode<? extends Node> node); // // /** // * Called just after {@link #containerBegin(ContainerNode)} if it returned {@code true} or after the children of a // * {@link ListNode} were visited. // */ // void listEnd(); // // /** // * Visit the given {@link ScalarNode}. // * // * @param node the {@link ScalarNode} to visit // */ // void scalar(ScalarNode<Object> node); // // }
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.srcdeps.core.config.tree.ContainerNode; import org.srcdeps.core.config.tree.ListNode; import org.srcdeps.core.config.tree.Node; import org.srcdeps.core.config.tree.ScalarNode; import org.srcdeps.core.config.tree.Visitor;
/** * Copyright 2015-2018 Maven Source Dependencies * Plugin contributors as indicated by the @author tags. * * 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.srcdeps.core.config.tree.walk; /** * A simple configuration tree walker. * * @author <a href="https://github.com/ppalaga">Peter Palaga</a> */ public class TreeWalker { @SuppressWarnings("unused") private static final Logger log = LoggerFactory.getLogger(TreeWalker.class); public TreeWalker() { super(); } /** * Walks a tree starting at the given {@code node} notifying the {@code visitor}. * * @param node the node to start at * @param visitor the visitor to notify */ @SuppressWarnings("unchecked") public void walk(Node node, Visitor visitor) {
// Path: srcdeps-core/src/main/java/org/srcdeps/core/config/tree/ContainerNode.java // public interface ContainerNode<C extends Node> extends Node { // /** // * @return a map of child nodes // */ // Map<String, C> getChildren(); // // } // // Path: srcdeps-core/src/main/java/org/srcdeps/core/config/tree/ListNode.java // public interface ListNode<E extends Node> extends Node { // /** // * @return the elements of this {@link ListNode} // */ // List<E> getElements(); // } // // Path: srcdeps-core/src/main/java/org/srcdeps/core/config/tree/Node.java // public interface Node { // /** // * Apply the defaults or apply some kind of inheritance in case the values of some attributes were not set // * explicitly. See also {@link DefaultsAndInheritanceVisitor}. // * // * @param configurationStack the stack of ancestor configuration nodes. Can be queried to inherit values. // */ // void applyDefaultsAndInheritance(Stack<Node> configurationStack); // // /** // * @return a list of comment lines that should appear before this node // */ // List<String> getCommentBefore(); // // /** // * @return the name of the present node that is supposed to be unique within the parent node. Can be {@code null} in // * case this {@link Node} is an element of a {@link NodeList}. // */ // String getName(); // // /** // * Fully reset the state of this {@link Node} using the given {@code source} {@link Node}. // * // * @param source the {@link Node} to take the values from // */ // void init(Node source); // // /** // * @param stack the ancestor hierarchy of this {@link Node} // * @return {@code true} if this {@link Node}'s internal state has not been set yet or if the state is in the // * instance or implementation specific default state. Otherwise returns {@code false} // */ // boolean isInDefaultState(Stack<Node> stack); // // /** // * @return {@code true} if the name of the node will commonly contain special characters, esp. periods. Otherwise // * returns {@code false} // */ // boolean shouldEscapeName(); // } // // Path: srcdeps-core/src/main/java/org/srcdeps/core/config/tree/ScalarNode.java // public interface ScalarNode<T> extends Node { // /** // * @return the default value to be used if the value of this {@link ScalarNode} is not set explicitly // */ // T getDefaultValue(); // // /** // * @return the type of the value // */ // Class<T> getType(); // // /** // * @return the value stored in this {@link ScalarNode} // */ // T getValue(); // // /** // * Sets the value stored in this {@link ScalarNode}. // * // * @param value the value to set // */ // void setValue(T value); // } // // Path: srcdeps-core/src/main/java/org/srcdeps/core/config/tree/Visitor.java // public interface Visitor { // // /** // * Check whether the children of the given {@link ContainerNode} should be visited. // * // * @param node the current {@link ContainerNode} // * @return {@code true} if the calling walker should traverse the children of the given {@code node}; {@code false} // * otherwise // */ // boolean containerBegin(ContainerNode<? extends Node> node); // // /** // * Called just after {@link #containerBegin(ContainerNode)} if it returned {@code true} or after the children of a // * {@link ContainerNode} were visited. // */ // void containerEnd(); // // /** // * Check whether the elements of the given {@link ListNode} should be visited. // * // * @param node the current {@link ListNode} // * @return {@code true} if the calling walker should traverse the elements of the given {@code node}; {@code false} // * otherwise // */ // boolean listBegin(ListNode<? extends Node> node); // // /** // * Called just after {@link #containerBegin(ContainerNode)} if it returned {@code true} or after the children of a // * {@link ListNode} were visited. // */ // void listEnd(); // // /** // * Visit the given {@link ScalarNode}. // * // * @param node the {@link ScalarNode} to visit // */ // void scalar(ScalarNode<Object> node); // // } // Path: srcdeps-core/src/main/java/org/srcdeps/core/config/tree/walk/TreeWalker.java import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.srcdeps.core.config.tree.ContainerNode; import org.srcdeps.core.config.tree.ListNode; import org.srcdeps.core.config.tree.Node; import org.srcdeps.core.config.tree.ScalarNode; import org.srcdeps.core.config.tree.Visitor; /** * Copyright 2015-2018 Maven Source Dependencies * Plugin contributors as indicated by the @author tags. * * 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.srcdeps.core.config.tree.walk; /** * A simple configuration tree walker. * * @author <a href="https://github.com/ppalaga">Peter Palaga</a> */ public class TreeWalker { @SuppressWarnings("unused") private static final Logger log = LoggerFactory.getLogger(TreeWalker.class); public TreeWalker() { super(); } /** * Walks a tree starting at the given {@code node} notifying the {@code visitor}. * * @param node the node to start at * @param visitor the visitor to notify */ @SuppressWarnings("unchecked") public void walk(Node node, Visitor visitor) {
if (node instanceof ScalarNode) {
srcdeps/srcdeps-core
srcdeps-core/src/main/java/org/srcdeps/core/config/tree/walk/TreeWalker.java
// Path: srcdeps-core/src/main/java/org/srcdeps/core/config/tree/ContainerNode.java // public interface ContainerNode<C extends Node> extends Node { // /** // * @return a map of child nodes // */ // Map<String, C> getChildren(); // // } // // Path: srcdeps-core/src/main/java/org/srcdeps/core/config/tree/ListNode.java // public interface ListNode<E extends Node> extends Node { // /** // * @return the elements of this {@link ListNode} // */ // List<E> getElements(); // } // // Path: srcdeps-core/src/main/java/org/srcdeps/core/config/tree/Node.java // public interface Node { // /** // * Apply the defaults or apply some kind of inheritance in case the values of some attributes were not set // * explicitly. See also {@link DefaultsAndInheritanceVisitor}. // * // * @param configurationStack the stack of ancestor configuration nodes. Can be queried to inherit values. // */ // void applyDefaultsAndInheritance(Stack<Node> configurationStack); // // /** // * @return a list of comment lines that should appear before this node // */ // List<String> getCommentBefore(); // // /** // * @return the name of the present node that is supposed to be unique within the parent node. Can be {@code null} in // * case this {@link Node} is an element of a {@link NodeList}. // */ // String getName(); // // /** // * Fully reset the state of this {@link Node} using the given {@code source} {@link Node}. // * // * @param source the {@link Node} to take the values from // */ // void init(Node source); // // /** // * @param stack the ancestor hierarchy of this {@link Node} // * @return {@code true} if this {@link Node}'s internal state has not been set yet or if the state is in the // * instance or implementation specific default state. Otherwise returns {@code false} // */ // boolean isInDefaultState(Stack<Node> stack); // // /** // * @return {@code true} if the name of the node will commonly contain special characters, esp. periods. Otherwise // * returns {@code false} // */ // boolean shouldEscapeName(); // } // // Path: srcdeps-core/src/main/java/org/srcdeps/core/config/tree/ScalarNode.java // public interface ScalarNode<T> extends Node { // /** // * @return the default value to be used if the value of this {@link ScalarNode} is not set explicitly // */ // T getDefaultValue(); // // /** // * @return the type of the value // */ // Class<T> getType(); // // /** // * @return the value stored in this {@link ScalarNode} // */ // T getValue(); // // /** // * Sets the value stored in this {@link ScalarNode}. // * // * @param value the value to set // */ // void setValue(T value); // } // // Path: srcdeps-core/src/main/java/org/srcdeps/core/config/tree/Visitor.java // public interface Visitor { // // /** // * Check whether the children of the given {@link ContainerNode} should be visited. // * // * @param node the current {@link ContainerNode} // * @return {@code true} if the calling walker should traverse the children of the given {@code node}; {@code false} // * otherwise // */ // boolean containerBegin(ContainerNode<? extends Node> node); // // /** // * Called just after {@link #containerBegin(ContainerNode)} if it returned {@code true} or after the children of a // * {@link ContainerNode} were visited. // */ // void containerEnd(); // // /** // * Check whether the elements of the given {@link ListNode} should be visited. // * // * @param node the current {@link ListNode} // * @return {@code true} if the calling walker should traverse the elements of the given {@code node}; {@code false} // * otherwise // */ // boolean listBegin(ListNode<? extends Node> node); // // /** // * Called just after {@link #containerBegin(ContainerNode)} if it returned {@code true} or after the children of a // * {@link ListNode} were visited. // */ // void listEnd(); // // /** // * Visit the given {@link ScalarNode}. // * // * @param node the {@link ScalarNode} to visit // */ // void scalar(ScalarNode<Object> node); // // }
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.srcdeps.core.config.tree.ContainerNode; import org.srcdeps.core.config.tree.ListNode; import org.srcdeps.core.config.tree.Node; import org.srcdeps.core.config.tree.ScalarNode; import org.srcdeps.core.config.tree.Visitor;
/** * Copyright 2015-2018 Maven Source Dependencies * Plugin contributors as indicated by the @author tags. * * 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.srcdeps.core.config.tree.walk; /** * A simple configuration tree walker. * * @author <a href="https://github.com/ppalaga">Peter Palaga</a> */ public class TreeWalker { @SuppressWarnings("unused") private static final Logger log = LoggerFactory.getLogger(TreeWalker.class); public TreeWalker() { super(); } /** * Walks a tree starting at the given {@code node} notifying the {@code visitor}. * * @param node the node to start at * @param visitor the visitor to notify */ @SuppressWarnings("unchecked") public void walk(Node node, Visitor visitor) { if (node instanceof ScalarNode) { visitor.scalar((ScalarNode<Object>) node);
// Path: srcdeps-core/src/main/java/org/srcdeps/core/config/tree/ContainerNode.java // public interface ContainerNode<C extends Node> extends Node { // /** // * @return a map of child nodes // */ // Map<String, C> getChildren(); // // } // // Path: srcdeps-core/src/main/java/org/srcdeps/core/config/tree/ListNode.java // public interface ListNode<E extends Node> extends Node { // /** // * @return the elements of this {@link ListNode} // */ // List<E> getElements(); // } // // Path: srcdeps-core/src/main/java/org/srcdeps/core/config/tree/Node.java // public interface Node { // /** // * Apply the defaults or apply some kind of inheritance in case the values of some attributes were not set // * explicitly. See also {@link DefaultsAndInheritanceVisitor}. // * // * @param configurationStack the stack of ancestor configuration nodes. Can be queried to inherit values. // */ // void applyDefaultsAndInheritance(Stack<Node> configurationStack); // // /** // * @return a list of comment lines that should appear before this node // */ // List<String> getCommentBefore(); // // /** // * @return the name of the present node that is supposed to be unique within the parent node. Can be {@code null} in // * case this {@link Node} is an element of a {@link NodeList}. // */ // String getName(); // // /** // * Fully reset the state of this {@link Node} using the given {@code source} {@link Node}. // * // * @param source the {@link Node} to take the values from // */ // void init(Node source); // // /** // * @param stack the ancestor hierarchy of this {@link Node} // * @return {@code true} if this {@link Node}'s internal state has not been set yet or if the state is in the // * instance or implementation specific default state. Otherwise returns {@code false} // */ // boolean isInDefaultState(Stack<Node> stack); // // /** // * @return {@code true} if the name of the node will commonly contain special characters, esp. periods. Otherwise // * returns {@code false} // */ // boolean shouldEscapeName(); // } // // Path: srcdeps-core/src/main/java/org/srcdeps/core/config/tree/ScalarNode.java // public interface ScalarNode<T> extends Node { // /** // * @return the default value to be used if the value of this {@link ScalarNode} is not set explicitly // */ // T getDefaultValue(); // // /** // * @return the type of the value // */ // Class<T> getType(); // // /** // * @return the value stored in this {@link ScalarNode} // */ // T getValue(); // // /** // * Sets the value stored in this {@link ScalarNode}. // * // * @param value the value to set // */ // void setValue(T value); // } // // Path: srcdeps-core/src/main/java/org/srcdeps/core/config/tree/Visitor.java // public interface Visitor { // // /** // * Check whether the children of the given {@link ContainerNode} should be visited. // * // * @param node the current {@link ContainerNode} // * @return {@code true} if the calling walker should traverse the children of the given {@code node}; {@code false} // * otherwise // */ // boolean containerBegin(ContainerNode<? extends Node> node); // // /** // * Called just after {@link #containerBegin(ContainerNode)} if it returned {@code true} or after the children of a // * {@link ContainerNode} were visited. // */ // void containerEnd(); // // /** // * Check whether the elements of the given {@link ListNode} should be visited. // * // * @param node the current {@link ListNode} // * @return {@code true} if the calling walker should traverse the elements of the given {@code node}; {@code false} // * otherwise // */ // boolean listBegin(ListNode<? extends Node> node); // // /** // * Called just after {@link #containerBegin(ContainerNode)} if it returned {@code true} or after the children of a // * {@link ListNode} were visited. // */ // void listEnd(); // // /** // * Visit the given {@link ScalarNode}. // * // * @param node the {@link ScalarNode} to visit // */ // void scalar(ScalarNode<Object> node); // // } // Path: srcdeps-core/src/main/java/org/srcdeps/core/config/tree/walk/TreeWalker.java import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.srcdeps.core.config.tree.ContainerNode; import org.srcdeps.core.config.tree.ListNode; import org.srcdeps.core.config.tree.Node; import org.srcdeps.core.config.tree.ScalarNode; import org.srcdeps.core.config.tree.Visitor; /** * Copyright 2015-2018 Maven Source Dependencies * Plugin contributors as indicated by the @author tags. * * 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.srcdeps.core.config.tree.walk; /** * A simple configuration tree walker. * * @author <a href="https://github.com/ppalaga">Peter Palaga</a> */ public class TreeWalker { @SuppressWarnings("unused") private static final Logger log = LoggerFactory.getLogger(TreeWalker.class); public TreeWalker() { super(); } /** * Walks a tree starting at the given {@code node} notifying the {@code visitor}. * * @param node the node to start at * @param visitor the visitor to notify */ @SuppressWarnings("unchecked") public void walk(Node node, Visitor visitor) { if (node instanceof ScalarNode) { visitor.scalar((ScalarNode<Object>) node);
} else if (node instanceof ListNode) {
srcdeps/srcdeps-core
srcdeps-core/src/main/java/org/srcdeps/core/GavSetWalker.java
// Path: srcdeps-core/src/main/java/org/srcdeps/core/util/BitStack.java // public class BitStack { // private final BitSet bits = new BitSet(); // private int size = 0; // // /** // * Pushes an item onto the top of this stack. // * // * @param item the item to push // * @return the {@code item} argument. // */ // public boolean push(boolean item) { // bits.set(size++, item); // return item; // } // // /** // * Removes the object at the top of this stack and returns it. // * // * @return The object at the top of this stack // * @throws EmptyStackException if this stack is empty. // */ // public synchronized boolean pop() { // boolean result = peek(); // size--; // return result; // } // // /** // * Returns the object at the top of this stack without removing it from the stack. // * // * @return the object at the top of this stack // * @throws EmptyStackException if this stack is empty. // */ // public synchronized boolean peek() { // if (size == 0) // throw new EmptyStackException(); // return bits.get(size - 1); // } // // /** // * @return {@code true} if and only if this stack contains no items; {@code false} otherwise. // */ // public boolean empty() { // return size == 0; // } // // } // // Path: srcdeps-core/src/main/java/org/srcdeps/core/util/Consumer.java // public interface Consumer<T> { // void accept(T t); // }
import java.util.TreeMap; import org.srcdeps.core.util.BitStack; import org.srcdeps.core.util.Consumer; import java.io.File; import java.io.IOException; import java.nio.file.FileVisitResult; import java.nio.file.FileVisitor; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.attribute.BasicFileAttributes; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.ListIterator; import java.util.Map;
/** * Copyright 2015-2018 Maven Source Dependencies * Plugin contributors as indicated by the @author tags. * * 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.srcdeps.core; /** * A tree walker through the files in the local Maven repository which belong to a specific {@link GavSet}. * * @author <a href="https://github.com/ppalaga">Peter Palaga</a> * @since 3.2.2 */ public class GavSetWalker { /** * A simple {@link Consumer} that just collects the GAV {@link Path}s into {@link #gavPaths} {@link Map}. */ public static class GavPathCollector implements Consumer<GavtcPath> { private final Map<Path, Gav> gavPaths = new TreeMap<>(); @Override public void accept(GavtcPath t) { gavPaths.put(t.getPath().getParent(), t); } /** * @return the GAV {@link Path}s collected */ public Map<Path, Gav> getGavPaths() { return gavPaths; } } /** * A {@link FileVisitor} for walking the local Maven repository. */ static class GavtcPathVisitor implements FileVisitor<Path> { static boolean hasIgnorableExtension(String name) { for (String ext : IGNORABLE_EXTENSIONS) { if (name.endsWith(ext)) { return true; } } return false; } private final Consumer<GavtcPath> callback;
// Path: srcdeps-core/src/main/java/org/srcdeps/core/util/BitStack.java // public class BitStack { // private final BitSet bits = new BitSet(); // private int size = 0; // // /** // * Pushes an item onto the top of this stack. // * // * @param item the item to push // * @return the {@code item} argument. // */ // public boolean push(boolean item) { // bits.set(size++, item); // return item; // } // // /** // * Removes the object at the top of this stack and returns it. // * // * @return The object at the top of this stack // * @throws EmptyStackException if this stack is empty. // */ // public synchronized boolean pop() { // boolean result = peek(); // size--; // return result; // } // // /** // * Returns the object at the top of this stack without removing it from the stack. // * // * @return the object at the top of this stack // * @throws EmptyStackException if this stack is empty. // */ // public synchronized boolean peek() { // if (size == 0) // throw new EmptyStackException(); // return bits.get(size - 1); // } // // /** // * @return {@code true} if and only if this stack contains no items; {@code false} otherwise. // */ // public boolean empty() { // return size == 0; // } // // } // // Path: srcdeps-core/src/main/java/org/srcdeps/core/util/Consumer.java // public interface Consumer<T> { // void accept(T t); // } // Path: srcdeps-core/src/main/java/org/srcdeps/core/GavSetWalker.java import java.util.TreeMap; import org.srcdeps.core.util.BitStack; import org.srcdeps.core.util.Consumer; import java.io.File; import java.io.IOException; import java.nio.file.FileVisitResult; import java.nio.file.FileVisitor; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.attribute.BasicFileAttributes; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.ListIterator; import java.util.Map; /** * Copyright 2015-2018 Maven Source Dependencies * Plugin contributors as indicated by the @author tags. * * 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.srcdeps.core; /** * A tree walker through the files in the local Maven repository which belong to a specific {@link GavSet}. * * @author <a href="https://github.com/ppalaga">Peter Palaga</a> * @since 3.2.2 */ public class GavSetWalker { /** * A simple {@link Consumer} that just collects the GAV {@link Path}s into {@link #gavPaths} {@link Map}. */ public static class GavPathCollector implements Consumer<GavtcPath> { private final Map<Path, Gav> gavPaths = new TreeMap<>(); @Override public void accept(GavtcPath t) { gavPaths.put(t.getPath().getParent(), t); } /** * @return the GAV {@link Path}s collected */ public Map<Path, Gav> getGavPaths() { return gavPaths; } } /** * A {@link FileVisitor} for walking the local Maven repository. */ static class GavtcPathVisitor implements FileVisitor<Path> { static boolean hasIgnorableExtension(String name) { for (String ext : IGNORABLE_EXTENSIONS) { if (name.endsWith(ext)) { return true; } } return false; } private final Consumer<GavtcPath> callback;
private final BitStack dirCanContainArtifacts = new BitStack();
srcdeps/srcdeps-core
srcdeps-core/src/main/java/org/srcdeps/core/shell/Shell.java
// Path: srcdeps-core/src/main/java/org/srcdeps/core/BuildException.java // public class BuildException extends Exception { // private static final long serialVersionUID = 1520625837859688798L; // // public BuildException(String message) { // super(message); // } // // public BuildException(String message, Throwable cause) { // super(message, cause); // } // // public BuildException(Throwable cause) { // super(cause); // } // // }
import java.io.BufferedReader; import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.srcdeps.core.BuildException;
} public void cancel() { this.cancelled = true; } @Override public void run() { try (BufferedReader r = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8))) { String line; while (!cancelled && (line = r.readLine()) != null) { out.accept(line); } } catch (IOException e) { exception = e; } } } static final Logger log = LoggerFactory.getLogger(Shell.class); /** * Executes the given {@link ShellCommand} synchronously. * * @param command the command to execute * @return the {@link CommandResult} that can be used to determine if the execution was successful * @throws BuildException on any build related problems * @throws CommandTimeoutException if the execution is not finished within the timeout defined in * {@link ShellCommand#getTimeoutMs()} */
// Path: srcdeps-core/src/main/java/org/srcdeps/core/BuildException.java // public class BuildException extends Exception { // private static final long serialVersionUID = 1520625837859688798L; // // public BuildException(String message) { // super(message); // } // // public BuildException(String message, Throwable cause) { // super(message, cause); // } // // public BuildException(Throwable cause) { // super(cause); // } // // } // Path: srcdeps-core/src/main/java/org/srcdeps/core/shell/Shell.java import java.io.BufferedReader; import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.srcdeps.core.BuildException; } public void cancel() { this.cancelled = true; } @Override public void run() { try (BufferedReader r = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8))) { String line; while (!cancelled && (line = r.readLine()) != null) { out.accept(line); } } catch (IOException e) { exception = e; } } } static final Logger log = LoggerFactory.getLogger(Shell.class); /** * Executes the given {@link ShellCommand} synchronously. * * @param command the command to execute * @return the {@link CommandResult} that can be used to determine if the execution was successful * @throws BuildException on any build related problems * @throws CommandTimeoutException if the execution is not finished within the timeout defined in * {@link ShellCommand#getTimeoutMs()} */
public static CommandResult execute(ShellCommand command) throws BuildException, CommandTimeoutException {
srcdeps/srcdeps-core
srcdeps-core/src/main/java/org/srcdeps/core/config/scalar/Scalars.java
// Path: srcdeps-core/src/main/java/org/srcdeps/core/BuildRequest.java // public enum Verbosity { // debug, error, info, trace, warn; // // public static Verbosity fastValueOf(String level) { // SrcdepsCoreUtils.assertArgNotNull(level, "Verbosity name"); // switch (level.toLowerCase(Locale.ROOT)) { // case "trace": // return trace; // case "debug": // return debug; // case "info": // return info; // case "warn": // return warn; // case "error": // return error; // default: // throw new IllegalStateException("No such " + Verbosity.class.getName() + " with name [" + level + "]"); // } // } // // } // // Path: srcdeps-core/src/main/java/org/srcdeps/core/config/tree/ScalarDeserializer.java // public interface ScalarDeserializer { // /** // * Deserialize the given {@link String} value to an object of another type such as int, Integer, boolean, Boolean, // * etc. // * // * @param value the {@link String} value to deserialize. // * @return the deserialized value // */ // Object deserialize(String value); // }
import java.lang.reflect.Type; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Collections; import java.util.HashMap; import java.util.Map; import org.srcdeps.core.BuildRequest.Verbosity; import org.srcdeps.core.config.tree.ScalarDeserializer;
/** * Copyright 2015-2018 Maven Source Dependencies * Plugin contributors as indicated by the @author tags. * * 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.srcdeps.core.config.scalar; /** * Hosts scalar types related helper methods. * * @author <a href="https://github.com/ppalaga">Peter Palaga</a> */ public final class Scalars { /** * {@link Map} from types we consider primitive to their respective {@link ScalarDeserializer}s. */ private static final Map<Type, ScalarDeserializer> SCALAR_TYPES; static { /* Put a ScalarDeserializer for every scalar type to scalarTypes map */ Map<Type, ScalarDeserializer> primitives = new HashMap<>(); primitives.put(String.class, new ScalarDeserializer() { @Override public Object deserialize(String value) { return value; } }); primitives.put(Boolean.class, new ScalarDeserializer() { @Override public Object deserialize(String value) { return Boolean.valueOf(value); } }); primitives.put(boolean.class, new ScalarDeserializer() { @Override public Object deserialize(String value) { return Boolean.parseBoolean(value); } }); primitives.put(Integer.class, new ScalarDeserializer() { @Override public Object deserialize(String value) { return Integer.valueOf(value); } }); primitives.put(int.class, new ScalarDeserializer() { @Override public Object deserialize(String value) { return Integer.parseInt(value); } }); primitives.put(Long.class, new ScalarDeserializer() { @Override public Object deserialize(String value) { return Long.valueOf(value); } }); primitives.put(long.class, new ScalarDeserializer() { @Override public Object deserialize(String value) { return Long.parseLong(value); } }); primitives.put(Double.class, new ScalarDeserializer() { @Override public Object deserialize(String value) { return Double.valueOf(value); } }); primitives.put(double.class, new ScalarDeserializer() { @Override public Object deserialize(String value) { return Double.parseDouble(value); } }); primitives.put(Float.class, new ScalarDeserializer() { @Override public Object deserialize(String value) { return Float.valueOf(value); } }); primitives.put(float.class, new ScalarDeserializer() { @Override public Object deserialize(String value) { return Float.parseFloat(value); } }); primitives.put(Short.class, new ScalarDeserializer() { @Override public Object deserialize(String value) { return Short.valueOf(value); } }); primitives.put(short.class, new ScalarDeserializer() { @Override public Object deserialize(String value) { return Short.parseShort(value); } }); primitives.put(Character.class, new ScalarDeserializer() { @Override public Object deserialize(String value) { if (value.length() != 1) { throw new RuntimeException( String.format("Cannot transform String [%s] of length %d to char", value, value.length())); } return Character.valueOf(value.charAt(0)); } }); primitives.put(char.class, new ScalarDeserializer() { @Override public Object deserialize(String value) { if (value.length() != 1) { throw new RuntimeException( String.format("Cannot transform String [%s] of length %d to char", value, value.length())); } return value.charAt(0); } });
// Path: srcdeps-core/src/main/java/org/srcdeps/core/BuildRequest.java // public enum Verbosity { // debug, error, info, trace, warn; // // public static Verbosity fastValueOf(String level) { // SrcdepsCoreUtils.assertArgNotNull(level, "Verbosity name"); // switch (level.toLowerCase(Locale.ROOT)) { // case "trace": // return trace; // case "debug": // return debug; // case "info": // return info; // case "warn": // return warn; // case "error": // return error; // default: // throw new IllegalStateException("No such " + Verbosity.class.getName() + " with name [" + level + "]"); // } // } // // } // // Path: srcdeps-core/src/main/java/org/srcdeps/core/config/tree/ScalarDeserializer.java // public interface ScalarDeserializer { // /** // * Deserialize the given {@link String} value to an object of another type such as int, Integer, boolean, Boolean, // * etc. // * // * @param value the {@link String} value to deserialize. // * @return the deserialized value // */ // Object deserialize(String value); // } // Path: srcdeps-core/src/main/java/org/srcdeps/core/config/scalar/Scalars.java import java.lang.reflect.Type; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Collections; import java.util.HashMap; import java.util.Map; import org.srcdeps.core.BuildRequest.Verbosity; import org.srcdeps.core.config.tree.ScalarDeserializer; /** * Copyright 2015-2018 Maven Source Dependencies * Plugin contributors as indicated by the @author tags. * * 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.srcdeps.core.config.scalar; /** * Hosts scalar types related helper methods. * * @author <a href="https://github.com/ppalaga">Peter Palaga</a> */ public final class Scalars { /** * {@link Map} from types we consider primitive to their respective {@link ScalarDeserializer}s. */ private static final Map<Type, ScalarDeserializer> SCALAR_TYPES; static { /* Put a ScalarDeserializer for every scalar type to scalarTypes map */ Map<Type, ScalarDeserializer> primitives = new HashMap<>(); primitives.put(String.class, new ScalarDeserializer() { @Override public Object deserialize(String value) { return value; } }); primitives.put(Boolean.class, new ScalarDeserializer() { @Override public Object deserialize(String value) { return Boolean.valueOf(value); } }); primitives.put(boolean.class, new ScalarDeserializer() { @Override public Object deserialize(String value) { return Boolean.parseBoolean(value); } }); primitives.put(Integer.class, new ScalarDeserializer() { @Override public Object deserialize(String value) { return Integer.valueOf(value); } }); primitives.put(int.class, new ScalarDeserializer() { @Override public Object deserialize(String value) { return Integer.parseInt(value); } }); primitives.put(Long.class, new ScalarDeserializer() { @Override public Object deserialize(String value) { return Long.valueOf(value); } }); primitives.put(long.class, new ScalarDeserializer() { @Override public Object deserialize(String value) { return Long.parseLong(value); } }); primitives.put(Double.class, new ScalarDeserializer() { @Override public Object deserialize(String value) { return Double.valueOf(value); } }); primitives.put(double.class, new ScalarDeserializer() { @Override public Object deserialize(String value) { return Double.parseDouble(value); } }); primitives.put(Float.class, new ScalarDeserializer() { @Override public Object deserialize(String value) { return Float.valueOf(value); } }); primitives.put(float.class, new ScalarDeserializer() { @Override public Object deserialize(String value) { return Float.parseFloat(value); } }); primitives.put(Short.class, new ScalarDeserializer() { @Override public Object deserialize(String value) { return Short.valueOf(value); } }); primitives.put(short.class, new ScalarDeserializer() { @Override public Object deserialize(String value) { return Short.parseShort(value); } }); primitives.put(Character.class, new ScalarDeserializer() { @Override public Object deserialize(String value) { if (value.length() != 1) { throw new RuntimeException( String.format("Cannot transform String [%s] of length %d to char", value, value.length())); } return Character.valueOf(value.charAt(0)); } }); primitives.put(char.class, new ScalarDeserializer() { @Override public Object deserialize(String value) { if (value.length() != 1) { throw new RuntimeException( String.format("Cannot transform String [%s] of length %d to char", value, value.length())); } return value.charAt(0); } });
primitives.put(Verbosity.class, new ScalarDeserializer() {
LapisBlue/Commons
src/test/java/blue/lapis/common/command/ParsingTest.java
// Path: src/main/java/blue/lapis/common/command/impl/Parsing.java // public class Parsing { // // public static String toLowerCase(String s) { // return s.toLowerCase(Locale.ENGLISH); // } // // public static boolean startsWithIgnoreCase(String s, String start) { // return s.regionMatches(true, 0, start, 0, start.length()); // } // // public static ImmutableList<String> split(String s, String delimiter) { // ImmutableList.Builder<String> builder = ImmutableList.builder(); // int tokenEnd = s.indexOf(delimiter); // int loc = 0; // while (tokenEnd >= 0) { // if (tokenEnd > loc) { // builder.add(s.substring(loc, tokenEnd)); // } // loc = tokenEnd + delimiter.length(); // tokenEnd = s.indexOf(delimiter, loc); // } // if (loc < s.length()) builder.add(s.substring(loc, s.length())); // // return builder.build(); // } // // public static String join(List<String> strings) { // int length = 0; // for (String s : strings) { // length += s.length(); // } // // char[] value = new char[length]; // int count = 0; // for (String s : strings) { // int len = s.length(); // if (len == 0) continue; // int newCount = count + len; // s.getChars(0, len, value, count); // count = newCount; // } // return new String(value); // } // // public static String join(List<String> strings, String delimiter) { // int length = 0; // for (String s : strings) { // length += s.length(); // } // length += delimiter.length() * (strings.size() - 1); // // char[] value = new char[length]; // int count = 0; // int numStrings = strings.size(); // for (String s : strings) { // int len = s.length(); // if (len == 0) continue; // int newCount = count + len; // s.getChars(0, len, value, count); // count = newCount; // // numStrings--; // if (numStrings > 0) { // len = delimiter.length(); // if (len == 0) continue; // newCount = count + len; // delimiter.getChars(0, len, value, count); // count = newCount; // } // } // return new String(value); // } // // }
import com.google.common.collect.ImmutableList; import org.junit.Test; import java.util.List; import java.util.regex.Pattern; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import blue.lapis.common.command.impl.Parsing; import com.google.common.base.Joiner; import com.google.common.base.Splitter;
/* * LapisCommons * Copyright (c) 2014, Lapis <https://github.com/LapisBlue> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package blue.lapis.common.command; /** * */ public class ParsingTest { @Test public void toLowerCase() {
// Path: src/main/java/blue/lapis/common/command/impl/Parsing.java // public class Parsing { // // public static String toLowerCase(String s) { // return s.toLowerCase(Locale.ENGLISH); // } // // public static boolean startsWithIgnoreCase(String s, String start) { // return s.regionMatches(true, 0, start, 0, start.length()); // } // // public static ImmutableList<String> split(String s, String delimiter) { // ImmutableList.Builder<String> builder = ImmutableList.builder(); // int tokenEnd = s.indexOf(delimiter); // int loc = 0; // while (tokenEnd >= 0) { // if (tokenEnd > loc) { // builder.add(s.substring(loc, tokenEnd)); // } // loc = tokenEnd + delimiter.length(); // tokenEnd = s.indexOf(delimiter, loc); // } // if (loc < s.length()) builder.add(s.substring(loc, s.length())); // // return builder.build(); // } // // public static String join(List<String> strings) { // int length = 0; // for (String s : strings) { // length += s.length(); // } // // char[] value = new char[length]; // int count = 0; // for (String s : strings) { // int len = s.length(); // if (len == 0) continue; // int newCount = count + len; // s.getChars(0, len, value, count); // count = newCount; // } // return new String(value); // } // // public static String join(List<String> strings, String delimiter) { // int length = 0; // for (String s : strings) { // length += s.length(); // } // length += delimiter.length() * (strings.size() - 1); // // char[] value = new char[length]; // int count = 0; // int numStrings = strings.size(); // for (String s : strings) { // int len = s.length(); // if (len == 0) continue; // int newCount = count + len; // s.getChars(0, len, value, count); // count = newCount; // // numStrings--; // if (numStrings > 0) { // len = delimiter.length(); // if (len == 0) continue; // newCount = count + len; // delimiter.getChars(0, len, value, count); // count = newCount; // } // } // return new String(value); // } // // } // Path: src/test/java/blue/lapis/common/command/ParsingTest.java import com.google.common.collect.ImmutableList; import org.junit.Test; import java.util.List; import java.util.regex.Pattern; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import blue.lapis.common.command.impl.Parsing; import com.google.common.base.Joiner; import com.google.common.base.Splitter; /* * LapisCommons * Copyright (c) 2014, Lapis <https://github.com/LapisBlue> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package blue.lapis.common.command; /** * */ public class ParsingTest { @Test public void toLowerCase() {
assertEquals(Parsing.toLowerCase("lApIsCoMmOnS"), "lapiscommons");
LapisBlue/Commons
src/main/java/blue/lapis/common/permission/Group.java
// Path: src/main/java/blue/lapis/common/permission/impl/StandardGroup.java // public class StandardGroup implements Group { // // private String id = "untitled"; // // IndexedSet<Group> immediateSupers; // IndexedSet<Group> immediateSubsets; // IndexedSet<Group> cache; // // public StandardGroup(String name) { // Preconditions.checkArgument(!name.trim().isEmpty(), "Name cannot be empty or whitespace."); // id = name.trim().toLowerCase(); // } // // public Group forNode(String nodeName) { // //in terms of iterations, this is the shortest possible search for implication/compound nodes // if (nodeName.indexOf('&') >= 0) { // // } // // //This is an ordinary node // return new StandardGroup(nodeName); // } // // @Override // public String getId() { // return id; // } // // @Override // public ImmutableSet<Group> getInheritors() { // return immediateSupers.resolve(); // } // // @Override // public boolean hasInheritor(final Group superset) { // return immediateSupers.contains(superset); // } // // @Override // public void addInheritor(final Group superset) { // immediateSupers.add(superset); // } // // @Override // public ImmutableSet<Group> getInheritance() { // return immediateSubsets.resolve(); // } // // @Override // public boolean inheritsFrom(final Group subset) { // return immediateSubsets.contains(subset); // } // // @Override // public void inheritFrom(final Group subset) { // immediateSubsets.add(subset); // } // // @Override // public boolean declaresPermission(final String node, final Group origin) { // if (id.equals(node)) return true; // if (node.startsWith(id + '.')) return true; // return false; // } // // @Override // public boolean grantsPermission(final String node, int depth, final Group origin) { // if (declaresPermission(node, origin)) return true; // if (depth > Group.MAX_SEARCH_DEPTH) return false; // for (Group group : immediateSubsets) { // if (group.grantsPermission(node, depth, origin)) return true; // } // // return false; // } // // }
import blue.lapis.common.permission.impl.StandardGroup; import com.google.common.collect.ImmutableSet;
/* * LapisCommons * Copyright (c) 2014, Lapis <https://github.com/LapisBlue> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package blue.lapis.common.permission; /** * Represents a collection of objects which permissions apply to, along with their inheritance * relationship and any associated permissions nodes. */ public interface Group { public static int MAX_SEARCH_DEPTH = 16;
// Path: src/main/java/blue/lapis/common/permission/impl/StandardGroup.java // public class StandardGroup implements Group { // // private String id = "untitled"; // // IndexedSet<Group> immediateSupers; // IndexedSet<Group> immediateSubsets; // IndexedSet<Group> cache; // // public StandardGroup(String name) { // Preconditions.checkArgument(!name.trim().isEmpty(), "Name cannot be empty or whitespace."); // id = name.trim().toLowerCase(); // } // // public Group forNode(String nodeName) { // //in terms of iterations, this is the shortest possible search for implication/compound nodes // if (nodeName.indexOf('&') >= 0) { // // } // // //This is an ordinary node // return new StandardGroup(nodeName); // } // // @Override // public String getId() { // return id; // } // // @Override // public ImmutableSet<Group> getInheritors() { // return immediateSupers.resolve(); // } // // @Override // public boolean hasInheritor(final Group superset) { // return immediateSupers.contains(superset); // } // // @Override // public void addInheritor(final Group superset) { // immediateSupers.add(superset); // } // // @Override // public ImmutableSet<Group> getInheritance() { // return immediateSubsets.resolve(); // } // // @Override // public boolean inheritsFrom(final Group subset) { // return immediateSubsets.contains(subset); // } // // @Override // public void inheritFrom(final Group subset) { // immediateSubsets.add(subset); // } // // @Override // public boolean declaresPermission(final String node, final Group origin) { // if (id.equals(node)) return true; // if (node.startsWith(id + '.')) return true; // return false; // } // // @Override // public boolean grantsPermission(final String node, int depth, final Group origin) { // if (declaresPermission(node, origin)) return true; // if (depth > Group.MAX_SEARCH_DEPTH) return false; // for (Group group : immediateSubsets) { // if (group.grantsPermission(node, depth, origin)) return true; // } // // return false; // } // // } // Path: src/main/java/blue/lapis/common/permission/Group.java import blue.lapis.common.permission.impl.StandardGroup; import com.google.common.collect.ImmutableSet; /* * LapisCommons * Copyright (c) 2014, Lapis <https://github.com/LapisBlue> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package blue.lapis.common.permission; /** * Represents a collection of objects which permissions apply to, along with their inheritance * relationship and any associated permissions nodes. */ public interface Group { public static int MAX_SEARCH_DEPTH = 16;
public static final Group ALL_GROUPS = new StandardGroup("root");
LapisBlue/Commons
src/main/java/blue/lapis/common/command/impl/PlayerTokenParser.java
// Path: src/main/java/blue/lapis/common/LapisCommonsPlugin.java // @Plugin(id = "lapis-commons", name = "LapisCommons", version = "1.0.0-SNAPSHOT") // public class LapisCommonsPlugin { // private static LapisCommonsPlugin instance; // // private final Game game; // private final PluginContainer container; // // @Inject // protected Logger logger; // // @Inject // public LapisCommonsPlugin(Game game, PluginContainer container) { // this.game = game; // this.container = container; // } // // /** // * Gets the instance of the LapisCommons plugin. // * // * @return The currently loaded plugin instance or null if the plugin is not loaded. // */ // public static LapisCommonsPlugin getInstance() { // return instance; // } // // /** // * Gets the instance the {@link Game} instance of the current server implementation. // * // * @return The game instance of the server implementation or null if the plugin is not loaded. // */ // public static Game getGame() { // return getInstance().game; // } // // /** // * Gets the plugin logger of the LapisCommons plugin. // * // * @return The plugin logger for this plugin or null if the plugin is not loaded // */ // public static Logger getLogger() { // return getInstance().logger; // } // // @Subscribe // public void initialize(PreInitializationEvent event) { // instance = this; // } // } // // Path: src/main/java/blue/lapis/common/command/token/InvalidTokenException.java // public class InvalidTokenException extends RuntimeException { // // private String token; // private Class<?> expectedType; // // public InvalidTokenException(String token, Class<?> expectedType) { // this.token = token; // this.expectedType = expectedType; // } // // /** // * @return the token that the TokenParser attempted to resolve // */ // public String getToken() { // return token; // } // // /** // * @return the Class of the object which the TokenParser creates // */ // public Class<?> getExpectedType() { // return expectedType; // } // } // // Path: src/main/java/blue/lapis/common/command/token/TokenParser.java // public interface TokenParser<T> { // // /** // * Parse the provided parser and return a typesafe object for it. // * // * @param source the Player, console, or command block which initiated this object resolution // * @param token the token to be resolved into an object of type {@code T} // * @return an object of type T which corresponds to the String entered // * // * @throws InvalidTokenException if the String does not appear to match any object // */ // T parse(CommandSource source, String token); // // /** // * Get tab-complete suggestions for this parser // * // * @param source The Player, CommandBlock, etc. responsible for this token // * @param token The token to generate tab-complete suggestions for // * @return a List of possible completions, or an empty List if none are available // */ // List<String> suggest(CommandSource source, String token); // }
import java.util.Collection; import java.util.List; import blue.lapis.common.LapisCommonsPlugin; import blue.lapis.common.command.token.InvalidTokenException; import blue.lapis.common.command.token.TokenParser; import com.google.common.collect.Lists; import org.spongepowered.api.entity.player.Player; import org.spongepowered.api.util.command.CommandSource;
/* * LapisCommons * Copyright (c) 2014, Lapis <https://github.com/LapisBlue> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package blue.lapis.common.command.impl; /** * Converts a Player name into an online {@link Player}. */ public class PlayerTokenParser implements TokenParser<Player> { @Override public Player parse(final CommandSource source, final String token) {
// Path: src/main/java/blue/lapis/common/LapisCommonsPlugin.java // @Plugin(id = "lapis-commons", name = "LapisCommons", version = "1.0.0-SNAPSHOT") // public class LapisCommonsPlugin { // private static LapisCommonsPlugin instance; // // private final Game game; // private final PluginContainer container; // // @Inject // protected Logger logger; // // @Inject // public LapisCommonsPlugin(Game game, PluginContainer container) { // this.game = game; // this.container = container; // } // // /** // * Gets the instance of the LapisCommons plugin. // * // * @return The currently loaded plugin instance or null if the plugin is not loaded. // */ // public static LapisCommonsPlugin getInstance() { // return instance; // } // // /** // * Gets the instance the {@link Game} instance of the current server implementation. // * // * @return The game instance of the server implementation or null if the plugin is not loaded. // */ // public static Game getGame() { // return getInstance().game; // } // // /** // * Gets the plugin logger of the LapisCommons plugin. // * // * @return The plugin logger for this plugin or null if the plugin is not loaded // */ // public static Logger getLogger() { // return getInstance().logger; // } // // @Subscribe // public void initialize(PreInitializationEvent event) { // instance = this; // } // } // // Path: src/main/java/blue/lapis/common/command/token/InvalidTokenException.java // public class InvalidTokenException extends RuntimeException { // // private String token; // private Class<?> expectedType; // // public InvalidTokenException(String token, Class<?> expectedType) { // this.token = token; // this.expectedType = expectedType; // } // // /** // * @return the token that the TokenParser attempted to resolve // */ // public String getToken() { // return token; // } // // /** // * @return the Class of the object which the TokenParser creates // */ // public Class<?> getExpectedType() { // return expectedType; // } // } // // Path: src/main/java/blue/lapis/common/command/token/TokenParser.java // public interface TokenParser<T> { // // /** // * Parse the provided parser and return a typesafe object for it. // * // * @param source the Player, console, or command block which initiated this object resolution // * @param token the token to be resolved into an object of type {@code T} // * @return an object of type T which corresponds to the String entered // * // * @throws InvalidTokenException if the String does not appear to match any object // */ // T parse(CommandSource source, String token); // // /** // * Get tab-complete suggestions for this parser // * // * @param source The Player, CommandBlock, etc. responsible for this token // * @param token The token to generate tab-complete suggestions for // * @return a List of possible completions, or an empty List if none are available // */ // List<String> suggest(CommandSource source, String token); // } // Path: src/main/java/blue/lapis/common/command/impl/PlayerTokenParser.java import java.util.Collection; import java.util.List; import blue.lapis.common.LapisCommonsPlugin; import blue.lapis.common.command.token.InvalidTokenException; import blue.lapis.common.command.token.TokenParser; import com.google.common.collect.Lists; import org.spongepowered.api.entity.player.Player; import org.spongepowered.api.util.command.CommandSource; /* * LapisCommons * Copyright (c) 2014, Lapis <https://github.com/LapisBlue> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package blue.lapis.common.command.impl; /** * Converts a Player name into an online {@link Player}. */ public class PlayerTokenParser implements TokenParser<Player> { @Override public Player parse(final CommandSource source, final String token) {
Collection<Player> players = LapisCommonsPlugin.getGame().getServer().getOnlinePlayers();
LapisBlue/Commons
src/main/java/blue/lapis/common/command/impl/PlayerTokenParser.java
// Path: src/main/java/blue/lapis/common/LapisCommonsPlugin.java // @Plugin(id = "lapis-commons", name = "LapisCommons", version = "1.0.0-SNAPSHOT") // public class LapisCommonsPlugin { // private static LapisCommonsPlugin instance; // // private final Game game; // private final PluginContainer container; // // @Inject // protected Logger logger; // // @Inject // public LapisCommonsPlugin(Game game, PluginContainer container) { // this.game = game; // this.container = container; // } // // /** // * Gets the instance of the LapisCommons plugin. // * // * @return The currently loaded plugin instance or null if the plugin is not loaded. // */ // public static LapisCommonsPlugin getInstance() { // return instance; // } // // /** // * Gets the instance the {@link Game} instance of the current server implementation. // * // * @return The game instance of the server implementation or null if the plugin is not loaded. // */ // public static Game getGame() { // return getInstance().game; // } // // /** // * Gets the plugin logger of the LapisCommons plugin. // * // * @return The plugin logger for this plugin or null if the plugin is not loaded // */ // public static Logger getLogger() { // return getInstance().logger; // } // // @Subscribe // public void initialize(PreInitializationEvent event) { // instance = this; // } // } // // Path: src/main/java/blue/lapis/common/command/token/InvalidTokenException.java // public class InvalidTokenException extends RuntimeException { // // private String token; // private Class<?> expectedType; // // public InvalidTokenException(String token, Class<?> expectedType) { // this.token = token; // this.expectedType = expectedType; // } // // /** // * @return the token that the TokenParser attempted to resolve // */ // public String getToken() { // return token; // } // // /** // * @return the Class of the object which the TokenParser creates // */ // public Class<?> getExpectedType() { // return expectedType; // } // } // // Path: src/main/java/blue/lapis/common/command/token/TokenParser.java // public interface TokenParser<T> { // // /** // * Parse the provided parser and return a typesafe object for it. // * // * @param source the Player, console, or command block which initiated this object resolution // * @param token the token to be resolved into an object of type {@code T} // * @return an object of type T which corresponds to the String entered // * // * @throws InvalidTokenException if the String does not appear to match any object // */ // T parse(CommandSource source, String token); // // /** // * Get tab-complete suggestions for this parser // * // * @param source The Player, CommandBlock, etc. responsible for this token // * @param token The token to generate tab-complete suggestions for // * @return a List of possible completions, or an empty List if none are available // */ // List<String> suggest(CommandSource source, String token); // }
import java.util.Collection; import java.util.List; import blue.lapis.common.LapisCommonsPlugin; import blue.lapis.common.command.token.InvalidTokenException; import blue.lapis.common.command.token.TokenParser; import com.google.common.collect.Lists; import org.spongepowered.api.entity.player.Player; import org.spongepowered.api.util.command.CommandSource;
/* * LapisCommons * Copyright (c) 2014, Lapis <https://github.com/LapisBlue> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package blue.lapis.common.command.impl; /** * Converts a Player name into an online {@link Player}. */ public class PlayerTokenParser implements TokenParser<Player> { @Override public Player parse(final CommandSource source, final String token) { Collection<Player> players = LapisCommonsPlugin.getGame().getServer().getOnlinePlayers(); // TODO: strip off leading "p:" ? // attempt resolving full names for (Player p : players) { if (p.getName().equalsIgnoreCase(token)) return p; } // attempt partial names for (Player p : players) { if (Parsing.startsWithIgnoreCase(p.getName(), token)) return p; }
// Path: src/main/java/blue/lapis/common/LapisCommonsPlugin.java // @Plugin(id = "lapis-commons", name = "LapisCommons", version = "1.0.0-SNAPSHOT") // public class LapisCommonsPlugin { // private static LapisCommonsPlugin instance; // // private final Game game; // private final PluginContainer container; // // @Inject // protected Logger logger; // // @Inject // public LapisCommonsPlugin(Game game, PluginContainer container) { // this.game = game; // this.container = container; // } // // /** // * Gets the instance of the LapisCommons plugin. // * // * @return The currently loaded plugin instance or null if the plugin is not loaded. // */ // public static LapisCommonsPlugin getInstance() { // return instance; // } // // /** // * Gets the instance the {@link Game} instance of the current server implementation. // * // * @return The game instance of the server implementation or null if the plugin is not loaded. // */ // public static Game getGame() { // return getInstance().game; // } // // /** // * Gets the plugin logger of the LapisCommons plugin. // * // * @return The plugin logger for this plugin or null if the plugin is not loaded // */ // public static Logger getLogger() { // return getInstance().logger; // } // // @Subscribe // public void initialize(PreInitializationEvent event) { // instance = this; // } // } // // Path: src/main/java/blue/lapis/common/command/token/InvalidTokenException.java // public class InvalidTokenException extends RuntimeException { // // private String token; // private Class<?> expectedType; // // public InvalidTokenException(String token, Class<?> expectedType) { // this.token = token; // this.expectedType = expectedType; // } // // /** // * @return the token that the TokenParser attempted to resolve // */ // public String getToken() { // return token; // } // // /** // * @return the Class of the object which the TokenParser creates // */ // public Class<?> getExpectedType() { // return expectedType; // } // } // // Path: src/main/java/blue/lapis/common/command/token/TokenParser.java // public interface TokenParser<T> { // // /** // * Parse the provided parser and return a typesafe object for it. // * // * @param source the Player, console, or command block which initiated this object resolution // * @param token the token to be resolved into an object of type {@code T} // * @return an object of type T which corresponds to the String entered // * // * @throws InvalidTokenException if the String does not appear to match any object // */ // T parse(CommandSource source, String token); // // /** // * Get tab-complete suggestions for this parser // * // * @param source The Player, CommandBlock, etc. responsible for this token // * @param token The token to generate tab-complete suggestions for // * @return a List of possible completions, or an empty List if none are available // */ // List<String> suggest(CommandSource source, String token); // } // Path: src/main/java/blue/lapis/common/command/impl/PlayerTokenParser.java import java.util.Collection; import java.util.List; import blue.lapis.common.LapisCommonsPlugin; import blue.lapis.common.command.token.InvalidTokenException; import blue.lapis.common.command.token.TokenParser; import com.google.common.collect.Lists; import org.spongepowered.api.entity.player.Player; import org.spongepowered.api.util.command.CommandSource; /* * LapisCommons * Copyright (c) 2014, Lapis <https://github.com/LapisBlue> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package blue.lapis.common.command.impl; /** * Converts a Player name into an online {@link Player}. */ public class PlayerTokenParser implements TokenParser<Player> { @Override public Player parse(final CommandSource source, final String token) { Collection<Player> players = LapisCommonsPlugin.getGame().getServer().getOnlinePlayers(); // TODO: strip off leading "p:" ? // attempt resolving full names for (Player p : players) { if (p.getName().equalsIgnoreCase(token)) return p; } // attempt partial names for (Player p : players) { if (Parsing.startsWithIgnoreCase(p.getName(), token)) return p; }
throw new InvalidTokenException(token, Player.class);
LapisBlue/Commons
src/main/java/blue/lapis/common/command/impl/IntegerTokenParser.java
// Path: src/main/java/blue/lapis/common/command/token/InvalidTokenException.java // public class InvalidTokenException extends RuntimeException { // // private String token; // private Class<?> expectedType; // // public InvalidTokenException(String token, Class<?> expectedType) { // this.token = token; // this.expectedType = expectedType; // } // // /** // * @return the token that the TokenParser attempted to resolve // */ // public String getToken() { // return token; // } // // /** // * @return the Class of the object which the TokenParser creates // */ // public Class<?> getExpectedType() { // return expectedType; // } // } // // Path: src/main/java/blue/lapis/common/command/token/TokenParser.java // public interface TokenParser<T> { // // /** // * Parse the provided parser and return a typesafe object for it. // * // * @param source the Player, console, or command block which initiated this object resolution // * @param token the token to be resolved into an object of type {@code T} // * @return an object of type T which corresponds to the String entered // * // * @throws InvalidTokenException if the String does not appear to match any object // */ // T parse(CommandSource source, String token); // // /** // * Get tab-complete suggestions for this parser // * // * @param source The Player, CommandBlock, etc. responsible for this token // * @param token The token to generate tab-complete suggestions for // * @return a List of possible completions, or an empty List if none are available // */ // List<String> suggest(CommandSource source, String token); // }
import blue.lapis.common.command.token.InvalidTokenException; import blue.lapis.common.command.token.TokenParser; import com.google.common.collect.ImmutableList; import org.spongepowered.api.util.command.CommandSource; import java.util.List;
/* * LapisCommons * Copyright (c) 2014, Lapis <https://github.com/LapisBlue> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package blue.lapis.common.command.impl; /** * Converts tokens into Integers, much like the name would suggest. */ public class IntegerTokenParser implements TokenParser<Integer> { @Override public Integer parse(CommandSource source, String token) { try { return Integer.valueOf(token.trim()); } catch (NumberFormatException e) {
// Path: src/main/java/blue/lapis/common/command/token/InvalidTokenException.java // public class InvalidTokenException extends RuntimeException { // // private String token; // private Class<?> expectedType; // // public InvalidTokenException(String token, Class<?> expectedType) { // this.token = token; // this.expectedType = expectedType; // } // // /** // * @return the token that the TokenParser attempted to resolve // */ // public String getToken() { // return token; // } // // /** // * @return the Class of the object which the TokenParser creates // */ // public Class<?> getExpectedType() { // return expectedType; // } // } // // Path: src/main/java/blue/lapis/common/command/token/TokenParser.java // public interface TokenParser<T> { // // /** // * Parse the provided parser and return a typesafe object for it. // * // * @param source the Player, console, or command block which initiated this object resolution // * @param token the token to be resolved into an object of type {@code T} // * @return an object of type T which corresponds to the String entered // * // * @throws InvalidTokenException if the String does not appear to match any object // */ // T parse(CommandSource source, String token); // // /** // * Get tab-complete suggestions for this parser // * // * @param source The Player, CommandBlock, etc. responsible for this token // * @param token The token to generate tab-complete suggestions for // * @return a List of possible completions, or an empty List if none are available // */ // List<String> suggest(CommandSource source, String token); // } // Path: src/main/java/blue/lapis/common/command/impl/IntegerTokenParser.java import blue.lapis.common.command.token.InvalidTokenException; import blue.lapis.common.command.token.TokenParser; import com.google.common.collect.ImmutableList; import org.spongepowered.api.util.command.CommandSource; import java.util.List; /* * LapisCommons * Copyright (c) 2014, Lapis <https://github.com/LapisBlue> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package blue.lapis.common.command.impl; /** * Converts tokens into Integers, much like the name would suggest. */ public class IntegerTokenParser implements TokenParser<Integer> { @Override public Integer parse(CommandSource source, String token) { try { return Integer.valueOf(token.trim()); } catch (NumberFormatException e) {
throw new InvalidTokenException(token, Integer.class);
LapisBlue/Commons
src/main/java/blue/lapis/common/command/token/TokenParserRegistry.java
// Path: src/main/java/blue/lapis/common/command/impl/BooleanTokenParser.java // public class BooleanTokenParser implements TokenParser<Boolean> { // private static final ImmutableList<String> TRUE = ImmutableList.of("1", "true", "yes", "on"); // private static final ImmutableList<String> FALSE = ImmutableList.of("0", "false", "no", "off"); // // @Override // public Boolean parse(CommandSource source, String token) { // token = Parsing.toLowerCase(token.trim()); // if (TRUE.contains(token)) return true; // if (FALSE.contains(token)) return false; // throw new InvalidTokenException(token, Boolean.class); // } // // @Override // public List<String> suggest(CommandSource source, String token) { // token = token.trim(); // if (!token.isEmpty()) { // token = Parsing.toLowerCase(token); // // ArrayList<String> result = Lists.newArrayListWithCapacity(1); // // for (String bool : TRUE) // if (bool.startsWith(token)) { // result.add(bool); // } // for (String bool : FALSE) // if (bool.startsWith(token)) { // result.add(bool); // } // // if (!result.isEmpty()) // return ImmutableList.copyOf(result); // } // // return ImmutableList.of("true", "false"); // } // } // // Path: src/main/java/blue/lapis/common/command/impl/IntegerTokenParser.java // public class IntegerTokenParser implements TokenParser<Integer> { // @Override // public Integer parse(CommandSource source, String token) { // try { // return Integer.valueOf(token.trim()); // } catch (NumberFormatException e) { // throw new InvalidTokenException(token, Integer.class); // } // } // // @Override // public List<String> suggest(CommandSource source, String token) { // String match = token.trim(); // if (match.length() == 0) return ImmutableList.of("1"); // char ch = match.charAt(0); // // if (Character.isDigit(ch)) { // try { // //Parse it out into an integer and return it back. This trims off any garbage. // return ImmutableList.of(Integer.valueOf(match).toString()); // } catch (NumberFormatException e) { // //The first character was a digit. We checked. // //This code section is probably unreachable but I like to be prepared for the impossible. // return ImmutableList.of("" + ch); // } // } else { // //This String is invalid, so suggest a number // return ImmutableList.of("1"); // } // } // } // // Path: src/main/java/blue/lapis/common/command/impl/PlayerTokenParser.java // public class PlayerTokenParser implements TokenParser<Player> { // // @Override // public Player parse(final CommandSource source, final String token) { // Collection<Player> players = LapisCommonsPlugin.getGame().getServer().getOnlinePlayers(); // // // TODO: strip off leading "p:" ? // // // attempt resolving full names // for (Player p : players) { // if (p.getName().equalsIgnoreCase(token)) // return p; // } // // // attempt partial names // for (Player p : players) { // if (Parsing.startsWithIgnoreCase(p.getName(), token)) // return p; // } // // throw new InvalidTokenException(token, Player.class); // } // // @Override // public List<String> suggest(final CommandSource source, final String partial) { // List<String> results = Lists.newArrayList(); // Collection<Player> players = LapisCommonsPlugin.getGame().getServer().getOnlinePlayers(); // // for (Player p : players) { // if (Parsing.startsWithIgnoreCase(p.getName(), partial)) // results.add(p.getName()); // } // // return results; // } // // }
import java.util.concurrent.locks.ReentrantReadWriteLock; import javax.annotation.Nullable; import blue.lapis.common.command.impl.BooleanTokenParser; import blue.lapis.common.command.impl.IntegerTokenParser; import blue.lapis.common.command.impl.PlayerTokenParser; import com.google.common.collect.Maps; import org.spongepowered.api.entity.player.Player; import java.util.Map;
/* * LapisCommons * Copyright (c) 2014, Lapis <https://github.com/LapisBlue> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package blue.lapis.common.command.token; /** * Thread-safe registry/factory for {@link TokenParser}s, which resolve Strings into typesafe game objects. */ public class TokenParserRegistry { private static final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); private static final Map<Class<?>, TokenParser<?>> tokenParserMap = Maps.newHashMap(); static {
// Path: src/main/java/blue/lapis/common/command/impl/BooleanTokenParser.java // public class BooleanTokenParser implements TokenParser<Boolean> { // private static final ImmutableList<String> TRUE = ImmutableList.of("1", "true", "yes", "on"); // private static final ImmutableList<String> FALSE = ImmutableList.of("0", "false", "no", "off"); // // @Override // public Boolean parse(CommandSource source, String token) { // token = Parsing.toLowerCase(token.trim()); // if (TRUE.contains(token)) return true; // if (FALSE.contains(token)) return false; // throw new InvalidTokenException(token, Boolean.class); // } // // @Override // public List<String> suggest(CommandSource source, String token) { // token = token.trim(); // if (!token.isEmpty()) { // token = Parsing.toLowerCase(token); // // ArrayList<String> result = Lists.newArrayListWithCapacity(1); // // for (String bool : TRUE) // if (bool.startsWith(token)) { // result.add(bool); // } // for (String bool : FALSE) // if (bool.startsWith(token)) { // result.add(bool); // } // // if (!result.isEmpty()) // return ImmutableList.copyOf(result); // } // // return ImmutableList.of("true", "false"); // } // } // // Path: src/main/java/blue/lapis/common/command/impl/IntegerTokenParser.java // public class IntegerTokenParser implements TokenParser<Integer> { // @Override // public Integer parse(CommandSource source, String token) { // try { // return Integer.valueOf(token.trim()); // } catch (NumberFormatException e) { // throw new InvalidTokenException(token, Integer.class); // } // } // // @Override // public List<String> suggest(CommandSource source, String token) { // String match = token.trim(); // if (match.length() == 0) return ImmutableList.of("1"); // char ch = match.charAt(0); // // if (Character.isDigit(ch)) { // try { // //Parse it out into an integer and return it back. This trims off any garbage. // return ImmutableList.of(Integer.valueOf(match).toString()); // } catch (NumberFormatException e) { // //The first character was a digit. We checked. // //This code section is probably unreachable but I like to be prepared for the impossible. // return ImmutableList.of("" + ch); // } // } else { // //This String is invalid, so suggest a number // return ImmutableList.of("1"); // } // } // } // // Path: src/main/java/blue/lapis/common/command/impl/PlayerTokenParser.java // public class PlayerTokenParser implements TokenParser<Player> { // // @Override // public Player parse(final CommandSource source, final String token) { // Collection<Player> players = LapisCommonsPlugin.getGame().getServer().getOnlinePlayers(); // // // TODO: strip off leading "p:" ? // // // attempt resolving full names // for (Player p : players) { // if (p.getName().equalsIgnoreCase(token)) // return p; // } // // // attempt partial names // for (Player p : players) { // if (Parsing.startsWithIgnoreCase(p.getName(), token)) // return p; // } // // throw new InvalidTokenException(token, Player.class); // } // // @Override // public List<String> suggest(final CommandSource source, final String partial) { // List<String> results = Lists.newArrayList(); // Collection<Player> players = LapisCommonsPlugin.getGame().getServer().getOnlinePlayers(); // // for (Player p : players) { // if (Parsing.startsWithIgnoreCase(p.getName(), partial)) // results.add(p.getName()); // } // // return results; // } // // } // Path: src/main/java/blue/lapis/common/command/token/TokenParserRegistry.java import java.util.concurrent.locks.ReentrantReadWriteLock; import javax.annotation.Nullable; import blue.lapis.common.command.impl.BooleanTokenParser; import blue.lapis.common.command.impl.IntegerTokenParser; import blue.lapis.common.command.impl.PlayerTokenParser; import com.google.common.collect.Maps; import org.spongepowered.api.entity.player.Player; import java.util.Map; /* * LapisCommons * Copyright (c) 2014, Lapis <https://github.com/LapisBlue> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package blue.lapis.common.command.token; /** * Thread-safe registry/factory for {@link TokenParser}s, which resolve Strings into typesafe game objects. */ public class TokenParserRegistry { private static final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); private static final Map<Class<?>, TokenParser<?>> tokenParserMap = Maps.newHashMap(); static {
register(Player.class, new PlayerTokenParser());
LapisBlue/Commons
src/main/java/blue/lapis/common/command/token/TokenParserRegistry.java
// Path: src/main/java/blue/lapis/common/command/impl/BooleanTokenParser.java // public class BooleanTokenParser implements TokenParser<Boolean> { // private static final ImmutableList<String> TRUE = ImmutableList.of("1", "true", "yes", "on"); // private static final ImmutableList<String> FALSE = ImmutableList.of("0", "false", "no", "off"); // // @Override // public Boolean parse(CommandSource source, String token) { // token = Parsing.toLowerCase(token.trim()); // if (TRUE.contains(token)) return true; // if (FALSE.contains(token)) return false; // throw new InvalidTokenException(token, Boolean.class); // } // // @Override // public List<String> suggest(CommandSource source, String token) { // token = token.trim(); // if (!token.isEmpty()) { // token = Parsing.toLowerCase(token); // // ArrayList<String> result = Lists.newArrayListWithCapacity(1); // // for (String bool : TRUE) // if (bool.startsWith(token)) { // result.add(bool); // } // for (String bool : FALSE) // if (bool.startsWith(token)) { // result.add(bool); // } // // if (!result.isEmpty()) // return ImmutableList.copyOf(result); // } // // return ImmutableList.of("true", "false"); // } // } // // Path: src/main/java/blue/lapis/common/command/impl/IntegerTokenParser.java // public class IntegerTokenParser implements TokenParser<Integer> { // @Override // public Integer parse(CommandSource source, String token) { // try { // return Integer.valueOf(token.trim()); // } catch (NumberFormatException e) { // throw new InvalidTokenException(token, Integer.class); // } // } // // @Override // public List<String> suggest(CommandSource source, String token) { // String match = token.trim(); // if (match.length() == 0) return ImmutableList.of("1"); // char ch = match.charAt(0); // // if (Character.isDigit(ch)) { // try { // //Parse it out into an integer and return it back. This trims off any garbage. // return ImmutableList.of(Integer.valueOf(match).toString()); // } catch (NumberFormatException e) { // //The first character was a digit. We checked. // //This code section is probably unreachable but I like to be prepared for the impossible. // return ImmutableList.of("" + ch); // } // } else { // //This String is invalid, so suggest a number // return ImmutableList.of("1"); // } // } // } // // Path: src/main/java/blue/lapis/common/command/impl/PlayerTokenParser.java // public class PlayerTokenParser implements TokenParser<Player> { // // @Override // public Player parse(final CommandSource source, final String token) { // Collection<Player> players = LapisCommonsPlugin.getGame().getServer().getOnlinePlayers(); // // // TODO: strip off leading "p:" ? // // // attempt resolving full names // for (Player p : players) { // if (p.getName().equalsIgnoreCase(token)) // return p; // } // // // attempt partial names // for (Player p : players) { // if (Parsing.startsWithIgnoreCase(p.getName(), token)) // return p; // } // // throw new InvalidTokenException(token, Player.class); // } // // @Override // public List<String> suggest(final CommandSource source, final String partial) { // List<String> results = Lists.newArrayList(); // Collection<Player> players = LapisCommonsPlugin.getGame().getServer().getOnlinePlayers(); // // for (Player p : players) { // if (Parsing.startsWithIgnoreCase(p.getName(), partial)) // results.add(p.getName()); // } // // return results; // } // // }
import java.util.concurrent.locks.ReentrantReadWriteLock; import javax.annotation.Nullable; import blue.lapis.common.command.impl.BooleanTokenParser; import blue.lapis.common.command.impl.IntegerTokenParser; import blue.lapis.common.command.impl.PlayerTokenParser; import com.google.common.collect.Maps; import org.spongepowered.api.entity.player.Player; import java.util.Map;
/* * LapisCommons * Copyright (c) 2014, Lapis <https://github.com/LapisBlue> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package blue.lapis.common.command.token; /** * Thread-safe registry/factory for {@link TokenParser}s, which resolve Strings into typesafe game objects. */ public class TokenParserRegistry { private static final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); private static final Map<Class<?>, TokenParser<?>> tokenParserMap = Maps.newHashMap(); static { register(Player.class, new PlayerTokenParser());
// Path: src/main/java/blue/lapis/common/command/impl/BooleanTokenParser.java // public class BooleanTokenParser implements TokenParser<Boolean> { // private static final ImmutableList<String> TRUE = ImmutableList.of("1", "true", "yes", "on"); // private static final ImmutableList<String> FALSE = ImmutableList.of("0", "false", "no", "off"); // // @Override // public Boolean parse(CommandSource source, String token) { // token = Parsing.toLowerCase(token.trim()); // if (TRUE.contains(token)) return true; // if (FALSE.contains(token)) return false; // throw new InvalidTokenException(token, Boolean.class); // } // // @Override // public List<String> suggest(CommandSource source, String token) { // token = token.trim(); // if (!token.isEmpty()) { // token = Parsing.toLowerCase(token); // // ArrayList<String> result = Lists.newArrayListWithCapacity(1); // // for (String bool : TRUE) // if (bool.startsWith(token)) { // result.add(bool); // } // for (String bool : FALSE) // if (bool.startsWith(token)) { // result.add(bool); // } // // if (!result.isEmpty()) // return ImmutableList.copyOf(result); // } // // return ImmutableList.of("true", "false"); // } // } // // Path: src/main/java/blue/lapis/common/command/impl/IntegerTokenParser.java // public class IntegerTokenParser implements TokenParser<Integer> { // @Override // public Integer parse(CommandSource source, String token) { // try { // return Integer.valueOf(token.trim()); // } catch (NumberFormatException e) { // throw new InvalidTokenException(token, Integer.class); // } // } // // @Override // public List<String> suggest(CommandSource source, String token) { // String match = token.trim(); // if (match.length() == 0) return ImmutableList.of("1"); // char ch = match.charAt(0); // // if (Character.isDigit(ch)) { // try { // //Parse it out into an integer and return it back. This trims off any garbage. // return ImmutableList.of(Integer.valueOf(match).toString()); // } catch (NumberFormatException e) { // //The first character was a digit. We checked. // //This code section is probably unreachable but I like to be prepared for the impossible. // return ImmutableList.of("" + ch); // } // } else { // //This String is invalid, so suggest a number // return ImmutableList.of("1"); // } // } // } // // Path: src/main/java/blue/lapis/common/command/impl/PlayerTokenParser.java // public class PlayerTokenParser implements TokenParser<Player> { // // @Override // public Player parse(final CommandSource source, final String token) { // Collection<Player> players = LapisCommonsPlugin.getGame().getServer().getOnlinePlayers(); // // // TODO: strip off leading "p:" ? // // // attempt resolving full names // for (Player p : players) { // if (p.getName().equalsIgnoreCase(token)) // return p; // } // // // attempt partial names // for (Player p : players) { // if (Parsing.startsWithIgnoreCase(p.getName(), token)) // return p; // } // // throw new InvalidTokenException(token, Player.class); // } // // @Override // public List<String> suggest(final CommandSource source, final String partial) { // List<String> results = Lists.newArrayList(); // Collection<Player> players = LapisCommonsPlugin.getGame().getServer().getOnlinePlayers(); // // for (Player p : players) { // if (Parsing.startsWithIgnoreCase(p.getName(), partial)) // results.add(p.getName()); // } // // return results; // } // // } // Path: src/main/java/blue/lapis/common/command/token/TokenParserRegistry.java import java.util.concurrent.locks.ReentrantReadWriteLock; import javax.annotation.Nullable; import blue.lapis.common.command.impl.BooleanTokenParser; import blue.lapis.common.command.impl.IntegerTokenParser; import blue.lapis.common.command.impl.PlayerTokenParser; import com.google.common.collect.Maps; import org.spongepowered.api.entity.player.Player; import java.util.Map; /* * LapisCommons * Copyright (c) 2014, Lapis <https://github.com/LapisBlue> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package blue.lapis.common.command.token; /** * Thread-safe registry/factory for {@link TokenParser}s, which resolve Strings into typesafe game objects. */ public class TokenParserRegistry { private static final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); private static final Map<Class<?>, TokenParser<?>> tokenParserMap = Maps.newHashMap(); static { register(Player.class, new PlayerTokenParser());
register(Integer.class, new IntegerTokenParser());
LapisBlue/Commons
src/main/java/blue/lapis/common/command/token/TokenParserRegistry.java
// Path: src/main/java/blue/lapis/common/command/impl/BooleanTokenParser.java // public class BooleanTokenParser implements TokenParser<Boolean> { // private static final ImmutableList<String> TRUE = ImmutableList.of("1", "true", "yes", "on"); // private static final ImmutableList<String> FALSE = ImmutableList.of("0", "false", "no", "off"); // // @Override // public Boolean parse(CommandSource source, String token) { // token = Parsing.toLowerCase(token.trim()); // if (TRUE.contains(token)) return true; // if (FALSE.contains(token)) return false; // throw new InvalidTokenException(token, Boolean.class); // } // // @Override // public List<String> suggest(CommandSource source, String token) { // token = token.trim(); // if (!token.isEmpty()) { // token = Parsing.toLowerCase(token); // // ArrayList<String> result = Lists.newArrayListWithCapacity(1); // // for (String bool : TRUE) // if (bool.startsWith(token)) { // result.add(bool); // } // for (String bool : FALSE) // if (bool.startsWith(token)) { // result.add(bool); // } // // if (!result.isEmpty()) // return ImmutableList.copyOf(result); // } // // return ImmutableList.of("true", "false"); // } // } // // Path: src/main/java/blue/lapis/common/command/impl/IntegerTokenParser.java // public class IntegerTokenParser implements TokenParser<Integer> { // @Override // public Integer parse(CommandSource source, String token) { // try { // return Integer.valueOf(token.trim()); // } catch (NumberFormatException e) { // throw new InvalidTokenException(token, Integer.class); // } // } // // @Override // public List<String> suggest(CommandSource source, String token) { // String match = token.trim(); // if (match.length() == 0) return ImmutableList.of("1"); // char ch = match.charAt(0); // // if (Character.isDigit(ch)) { // try { // //Parse it out into an integer and return it back. This trims off any garbage. // return ImmutableList.of(Integer.valueOf(match).toString()); // } catch (NumberFormatException e) { // //The first character was a digit. We checked. // //This code section is probably unreachable but I like to be prepared for the impossible. // return ImmutableList.of("" + ch); // } // } else { // //This String is invalid, so suggest a number // return ImmutableList.of("1"); // } // } // } // // Path: src/main/java/blue/lapis/common/command/impl/PlayerTokenParser.java // public class PlayerTokenParser implements TokenParser<Player> { // // @Override // public Player parse(final CommandSource source, final String token) { // Collection<Player> players = LapisCommonsPlugin.getGame().getServer().getOnlinePlayers(); // // // TODO: strip off leading "p:" ? // // // attempt resolving full names // for (Player p : players) { // if (p.getName().equalsIgnoreCase(token)) // return p; // } // // // attempt partial names // for (Player p : players) { // if (Parsing.startsWithIgnoreCase(p.getName(), token)) // return p; // } // // throw new InvalidTokenException(token, Player.class); // } // // @Override // public List<String> suggest(final CommandSource source, final String partial) { // List<String> results = Lists.newArrayList(); // Collection<Player> players = LapisCommonsPlugin.getGame().getServer().getOnlinePlayers(); // // for (Player p : players) { // if (Parsing.startsWithIgnoreCase(p.getName(), partial)) // results.add(p.getName()); // } // // return results; // } // // }
import java.util.concurrent.locks.ReentrantReadWriteLock; import javax.annotation.Nullable; import blue.lapis.common.command.impl.BooleanTokenParser; import blue.lapis.common.command.impl.IntegerTokenParser; import blue.lapis.common.command.impl.PlayerTokenParser; import com.google.common.collect.Maps; import org.spongepowered.api.entity.player.Player; import java.util.Map;
/* * LapisCommons * Copyright (c) 2014, Lapis <https://github.com/LapisBlue> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package blue.lapis.common.command.token; /** * Thread-safe registry/factory for {@link TokenParser}s, which resolve Strings into typesafe game objects. */ public class TokenParserRegistry { private static final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); private static final Map<Class<?>, TokenParser<?>> tokenParserMap = Maps.newHashMap(); static { register(Player.class, new PlayerTokenParser()); register(Integer.class, new IntegerTokenParser());
// Path: src/main/java/blue/lapis/common/command/impl/BooleanTokenParser.java // public class BooleanTokenParser implements TokenParser<Boolean> { // private static final ImmutableList<String> TRUE = ImmutableList.of("1", "true", "yes", "on"); // private static final ImmutableList<String> FALSE = ImmutableList.of("0", "false", "no", "off"); // // @Override // public Boolean parse(CommandSource source, String token) { // token = Parsing.toLowerCase(token.trim()); // if (TRUE.contains(token)) return true; // if (FALSE.contains(token)) return false; // throw new InvalidTokenException(token, Boolean.class); // } // // @Override // public List<String> suggest(CommandSource source, String token) { // token = token.trim(); // if (!token.isEmpty()) { // token = Parsing.toLowerCase(token); // // ArrayList<String> result = Lists.newArrayListWithCapacity(1); // // for (String bool : TRUE) // if (bool.startsWith(token)) { // result.add(bool); // } // for (String bool : FALSE) // if (bool.startsWith(token)) { // result.add(bool); // } // // if (!result.isEmpty()) // return ImmutableList.copyOf(result); // } // // return ImmutableList.of("true", "false"); // } // } // // Path: src/main/java/blue/lapis/common/command/impl/IntegerTokenParser.java // public class IntegerTokenParser implements TokenParser<Integer> { // @Override // public Integer parse(CommandSource source, String token) { // try { // return Integer.valueOf(token.trim()); // } catch (NumberFormatException e) { // throw new InvalidTokenException(token, Integer.class); // } // } // // @Override // public List<String> suggest(CommandSource source, String token) { // String match = token.trim(); // if (match.length() == 0) return ImmutableList.of("1"); // char ch = match.charAt(0); // // if (Character.isDigit(ch)) { // try { // //Parse it out into an integer and return it back. This trims off any garbage. // return ImmutableList.of(Integer.valueOf(match).toString()); // } catch (NumberFormatException e) { // //The first character was a digit. We checked. // //This code section is probably unreachable but I like to be prepared for the impossible. // return ImmutableList.of("" + ch); // } // } else { // //This String is invalid, so suggest a number // return ImmutableList.of("1"); // } // } // } // // Path: src/main/java/blue/lapis/common/command/impl/PlayerTokenParser.java // public class PlayerTokenParser implements TokenParser<Player> { // // @Override // public Player parse(final CommandSource source, final String token) { // Collection<Player> players = LapisCommonsPlugin.getGame().getServer().getOnlinePlayers(); // // // TODO: strip off leading "p:" ? // // // attempt resolving full names // for (Player p : players) { // if (p.getName().equalsIgnoreCase(token)) // return p; // } // // // attempt partial names // for (Player p : players) { // if (Parsing.startsWithIgnoreCase(p.getName(), token)) // return p; // } // // throw new InvalidTokenException(token, Player.class); // } // // @Override // public List<String> suggest(final CommandSource source, final String partial) { // List<String> results = Lists.newArrayList(); // Collection<Player> players = LapisCommonsPlugin.getGame().getServer().getOnlinePlayers(); // // for (Player p : players) { // if (Parsing.startsWithIgnoreCase(p.getName(), partial)) // results.add(p.getName()); // } // // return results; // } // // } // Path: src/main/java/blue/lapis/common/command/token/TokenParserRegistry.java import java.util.concurrent.locks.ReentrantReadWriteLock; import javax.annotation.Nullable; import blue.lapis.common.command.impl.BooleanTokenParser; import blue.lapis.common.command.impl.IntegerTokenParser; import blue.lapis.common.command.impl.PlayerTokenParser; import com.google.common.collect.Maps; import org.spongepowered.api.entity.player.Player; import java.util.Map; /* * LapisCommons * Copyright (c) 2014, Lapis <https://github.com/LapisBlue> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package blue.lapis.common.command.token; /** * Thread-safe registry/factory for {@link TokenParser}s, which resolve Strings into typesafe game objects. */ public class TokenParserRegistry { private static final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); private static final Map<Class<?>, TokenParser<?>> tokenParserMap = Maps.newHashMap(); static { register(Player.class, new PlayerTokenParser()); register(Integer.class, new IntegerTokenParser());
register(Boolean.class, new BooleanTokenParser());
LapisBlue/Commons
src/main/java/blue/lapis/common/command/impl/BooleanTokenParser.java
// Path: src/main/java/blue/lapis/common/command/token/InvalidTokenException.java // public class InvalidTokenException extends RuntimeException { // // private String token; // private Class<?> expectedType; // // public InvalidTokenException(String token, Class<?> expectedType) { // this.token = token; // this.expectedType = expectedType; // } // // /** // * @return the token that the TokenParser attempted to resolve // */ // public String getToken() { // return token; // } // // /** // * @return the Class of the object which the TokenParser creates // */ // public Class<?> getExpectedType() { // return expectedType; // } // } // // Path: src/main/java/blue/lapis/common/command/token/TokenParser.java // public interface TokenParser<T> { // // /** // * Parse the provided parser and return a typesafe object for it. // * // * @param source the Player, console, or command block which initiated this object resolution // * @param token the token to be resolved into an object of type {@code T} // * @return an object of type T which corresponds to the String entered // * // * @throws InvalidTokenException if the String does not appear to match any object // */ // T parse(CommandSource source, String token); // // /** // * Get tab-complete suggestions for this parser // * // * @param source The Player, CommandBlock, etc. responsible for this token // * @param token The token to generate tab-complete suggestions for // * @return a List of possible completions, or an empty List if none are available // */ // List<String> suggest(CommandSource source, String token); // }
import java.util.List; import blue.lapis.common.command.token.InvalidTokenException; import blue.lapis.common.command.token.TokenParser; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import org.spongepowered.api.util.command.CommandSource; import java.util.ArrayList;
/* * LapisCommons * Copyright (c) 2014, Lapis <https://github.com/LapisBlue> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package blue.lapis.common.command.impl; public class BooleanTokenParser implements TokenParser<Boolean> { private static final ImmutableList<String> TRUE = ImmutableList.of("1", "true", "yes", "on"); private static final ImmutableList<String> FALSE = ImmutableList.of("0", "false", "no", "off"); @Override public Boolean parse(CommandSource source, String token) { token = Parsing.toLowerCase(token.trim()); if (TRUE.contains(token)) return true; if (FALSE.contains(token)) return false;
// Path: src/main/java/blue/lapis/common/command/token/InvalidTokenException.java // public class InvalidTokenException extends RuntimeException { // // private String token; // private Class<?> expectedType; // // public InvalidTokenException(String token, Class<?> expectedType) { // this.token = token; // this.expectedType = expectedType; // } // // /** // * @return the token that the TokenParser attempted to resolve // */ // public String getToken() { // return token; // } // // /** // * @return the Class of the object which the TokenParser creates // */ // public Class<?> getExpectedType() { // return expectedType; // } // } // // Path: src/main/java/blue/lapis/common/command/token/TokenParser.java // public interface TokenParser<T> { // // /** // * Parse the provided parser and return a typesafe object for it. // * // * @param source the Player, console, or command block which initiated this object resolution // * @param token the token to be resolved into an object of type {@code T} // * @return an object of type T which corresponds to the String entered // * // * @throws InvalidTokenException if the String does not appear to match any object // */ // T parse(CommandSource source, String token); // // /** // * Get tab-complete suggestions for this parser // * // * @param source The Player, CommandBlock, etc. responsible for this token // * @param token The token to generate tab-complete suggestions for // * @return a List of possible completions, or an empty List if none are available // */ // List<String> suggest(CommandSource source, String token); // } // Path: src/main/java/blue/lapis/common/command/impl/BooleanTokenParser.java import java.util.List; import blue.lapis.common.command.token.InvalidTokenException; import blue.lapis.common.command.token.TokenParser; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import org.spongepowered.api.util.command.CommandSource; import java.util.ArrayList; /* * LapisCommons * Copyright (c) 2014, Lapis <https://github.com/LapisBlue> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package blue.lapis.common.command.impl; public class BooleanTokenParser implements TokenParser<Boolean> { private static final ImmutableList<String> TRUE = ImmutableList.of("1", "true", "yes", "on"); private static final ImmutableList<String> FALSE = ImmutableList.of("0", "false", "no", "off"); @Override public Boolean parse(CommandSource source, String token) { token = Parsing.toLowerCase(token.trim()); if (TRUE.contains(token)) return true; if (FALSE.contains(token)) return false;
throw new InvalidTokenException(token, Boolean.class);
LapisBlue/Commons
src/main/java/blue/lapis/common/command/impl/StandardCommandRecognizer.java
// Path: src/main/java/blue/lapis/common/command/CommandRecognizer.java // public interface CommandRecognizer { // boolean recognize(final CommandSource source, // final String inputLine, // final LapisCommand command); // } // // Path: src/main/java/blue/lapis/common/command/LapisCommand.java // public class LapisCommand<S extends CommandSource> implements CommandHolder, CommandInvocationTarget<S> { // // private CommandRecognizer recognizer = StandardCommandRecognizer.INSTANCE; // private Tokenizer tokenizer = new StandardTokenizer(); // private List<LapisCommand> commands = Lists.newArrayList(); // private String name; // // public LapisCommand(final String name) { // this.name = name; // } // // @Override // public String getName() { // return name; // } // // @Override // public void register(String pluginID, CommandInvocationTarget command) { // //verify pluginID. It pays to be paranoid. // Optional<PluginContainer> plug = LapisCommonsPlugin.getGame().getPluginManager().getPlugin(pluginID); // if (plug.isPresent()) { // //TODO: Registrations // } else { // LapisCommonsPlugin.getLogger().warn( // "Attempted registration for a command for nonexistant plugin \"" + pluginID + "\"!"); // } // } // // @Override // @SuppressWarnings("unchecked") // public void fireCommand(final CommandSource source, final String inputline) { // //Tokenize inputline // ImmutableList<String> tokens = tokenizer.getTokens(inputline); // // //Construct a context // CommandContext context; // // context = new CommandContextImpl(source) // .withLine(inputline) // .withTokens(tokens); // } // // public void invoke(CommandContext<S> context) { // // } // // public void setRecognizer(final CommandRecognizer recognizer) { // this.recognizer = recognizer; // } // }
import blue.lapis.common.command.CommandRecognizer; import blue.lapis.common.command.LapisCommand; import org.spongepowered.api.util.command.CommandSource;
/* * LapisCommons * Copyright (c) 2014, Lapis <https://github.com/LapisBlue> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package blue.lapis.common.command.impl; /** * Straightforward implementation of CommandRecognizer */ public class StandardCommandRecognizer implements CommandRecognizer { public static final StandardCommandRecognizer INSTANCE = new StandardCommandRecognizer(); @Override public boolean recognize(final CommandSource source, final String inputLine,
// Path: src/main/java/blue/lapis/common/command/CommandRecognizer.java // public interface CommandRecognizer { // boolean recognize(final CommandSource source, // final String inputLine, // final LapisCommand command); // } // // Path: src/main/java/blue/lapis/common/command/LapisCommand.java // public class LapisCommand<S extends CommandSource> implements CommandHolder, CommandInvocationTarget<S> { // // private CommandRecognizer recognizer = StandardCommandRecognizer.INSTANCE; // private Tokenizer tokenizer = new StandardTokenizer(); // private List<LapisCommand> commands = Lists.newArrayList(); // private String name; // // public LapisCommand(final String name) { // this.name = name; // } // // @Override // public String getName() { // return name; // } // // @Override // public void register(String pluginID, CommandInvocationTarget command) { // //verify pluginID. It pays to be paranoid. // Optional<PluginContainer> plug = LapisCommonsPlugin.getGame().getPluginManager().getPlugin(pluginID); // if (plug.isPresent()) { // //TODO: Registrations // } else { // LapisCommonsPlugin.getLogger().warn( // "Attempted registration for a command for nonexistant plugin \"" + pluginID + "\"!"); // } // } // // @Override // @SuppressWarnings("unchecked") // public void fireCommand(final CommandSource source, final String inputline) { // //Tokenize inputline // ImmutableList<String> tokens = tokenizer.getTokens(inputline); // // //Construct a context // CommandContext context; // // context = new CommandContextImpl(source) // .withLine(inputline) // .withTokens(tokens); // } // // public void invoke(CommandContext<S> context) { // // } // // public void setRecognizer(final CommandRecognizer recognizer) { // this.recognizer = recognizer; // } // } // Path: src/main/java/blue/lapis/common/command/impl/StandardCommandRecognizer.java import blue.lapis.common.command.CommandRecognizer; import blue.lapis.common.command.LapisCommand; import org.spongepowered.api.util.command.CommandSource; /* * LapisCommons * Copyright (c) 2014, Lapis <https://github.com/LapisBlue> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package blue.lapis.common.command.impl; /** * Straightforward implementation of CommandRecognizer */ public class StandardCommandRecognizer implements CommandRecognizer { public static final StandardCommandRecognizer INSTANCE = new StandardCommandRecognizer(); @Override public boolean recognize(final CommandSource source, final String inputLine,
final LapisCommand command) {
LapisBlue/Commons
src/main/java/blue/lapis/common/economy/Economy.java
// Path: src/main/java/blue/lapis/common/economy/formatter/BalanceFormatterRegistry.java // public final class BalanceFormatterRegistry { // // private static final ReentrantReadWriteLock mutex = new ReentrantReadWriteLock(); // private static final Map<String, BalanceFormatter> registrations = Maps.newHashMap(); // // private BalanceFormatterRegistry() { // } // // /** // * Retrieves a valid CurrencyFormatter for the given prefix, even if one is not registered. // * // * @param prefix The account-prefix for the currency in question // * @return A CurrencyFormatter which can express the quantity and units of currency of this type // */ // public static BalanceFormatter get(String prefix) { // if (registrations.containsKey(prefix)) { // mutex.readLock().lock(); // BalanceFormatter result = registrations.get(prefix); // mutex.readLock().unlock(); // return result; // } else { // mutex.writeLock().lock(); // BalanceFormatter formatter = new SuffixBalanceFormatter(" " + prefix); // registrations.put(prefix, formatter); // mutex.writeLock().unlock(); // return formatter; // } // } // // /** // * Register a formatter for the specified currency account-prefix. // * // * @param prefix The account-prefix for the currency to register // * @param formatter A CurrencyFormatter which can turn amounts of this currency into a human-readable // * String // */ // public void register(String prefix, BalanceFormatter formatter) { // mutex.writeLock().lock(); // registrations.put(prefix, formatter); // mutex.writeLock().unlock(); // } // }
import blue.lapis.common.economy.formatter.BalanceFormatterRegistry; import java.util.List; import javax.annotation.Nullable;
/* * LapisCommons * Copyright (c) 2014, Lapis <https://github.com/LapisBlue> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package blue.lapis.common.economy; /** * Represents the economy as a whole. This class is currently under API scrutiny, * so details may change frequently. */ public final class Economy { private static Economy INSTANCE; /* private ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); private HashMap<Object, EconomyAccount> accounts = Maps.newHashMap(); */ private Economy() { // TODO } public static Economy getInstance() { if (INSTANCE == null) { INSTANCE = new Economy(); } return INSTANCE; } public String formatBalance(double amount, String prefix) {
// Path: src/main/java/blue/lapis/common/economy/formatter/BalanceFormatterRegistry.java // public final class BalanceFormatterRegistry { // // private static final ReentrantReadWriteLock mutex = new ReentrantReadWriteLock(); // private static final Map<String, BalanceFormatter> registrations = Maps.newHashMap(); // // private BalanceFormatterRegistry() { // } // // /** // * Retrieves a valid CurrencyFormatter for the given prefix, even if one is not registered. // * // * @param prefix The account-prefix for the currency in question // * @return A CurrencyFormatter which can express the quantity and units of currency of this type // */ // public static BalanceFormatter get(String prefix) { // if (registrations.containsKey(prefix)) { // mutex.readLock().lock(); // BalanceFormatter result = registrations.get(prefix); // mutex.readLock().unlock(); // return result; // } else { // mutex.writeLock().lock(); // BalanceFormatter formatter = new SuffixBalanceFormatter(" " + prefix); // registrations.put(prefix, formatter); // mutex.writeLock().unlock(); // return formatter; // } // } // // /** // * Register a formatter for the specified currency account-prefix. // * // * @param prefix The account-prefix for the currency to register // * @param formatter A CurrencyFormatter which can turn amounts of this currency into a human-readable // * String // */ // public void register(String prefix, BalanceFormatter formatter) { // mutex.writeLock().lock(); // registrations.put(prefix, formatter); // mutex.writeLock().unlock(); // } // } // Path: src/main/java/blue/lapis/common/economy/Economy.java import blue.lapis.common.economy.formatter.BalanceFormatterRegistry; import java.util.List; import javax.annotation.Nullable; /* * LapisCommons * Copyright (c) 2014, Lapis <https://github.com/LapisBlue> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package blue.lapis.common.economy; /** * Represents the economy as a whole. This class is currently under API scrutiny, * so details may change frequently. */ public final class Economy { private static Economy INSTANCE; /* private ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); private HashMap<Object, EconomyAccount> accounts = Maps.newHashMap(); */ private Economy() { // TODO } public static Economy getInstance() { if (INSTANCE == null) { INSTANCE = new Economy(); } return INSTANCE; } public String formatBalance(double amount, String prefix) {
return BalanceFormatterRegistry.get(prefix).format(amount);
LapisBlue/Commons
src/main/java/blue/lapis/common/command/impl/CommandContextImpl.java
// Path: src/main/java/blue/lapis/common/command/CommandContext.java // public interface CommandContext<S extends CommandSource> { // // /** // * @return the CommandSource which this command was issued from // */ // S getSource(); // // /** // * @return the entire line of text entered, except for the portion recognized as the command // */ // public String getLine(); // // /** // * @return the tokens in String format, as determined by the Tokenizer for this command // */ // public ImmutableList<String> getTokens(); // // /** // * Gets the specified typesafe argument. Throws {@link InvalidTokenException} if the argument is not of the // * expected type. // * // * @param clazz The expected class of the argument // * @param argNum The index of the argument. Note that this is the argument number, not the token number. // * @param <T> The expected class of the argument // * @return The argument if it exists, or null if the index is past the end of the list // */ // @Nullable // public <T> T get(Class<T> clazz, int argNum); // } // // Path: src/main/java/blue/lapis/common/command/token/InvalidTokenException.java // public class InvalidTokenException extends RuntimeException { // // private String token; // private Class<?> expectedType; // // public InvalidTokenException(String token, Class<?> expectedType) { // this.token = token; // this.expectedType = expectedType; // } // // /** // * @return the token that the TokenParser attempted to resolve // */ // public String getToken() { // return token; // } // // /** // * @return the Class of the object which the TokenParser creates // */ // public Class<?> getExpectedType() { // return expectedType; // } // } // // Path: src/main/java/blue/lapis/common/command/token/TokenParser.java // public interface TokenParser<T> { // // /** // * Parse the provided parser and return a typesafe object for it. // * // * @param source the Player, console, or command block which initiated this object resolution // * @param token the token to be resolved into an object of type {@code T} // * @return an object of type T which corresponds to the String entered // * // * @throws InvalidTokenException if the String does not appear to match any object // */ // T parse(CommandSource source, String token); // // /** // * Get tab-complete suggestions for this parser // * // * @param source The Player, CommandBlock, etc. responsible for this token // * @param token The token to generate tab-complete suggestions for // * @return a List of possible completions, or an empty List if none are available // */ // List<String> suggest(CommandSource source, String token); // } // // Path: src/main/java/blue/lapis/common/command/token/TokenParserRegistry.java // public class TokenParserRegistry { // // private static final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); // private static final Map<Class<?>, TokenParser<?>> tokenParserMap = Maps.newHashMap(); // // static { // register(Player.class, new PlayerTokenParser()); // register(Integer.class, new IntegerTokenParser()); // register(Boolean.class, new BooleanTokenParser()); // } // // // @SuppressWarnings("unchecked") // @Nullable // public static <T> TokenParser<T> get(Class<T> clazz) { // TokenParser<T> t; // lock.readLock().lock(); // { // t = (TokenParser<T>) tokenParserMap.get(clazz); // } // lock.readLock().unlock(); // return t; // } // // public static <T> void register(Class<T> clazz, TokenParser<T> parser) { // lock.writeLock().lock(); // { // tokenParserMap.put(clazz, parser); // } // lock.writeLock().unlock(); // } // }
import org.spongepowered.api.util.command.CommandSource; import java.util.List; import javax.annotation.Nullable; import blue.lapis.common.command.CommandContext; import blue.lapis.common.command.token.InvalidTokenException; import blue.lapis.common.command.token.TokenParser; import blue.lapis.common.command.token.TokenParserRegistry; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists;
@Override public S getSource() { return source; } @Override public String getLine() { return line; } @Override public ImmutableList<String> getTokens() { return tokens; } @Override @Nullable @SuppressWarnings("unchecked") public <T> T get(Class<T> clazz, int argNum) { Preconditions.checkState(args.size() == tokens.size()); //invariant Preconditions.checkArgument(argNum >= 0); //Requesting past the end of args is still valid if (args.size() <= argNum) return null; Object o = args.get(argNum); //Just-in-time resolve the argument if we need to if (o == null) { try {
// Path: src/main/java/blue/lapis/common/command/CommandContext.java // public interface CommandContext<S extends CommandSource> { // // /** // * @return the CommandSource which this command was issued from // */ // S getSource(); // // /** // * @return the entire line of text entered, except for the portion recognized as the command // */ // public String getLine(); // // /** // * @return the tokens in String format, as determined by the Tokenizer for this command // */ // public ImmutableList<String> getTokens(); // // /** // * Gets the specified typesafe argument. Throws {@link InvalidTokenException} if the argument is not of the // * expected type. // * // * @param clazz The expected class of the argument // * @param argNum The index of the argument. Note that this is the argument number, not the token number. // * @param <T> The expected class of the argument // * @return The argument if it exists, or null if the index is past the end of the list // */ // @Nullable // public <T> T get(Class<T> clazz, int argNum); // } // // Path: src/main/java/blue/lapis/common/command/token/InvalidTokenException.java // public class InvalidTokenException extends RuntimeException { // // private String token; // private Class<?> expectedType; // // public InvalidTokenException(String token, Class<?> expectedType) { // this.token = token; // this.expectedType = expectedType; // } // // /** // * @return the token that the TokenParser attempted to resolve // */ // public String getToken() { // return token; // } // // /** // * @return the Class of the object which the TokenParser creates // */ // public Class<?> getExpectedType() { // return expectedType; // } // } // // Path: src/main/java/blue/lapis/common/command/token/TokenParser.java // public interface TokenParser<T> { // // /** // * Parse the provided parser and return a typesafe object for it. // * // * @param source the Player, console, or command block which initiated this object resolution // * @param token the token to be resolved into an object of type {@code T} // * @return an object of type T which corresponds to the String entered // * // * @throws InvalidTokenException if the String does not appear to match any object // */ // T parse(CommandSource source, String token); // // /** // * Get tab-complete suggestions for this parser // * // * @param source The Player, CommandBlock, etc. responsible for this token // * @param token The token to generate tab-complete suggestions for // * @return a List of possible completions, or an empty List if none are available // */ // List<String> suggest(CommandSource source, String token); // } // // Path: src/main/java/blue/lapis/common/command/token/TokenParserRegistry.java // public class TokenParserRegistry { // // private static final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); // private static final Map<Class<?>, TokenParser<?>> tokenParserMap = Maps.newHashMap(); // // static { // register(Player.class, new PlayerTokenParser()); // register(Integer.class, new IntegerTokenParser()); // register(Boolean.class, new BooleanTokenParser()); // } // // // @SuppressWarnings("unchecked") // @Nullable // public static <T> TokenParser<T> get(Class<T> clazz) { // TokenParser<T> t; // lock.readLock().lock(); // { // t = (TokenParser<T>) tokenParserMap.get(clazz); // } // lock.readLock().unlock(); // return t; // } // // public static <T> void register(Class<T> clazz, TokenParser<T> parser) { // lock.writeLock().lock(); // { // tokenParserMap.put(clazz, parser); // } // lock.writeLock().unlock(); // } // } // Path: src/main/java/blue/lapis/common/command/impl/CommandContextImpl.java import org.spongepowered.api.util.command.CommandSource; import java.util.List; import javax.annotation.Nullable; import blue.lapis.common.command.CommandContext; import blue.lapis.common.command.token.InvalidTokenException; import blue.lapis.common.command.token.TokenParser; import blue.lapis.common.command.token.TokenParserRegistry; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; @Override public S getSource() { return source; } @Override public String getLine() { return line; } @Override public ImmutableList<String> getTokens() { return tokens; } @Override @Nullable @SuppressWarnings("unchecked") public <T> T get(Class<T> clazz, int argNum) { Preconditions.checkState(args.size() == tokens.size()); //invariant Preconditions.checkArgument(argNum >= 0); //Requesting past the end of args is still valid if (args.size() <= argNum) return null; Object o = args.get(argNum); //Just-in-time resolve the argument if we need to if (o == null) { try {
TokenParser<T> parser = TokenParserRegistry.get(clazz);
LapisBlue/Commons
src/main/java/blue/lapis/common/command/impl/CommandContextImpl.java
// Path: src/main/java/blue/lapis/common/command/CommandContext.java // public interface CommandContext<S extends CommandSource> { // // /** // * @return the CommandSource which this command was issued from // */ // S getSource(); // // /** // * @return the entire line of text entered, except for the portion recognized as the command // */ // public String getLine(); // // /** // * @return the tokens in String format, as determined by the Tokenizer for this command // */ // public ImmutableList<String> getTokens(); // // /** // * Gets the specified typesafe argument. Throws {@link InvalidTokenException} if the argument is not of the // * expected type. // * // * @param clazz The expected class of the argument // * @param argNum The index of the argument. Note that this is the argument number, not the token number. // * @param <T> The expected class of the argument // * @return The argument if it exists, or null if the index is past the end of the list // */ // @Nullable // public <T> T get(Class<T> clazz, int argNum); // } // // Path: src/main/java/blue/lapis/common/command/token/InvalidTokenException.java // public class InvalidTokenException extends RuntimeException { // // private String token; // private Class<?> expectedType; // // public InvalidTokenException(String token, Class<?> expectedType) { // this.token = token; // this.expectedType = expectedType; // } // // /** // * @return the token that the TokenParser attempted to resolve // */ // public String getToken() { // return token; // } // // /** // * @return the Class of the object which the TokenParser creates // */ // public Class<?> getExpectedType() { // return expectedType; // } // } // // Path: src/main/java/blue/lapis/common/command/token/TokenParser.java // public interface TokenParser<T> { // // /** // * Parse the provided parser and return a typesafe object for it. // * // * @param source the Player, console, or command block which initiated this object resolution // * @param token the token to be resolved into an object of type {@code T} // * @return an object of type T which corresponds to the String entered // * // * @throws InvalidTokenException if the String does not appear to match any object // */ // T parse(CommandSource source, String token); // // /** // * Get tab-complete suggestions for this parser // * // * @param source The Player, CommandBlock, etc. responsible for this token // * @param token The token to generate tab-complete suggestions for // * @return a List of possible completions, or an empty List if none are available // */ // List<String> suggest(CommandSource source, String token); // } // // Path: src/main/java/blue/lapis/common/command/token/TokenParserRegistry.java // public class TokenParserRegistry { // // private static final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); // private static final Map<Class<?>, TokenParser<?>> tokenParserMap = Maps.newHashMap(); // // static { // register(Player.class, new PlayerTokenParser()); // register(Integer.class, new IntegerTokenParser()); // register(Boolean.class, new BooleanTokenParser()); // } // // // @SuppressWarnings("unchecked") // @Nullable // public static <T> TokenParser<T> get(Class<T> clazz) { // TokenParser<T> t; // lock.readLock().lock(); // { // t = (TokenParser<T>) tokenParserMap.get(clazz); // } // lock.readLock().unlock(); // return t; // } // // public static <T> void register(Class<T> clazz, TokenParser<T> parser) { // lock.writeLock().lock(); // { // tokenParserMap.put(clazz, parser); // } // lock.writeLock().unlock(); // } // }
import org.spongepowered.api.util.command.CommandSource; import java.util.List; import javax.annotation.Nullable; import blue.lapis.common.command.CommandContext; import blue.lapis.common.command.token.InvalidTokenException; import blue.lapis.common.command.token.TokenParser; import blue.lapis.common.command.token.TokenParserRegistry; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists;
@Override public S getSource() { return source; } @Override public String getLine() { return line; } @Override public ImmutableList<String> getTokens() { return tokens; } @Override @Nullable @SuppressWarnings("unchecked") public <T> T get(Class<T> clazz, int argNum) { Preconditions.checkState(args.size() == tokens.size()); //invariant Preconditions.checkArgument(argNum >= 0); //Requesting past the end of args is still valid if (args.size() <= argNum) return null; Object o = args.get(argNum); //Just-in-time resolve the argument if we need to if (o == null) { try {
// Path: src/main/java/blue/lapis/common/command/CommandContext.java // public interface CommandContext<S extends CommandSource> { // // /** // * @return the CommandSource which this command was issued from // */ // S getSource(); // // /** // * @return the entire line of text entered, except for the portion recognized as the command // */ // public String getLine(); // // /** // * @return the tokens in String format, as determined by the Tokenizer for this command // */ // public ImmutableList<String> getTokens(); // // /** // * Gets the specified typesafe argument. Throws {@link InvalidTokenException} if the argument is not of the // * expected type. // * // * @param clazz The expected class of the argument // * @param argNum The index of the argument. Note that this is the argument number, not the token number. // * @param <T> The expected class of the argument // * @return The argument if it exists, or null if the index is past the end of the list // */ // @Nullable // public <T> T get(Class<T> clazz, int argNum); // } // // Path: src/main/java/blue/lapis/common/command/token/InvalidTokenException.java // public class InvalidTokenException extends RuntimeException { // // private String token; // private Class<?> expectedType; // // public InvalidTokenException(String token, Class<?> expectedType) { // this.token = token; // this.expectedType = expectedType; // } // // /** // * @return the token that the TokenParser attempted to resolve // */ // public String getToken() { // return token; // } // // /** // * @return the Class of the object which the TokenParser creates // */ // public Class<?> getExpectedType() { // return expectedType; // } // } // // Path: src/main/java/blue/lapis/common/command/token/TokenParser.java // public interface TokenParser<T> { // // /** // * Parse the provided parser and return a typesafe object for it. // * // * @param source the Player, console, or command block which initiated this object resolution // * @param token the token to be resolved into an object of type {@code T} // * @return an object of type T which corresponds to the String entered // * // * @throws InvalidTokenException if the String does not appear to match any object // */ // T parse(CommandSource source, String token); // // /** // * Get tab-complete suggestions for this parser // * // * @param source The Player, CommandBlock, etc. responsible for this token // * @param token The token to generate tab-complete suggestions for // * @return a List of possible completions, or an empty List if none are available // */ // List<String> suggest(CommandSource source, String token); // } // // Path: src/main/java/blue/lapis/common/command/token/TokenParserRegistry.java // public class TokenParserRegistry { // // private static final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); // private static final Map<Class<?>, TokenParser<?>> tokenParserMap = Maps.newHashMap(); // // static { // register(Player.class, new PlayerTokenParser()); // register(Integer.class, new IntegerTokenParser()); // register(Boolean.class, new BooleanTokenParser()); // } // // // @SuppressWarnings("unchecked") // @Nullable // public static <T> TokenParser<T> get(Class<T> clazz) { // TokenParser<T> t; // lock.readLock().lock(); // { // t = (TokenParser<T>) tokenParserMap.get(clazz); // } // lock.readLock().unlock(); // return t; // } // // public static <T> void register(Class<T> clazz, TokenParser<T> parser) { // lock.writeLock().lock(); // { // tokenParserMap.put(clazz, parser); // } // lock.writeLock().unlock(); // } // } // Path: src/main/java/blue/lapis/common/command/impl/CommandContextImpl.java import org.spongepowered.api.util.command.CommandSource; import java.util.List; import javax.annotation.Nullable; import blue.lapis.common.command.CommandContext; import blue.lapis.common.command.token.InvalidTokenException; import blue.lapis.common.command.token.TokenParser; import blue.lapis.common.command.token.TokenParserRegistry; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; @Override public S getSource() { return source; } @Override public String getLine() { return line; } @Override public ImmutableList<String> getTokens() { return tokens; } @Override @Nullable @SuppressWarnings("unchecked") public <T> T get(Class<T> clazz, int argNum) { Preconditions.checkState(args.size() == tokens.size()); //invariant Preconditions.checkArgument(argNum >= 0); //Requesting past the end of args is still valid if (args.size() <= argNum) return null; Object o = args.get(argNum); //Just-in-time resolve the argument if we need to if (o == null) { try {
TokenParser<T> parser = TokenParserRegistry.get(clazz);
LapisBlue/Commons
src/main/java/blue/lapis/common/command/impl/CommandContextImpl.java
// Path: src/main/java/blue/lapis/common/command/CommandContext.java // public interface CommandContext<S extends CommandSource> { // // /** // * @return the CommandSource which this command was issued from // */ // S getSource(); // // /** // * @return the entire line of text entered, except for the portion recognized as the command // */ // public String getLine(); // // /** // * @return the tokens in String format, as determined by the Tokenizer for this command // */ // public ImmutableList<String> getTokens(); // // /** // * Gets the specified typesafe argument. Throws {@link InvalidTokenException} if the argument is not of the // * expected type. // * // * @param clazz The expected class of the argument // * @param argNum The index of the argument. Note that this is the argument number, not the token number. // * @param <T> The expected class of the argument // * @return The argument if it exists, or null if the index is past the end of the list // */ // @Nullable // public <T> T get(Class<T> clazz, int argNum); // } // // Path: src/main/java/blue/lapis/common/command/token/InvalidTokenException.java // public class InvalidTokenException extends RuntimeException { // // private String token; // private Class<?> expectedType; // // public InvalidTokenException(String token, Class<?> expectedType) { // this.token = token; // this.expectedType = expectedType; // } // // /** // * @return the token that the TokenParser attempted to resolve // */ // public String getToken() { // return token; // } // // /** // * @return the Class of the object which the TokenParser creates // */ // public Class<?> getExpectedType() { // return expectedType; // } // } // // Path: src/main/java/blue/lapis/common/command/token/TokenParser.java // public interface TokenParser<T> { // // /** // * Parse the provided parser and return a typesafe object for it. // * // * @param source the Player, console, or command block which initiated this object resolution // * @param token the token to be resolved into an object of type {@code T} // * @return an object of type T which corresponds to the String entered // * // * @throws InvalidTokenException if the String does not appear to match any object // */ // T parse(CommandSource source, String token); // // /** // * Get tab-complete suggestions for this parser // * // * @param source The Player, CommandBlock, etc. responsible for this token // * @param token The token to generate tab-complete suggestions for // * @return a List of possible completions, or an empty List if none are available // */ // List<String> suggest(CommandSource source, String token); // } // // Path: src/main/java/blue/lapis/common/command/token/TokenParserRegistry.java // public class TokenParserRegistry { // // private static final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); // private static final Map<Class<?>, TokenParser<?>> tokenParserMap = Maps.newHashMap(); // // static { // register(Player.class, new PlayerTokenParser()); // register(Integer.class, new IntegerTokenParser()); // register(Boolean.class, new BooleanTokenParser()); // } // // // @SuppressWarnings("unchecked") // @Nullable // public static <T> TokenParser<T> get(Class<T> clazz) { // TokenParser<T> t; // lock.readLock().lock(); // { // t = (TokenParser<T>) tokenParserMap.get(clazz); // } // lock.readLock().unlock(); // return t; // } // // public static <T> void register(Class<T> clazz, TokenParser<T> parser) { // lock.writeLock().lock(); // { // tokenParserMap.put(clazz, parser); // } // lock.writeLock().unlock(); // } // }
import org.spongepowered.api.util.command.CommandSource; import java.util.List; import javax.annotation.Nullable; import blue.lapis.common.command.CommandContext; import blue.lapis.common.command.token.InvalidTokenException; import blue.lapis.common.command.token.TokenParser; import blue.lapis.common.command.token.TokenParserRegistry; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists;
@Nullable @SuppressWarnings("unchecked") public <T> T get(Class<T> clazz, int argNum) { Preconditions.checkState(args.size() == tokens.size()); //invariant Preconditions.checkArgument(argNum >= 0); //Requesting past the end of args is still valid if (args.size() <= argNum) return null; Object o = args.get(argNum); //Just-in-time resolve the argument if we need to if (o == null) { try { TokenParser<T> parser = TokenParserRegistry.get(clazz); String token = tokens.get(argNum); assert (token != null); //Also invariant. Tokenizer is not allowed to produce nulls. T t = parser.parse(source, token); args.set(argNum, t); return t; } catch (Throwable ignored) { } return null; } if (clazz.isAssignableFrom(o.getClass())) { return (T) args.get(argNum); } else { //convenience fallbacks if (clazz.equals(String.class)) return (T) args.get(argNum).toString();
// Path: src/main/java/blue/lapis/common/command/CommandContext.java // public interface CommandContext<S extends CommandSource> { // // /** // * @return the CommandSource which this command was issued from // */ // S getSource(); // // /** // * @return the entire line of text entered, except for the portion recognized as the command // */ // public String getLine(); // // /** // * @return the tokens in String format, as determined by the Tokenizer for this command // */ // public ImmutableList<String> getTokens(); // // /** // * Gets the specified typesafe argument. Throws {@link InvalidTokenException} if the argument is not of the // * expected type. // * // * @param clazz The expected class of the argument // * @param argNum The index of the argument. Note that this is the argument number, not the token number. // * @param <T> The expected class of the argument // * @return The argument if it exists, or null if the index is past the end of the list // */ // @Nullable // public <T> T get(Class<T> clazz, int argNum); // } // // Path: src/main/java/blue/lapis/common/command/token/InvalidTokenException.java // public class InvalidTokenException extends RuntimeException { // // private String token; // private Class<?> expectedType; // // public InvalidTokenException(String token, Class<?> expectedType) { // this.token = token; // this.expectedType = expectedType; // } // // /** // * @return the token that the TokenParser attempted to resolve // */ // public String getToken() { // return token; // } // // /** // * @return the Class of the object which the TokenParser creates // */ // public Class<?> getExpectedType() { // return expectedType; // } // } // // Path: src/main/java/blue/lapis/common/command/token/TokenParser.java // public interface TokenParser<T> { // // /** // * Parse the provided parser and return a typesafe object for it. // * // * @param source the Player, console, or command block which initiated this object resolution // * @param token the token to be resolved into an object of type {@code T} // * @return an object of type T which corresponds to the String entered // * // * @throws InvalidTokenException if the String does not appear to match any object // */ // T parse(CommandSource source, String token); // // /** // * Get tab-complete suggestions for this parser // * // * @param source The Player, CommandBlock, etc. responsible for this token // * @param token The token to generate tab-complete suggestions for // * @return a List of possible completions, or an empty List if none are available // */ // List<String> suggest(CommandSource source, String token); // } // // Path: src/main/java/blue/lapis/common/command/token/TokenParserRegistry.java // public class TokenParserRegistry { // // private static final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); // private static final Map<Class<?>, TokenParser<?>> tokenParserMap = Maps.newHashMap(); // // static { // register(Player.class, new PlayerTokenParser()); // register(Integer.class, new IntegerTokenParser()); // register(Boolean.class, new BooleanTokenParser()); // } // // // @SuppressWarnings("unchecked") // @Nullable // public static <T> TokenParser<T> get(Class<T> clazz) { // TokenParser<T> t; // lock.readLock().lock(); // { // t = (TokenParser<T>) tokenParserMap.get(clazz); // } // lock.readLock().unlock(); // return t; // } // // public static <T> void register(Class<T> clazz, TokenParser<T> parser) { // lock.writeLock().lock(); // { // tokenParserMap.put(clazz, parser); // } // lock.writeLock().unlock(); // } // } // Path: src/main/java/blue/lapis/common/command/impl/CommandContextImpl.java import org.spongepowered.api.util.command.CommandSource; import java.util.List; import javax.annotation.Nullable; import blue.lapis.common.command.CommandContext; import blue.lapis.common.command.token.InvalidTokenException; import blue.lapis.common.command.token.TokenParser; import blue.lapis.common.command.token.TokenParserRegistry; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; @Nullable @SuppressWarnings("unchecked") public <T> T get(Class<T> clazz, int argNum) { Preconditions.checkState(args.size() == tokens.size()); //invariant Preconditions.checkArgument(argNum >= 0); //Requesting past the end of args is still valid if (args.size() <= argNum) return null; Object o = args.get(argNum); //Just-in-time resolve the argument if we need to if (o == null) { try { TokenParser<T> parser = TokenParserRegistry.get(clazz); String token = tokens.get(argNum); assert (token != null); //Also invariant. Tokenizer is not allowed to produce nulls. T t = parser.parse(source, token); args.set(argNum, t); return t; } catch (Throwable ignored) { } return null; } if (clazz.isAssignableFrom(o.getClass())) { return (T) args.get(argNum); } else { //convenience fallbacks if (clazz.equals(String.class)) return (T) args.get(argNum).toString();
throw new InvalidTokenException(args.get(argNum).getClass().getSimpleName(), clazz);
LapisBlue/Commons
src/main/java/blue/lapis/common/economy/EconomyAccount.java
// Path: src/main/java/blue/lapis/common/economy/formatter/BalanceFormatter.java // public interface BalanceFormatter { // // /** // * Converts a machine-readable currency into a human-readable String which expresses its quantity and units // * // * @param amount The amount of currency to render // * @return A formatted String expressing the currency's quantity and units. // */ // String format(double amount); // }
import blue.lapis.common.economy.formatter.BalanceFormatter;
/* * LapisCommons * Copyright (c) 2014, Lapis <https://github.com/LapisBlue> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package blue.lapis.common.economy; /** * <p>Represents a single account of a single type of currency. Generally, accounts of a common currency have a * common prefix in their ID (such as "gold:savings" and "gold:inventory", or even "gold"). This interface does * not address who or what the holder is, or the number of holders, only the balance.</p> * * <p>This interface is available for custom economy systems to implement, either to allow credit, store * transaction logs, or create other unforseen behaviors.</p> */ public interface EconomyAccount { String getID(); /** * @return The current balance on this account */ double getBalance(); /** * @return a formatter which can display this account's currency */
// Path: src/main/java/blue/lapis/common/economy/formatter/BalanceFormatter.java // public interface BalanceFormatter { // // /** // * Converts a machine-readable currency into a human-readable String which expresses its quantity and units // * // * @param amount The amount of currency to render // * @return A formatted String expressing the currency's quantity and units. // */ // String format(double amount); // } // Path: src/main/java/blue/lapis/common/economy/EconomyAccount.java import blue.lapis.common.economy.formatter.BalanceFormatter; /* * LapisCommons * Copyright (c) 2014, Lapis <https://github.com/LapisBlue> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package blue.lapis.common.economy; /** * <p>Represents a single account of a single type of currency. Generally, accounts of a common currency have a * common prefix in their ID (such as "gold:savings" and "gold:inventory", or even "gold"). This interface does * not address who or what the holder is, or the number of holders, only the balance.</p> * * <p>This interface is available for custom economy systems to implement, either to allow credit, store * transaction logs, or create other unforseen behaviors.</p> */ public interface EconomyAccount { String getID(); /** * @return The current balance on this account */ double getBalance(); /** * @return a formatter which can display this account's currency */
BalanceFormatter getFormatter();
LapisBlue/Commons
src/test/java/blue/lapis/common/command/TokenizerTest.java
// Path: src/test/java/blue/lapis/common/CommonsTests.java // public final class CommonsTests { // // public static void mockPlugin() { // Game game = mock(Game.class); // PluginContainer container = mock(PluginContainer.class); // // LapisCommonsPlugin plugin = new LapisCommonsPlugin(game, container); // plugin.logger = LoggerFactory.getLogger(LapisCommonsPlugin.class); // // PreInitializationEvent init = mock(PreInitializationEvent.class); // plugin.initialize(init); // } // // public static void mockPlayers(String... players) { // List<Player> playerList = Lists.newArrayListWithCapacity(players.length); // for (String name : players) { // Player player = mock(Player.class); // when(player.getName()).thenReturn(name); // playerList.add(player); // } // // Game game = LapisCommonsPlugin.getGame(); // Server server = mock(Server.class); // when(server.getOnlinePlayers()).thenReturn(ImmutableList.copyOf(playerList)); // when(game.getServer()).thenReturn(server); // } // } // // Path: src/main/java/blue/lapis/common/command/impl/StandardTokenizer.java // public class StandardTokenizer implements Tokenizer { // // @Override // public ImmutableList<String> getTokens(final String s) { // List<String> result = Lists.newArrayList(); // // StringBuilder token = new StringBuilder(); // char delimiter = ' '; // for (int i = 0; i < s.length(); i++) { // char cur = s.charAt(i); // // if (delimiter != ' ') { // if (cur != delimiter) { // token.append(cur); // } else { // delimiter = ' '; // result.add(token.toString()); // token.setLength(0); // Reset the token // } // } else { // if (cur == '"') { // delimiter = '"'; // } else { // if (Character.isWhitespace(cur)) { // if (token.length() > 0) { // result.add(token.toString()); // token.setLength(0); // } // } else { // if (Character.isLetterOrDigit(cur)) { // token.append(cur); // } else { // //Commit both the existing token and this new symbol // if (token.length() > 0) { // result.add(token.toString()); // token.setLength(0); // } // result.add(String.valueOf(cur)); // } // } // } // } // } // if (token.length() > 0) result.add(token.toString()); // // return ImmutableList.copyOf(result); // } // }
import java.util.List; import static org.junit.Assert.assertEquals; import blue.lapis.common.CommonsTests; import blue.lapis.common.command.impl.StandardTokenizer; import com.google.common.collect.ImmutableList; import org.junit.Before; import org.junit.Test;
/* * LapisCommons * Copyright (c) 2014, Lapis <https://github.com/LapisBlue> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package blue.lapis.common.command; public class TokenizerTest { private final StandardTokenizer tokenizer = new StandardTokenizer(); @Before public void initTests() {
// Path: src/test/java/blue/lapis/common/CommonsTests.java // public final class CommonsTests { // // public static void mockPlugin() { // Game game = mock(Game.class); // PluginContainer container = mock(PluginContainer.class); // // LapisCommonsPlugin plugin = new LapisCommonsPlugin(game, container); // plugin.logger = LoggerFactory.getLogger(LapisCommonsPlugin.class); // // PreInitializationEvent init = mock(PreInitializationEvent.class); // plugin.initialize(init); // } // // public static void mockPlayers(String... players) { // List<Player> playerList = Lists.newArrayListWithCapacity(players.length); // for (String name : players) { // Player player = mock(Player.class); // when(player.getName()).thenReturn(name); // playerList.add(player); // } // // Game game = LapisCommonsPlugin.getGame(); // Server server = mock(Server.class); // when(server.getOnlinePlayers()).thenReturn(ImmutableList.copyOf(playerList)); // when(game.getServer()).thenReturn(server); // } // } // // Path: src/main/java/blue/lapis/common/command/impl/StandardTokenizer.java // public class StandardTokenizer implements Tokenizer { // // @Override // public ImmutableList<String> getTokens(final String s) { // List<String> result = Lists.newArrayList(); // // StringBuilder token = new StringBuilder(); // char delimiter = ' '; // for (int i = 0; i < s.length(); i++) { // char cur = s.charAt(i); // // if (delimiter != ' ') { // if (cur != delimiter) { // token.append(cur); // } else { // delimiter = ' '; // result.add(token.toString()); // token.setLength(0); // Reset the token // } // } else { // if (cur == '"') { // delimiter = '"'; // } else { // if (Character.isWhitespace(cur)) { // if (token.length() > 0) { // result.add(token.toString()); // token.setLength(0); // } // } else { // if (Character.isLetterOrDigit(cur)) { // token.append(cur); // } else { // //Commit both the existing token and this new symbol // if (token.length() > 0) { // result.add(token.toString()); // token.setLength(0); // } // result.add(String.valueOf(cur)); // } // } // } // } // } // if (token.length() > 0) result.add(token.toString()); // // return ImmutableList.copyOf(result); // } // } // Path: src/test/java/blue/lapis/common/command/TokenizerTest.java import java.util.List; import static org.junit.Assert.assertEquals; import blue.lapis.common.CommonsTests; import blue.lapis.common.command.impl.StandardTokenizer; import com.google.common.collect.ImmutableList; import org.junit.Before; import org.junit.Test; /* * LapisCommons * Copyright (c) 2014, Lapis <https://github.com/LapisBlue> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package blue.lapis.common.command; public class TokenizerTest { private final StandardTokenizer tokenizer = new StandardTokenizer(); @Before public void initTests() {
CommonsTests.mockPlugin();
LapisBlue/Commons
src/main/java/blue/lapis/common/economy/Transaction.java
// Path: src/main/java/blue/lapis/common/LapisCommonsPlugin.java // @Plugin(id = "lapis-commons", name = "LapisCommons", version = "1.0.0-SNAPSHOT") // public class LapisCommonsPlugin { // private static LapisCommonsPlugin instance; // // private final Game game; // private final PluginContainer container; // // @Inject // protected Logger logger; // // @Inject // public LapisCommonsPlugin(Game game, PluginContainer container) { // this.game = game; // this.container = container; // } // // /** // * Gets the instance of the LapisCommons plugin. // * // * @return The currently loaded plugin instance or null if the plugin is not loaded. // */ // public static LapisCommonsPlugin getInstance() { // return instance; // } // // /** // * Gets the instance the {@link Game} instance of the current server implementation. // * // * @return The game instance of the server implementation or null if the plugin is not loaded. // */ // public static Game getGame() { // return getInstance().game; // } // // /** // * Gets the plugin logger of the LapisCommons plugin. // * // * @return The plugin logger for this plugin or null if the plugin is not loaded // */ // public static Logger getLogger() { // return getInstance().logger; // } // // @Subscribe // public void initialize(PreInitializationEvent event) { // instance = this; // } // } // // Path: src/main/java/blue/lapis/common/economy/event/TransactionEvent.java // public interface TransactionEvent extends EconomyEvent, Cancellable { // // Transaction getTransaction(); // } // // Path: src/main/java/blue/lapis/common/economy/event/TransactionException.java // public class TransactionException extends Exception { // // private final Transaction transaction; // // public TransactionException(final Transaction t) { // this.transaction = t; // } // // public TransactionException(final String message, final Transaction t) { // super(message); // this.transaction = t; // } // // public Transaction getTransaction() { // return transaction; // } // } // // Path: src/main/java/blue/lapis/common/economy/event/impl/TransactionEventImpl.java // public class TransactionEventImpl extends EconomyEventImpl implements TransactionEvent { // private final Transaction transaction; // private boolean cancelled = false; // // public TransactionEventImpl(Transaction transaction) { // super(Preconditions.checkNotNull(transaction, "transaction").getAccount()); // this.transaction = transaction; // } // // @Override // public Transaction getTransaction() { // return transaction; // } // // @Override // public void setCancelled(boolean cancelled) { // this.cancelled = cancelled; // } // // @Override // public boolean isCancelled() { // return cancelled; // } // }
import javax.annotation.Nullable; import blue.lapis.common.LapisCommonsPlugin; import blue.lapis.common.economy.event.TransactionEvent; import blue.lapis.common.economy.event.TransactionException; import blue.lapis.common.economy.event.impl.TransactionEventImpl; import com.google.common.base.Preconditions; import com.google.common.util.concurrent.FutureCallback;
* @param amount The amount to reduce the account balance by * @return This object for further modification */ public Transaction subtract(double amount) { delta -= amount; return this; } /** * Express a constant balance that the account should be changed to * * @param amount The amount that the new account balance should be * @return This object for further modification */ public Transaction setAbsolute(double amount) { balance = amount; return this; } /** * Causes a TransactionEvent to be fired for this Transaction, and if the event is not cancelled, hands * this Transaction to the EconomyAccount for final processing. This final processing may complete * asynchronously, and may fail, so it's important to register a FutureCallback to handle the result of the * transaction. * * @param onResult A callback for when the transaction is complete */ public void commit(FutureCallback<Transaction> onResult) { validateState(Status.INCOMPLETE); status = Status.IN_TRANSIT;
// Path: src/main/java/blue/lapis/common/LapisCommonsPlugin.java // @Plugin(id = "lapis-commons", name = "LapisCommons", version = "1.0.0-SNAPSHOT") // public class LapisCommonsPlugin { // private static LapisCommonsPlugin instance; // // private final Game game; // private final PluginContainer container; // // @Inject // protected Logger logger; // // @Inject // public LapisCommonsPlugin(Game game, PluginContainer container) { // this.game = game; // this.container = container; // } // // /** // * Gets the instance of the LapisCommons plugin. // * // * @return The currently loaded plugin instance or null if the plugin is not loaded. // */ // public static LapisCommonsPlugin getInstance() { // return instance; // } // // /** // * Gets the instance the {@link Game} instance of the current server implementation. // * // * @return The game instance of the server implementation or null if the plugin is not loaded. // */ // public static Game getGame() { // return getInstance().game; // } // // /** // * Gets the plugin logger of the LapisCommons plugin. // * // * @return The plugin logger for this plugin or null if the plugin is not loaded // */ // public static Logger getLogger() { // return getInstance().logger; // } // // @Subscribe // public void initialize(PreInitializationEvent event) { // instance = this; // } // } // // Path: src/main/java/blue/lapis/common/economy/event/TransactionEvent.java // public interface TransactionEvent extends EconomyEvent, Cancellable { // // Transaction getTransaction(); // } // // Path: src/main/java/blue/lapis/common/economy/event/TransactionException.java // public class TransactionException extends Exception { // // private final Transaction transaction; // // public TransactionException(final Transaction t) { // this.transaction = t; // } // // public TransactionException(final String message, final Transaction t) { // super(message); // this.transaction = t; // } // // public Transaction getTransaction() { // return transaction; // } // } // // Path: src/main/java/blue/lapis/common/economy/event/impl/TransactionEventImpl.java // public class TransactionEventImpl extends EconomyEventImpl implements TransactionEvent { // private final Transaction transaction; // private boolean cancelled = false; // // public TransactionEventImpl(Transaction transaction) { // super(Preconditions.checkNotNull(transaction, "transaction").getAccount()); // this.transaction = transaction; // } // // @Override // public Transaction getTransaction() { // return transaction; // } // // @Override // public void setCancelled(boolean cancelled) { // this.cancelled = cancelled; // } // // @Override // public boolean isCancelled() { // return cancelled; // } // } // Path: src/main/java/blue/lapis/common/economy/Transaction.java import javax.annotation.Nullable; import blue.lapis.common.LapisCommonsPlugin; import blue.lapis.common.economy.event.TransactionEvent; import blue.lapis.common.economy.event.TransactionException; import blue.lapis.common.economy.event.impl.TransactionEventImpl; import com.google.common.base.Preconditions; import com.google.common.util.concurrent.FutureCallback; * @param amount The amount to reduce the account balance by * @return This object for further modification */ public Transaction subtract(double amount) { delta -= amount; return this; } /** * Express a constant balance that the account should be changed to * * @param amount The amount that the new account balance should be * @return This object for further modification */ public Transaction setAbsolute(double amount) { balance = amount; return this; } /** * Causes a TransactionEvent to be fired for this Transaction, and if the event is not cancelled, hands * this Transaction to the EconomyAccount for final processing. This final processing may complete * asynchronously, and may fail, so it's important to register a FutureCallback to handle the result of the * transaction. * * @param onResult A callback for when the transaction is complete */ public void commit(FutureCallback<Transaction> onResult) { validateState(Status.INCOMPLETE); status = Status.IN_TRANSIT;
TransactionEvent event = new TransactionEventImpl(this);
LapisBlue/Commons
src/main/java/blue/lapis/common/economy/Transaction.java
// Path: src/main/java/blue/lapis/common/LapisCommonsPlugin.java // @Plugin(id = "lapis-commons", name = "LapisCommons", version = "1.0.0-SNAPSHOT") // public class LapisCommonsPlugin { // private static LapisCommonsPlugin instance; // // private final Game game; // private final PluginContainer container; // // @Inject // protected Logger logger; // // @Inject // public LapisCommonsPlugin(Game game, PluginContainer container) { // this.game = game; // this.container = container; // } // // /** // * Gets the instance of the LapisCommons plugin. // * // * @return The currently loaded plugin instance or null if the plugin is not loaded. // */ // public static LapisCommonsPlugin getInstance() { // return instance; // } // // /** // * Gets the instance the {@link Game} instance of the current server implementation. // * // * @return The game instance of the server implementation or null if the plugin is not loaded. // */ // public static Game getGame() { // return getInstance().game; // } // // /** // * Gets the plugin logger of the LapisCommons plugin. // * // * @return The plugin logger for this plugin or null if the plugin is not loaded // */ // public static Logger getLogger() { // return getInstance().logger; // } // // @Subscribe // public void initialize(PreInitializationEvent event) { // instance = this; // } // } // // Path: src/main/java/blue/lapis/common/economy/event/TransactionEvent.java // public interface TransactionEvent extends EconomyEvent, Cancellable { // // Transaction getTransaction(); // } // // Path: src/main/java/blue/lapis/common/economy/event/TransactionException.java // public class TransactionException extends Exception { // // private final Transaction transaction; // // public TransactionException(final Transaction t) { // this.transaction = t; // } // // public TransactionException(final String message, final Transaction t) { // super(message); // this.transaction = t; // } // // public Transaction getTransaction() { // return transaction; // } // } // // Path: src/main/java/blue/lapis/common/economy/event/impl/TransactionEventImpl.java // public class TransactionEventImpl extends EconomyEventImpl implements TransactionEvent { // private final Transaction transaction; // private boolean cancelled = false; // // public TransactionEventImpl(Transaction transaction) { // super(Preconditions.checkNotNull(transaction, "transaction").getAccount()); // this.transaction = transaction; // } // // @Override // public Transaction getTransaction() { // return transaction; // } // // @Override // public void setCancelled(boolean cancelled) { // this.cancelled = cancelled; // } // // @Override // public boolean isCancelled() { // return cancelled; // } // }
import javax.annotation.Nullable; import blue.lapis.common.LapisCommonsPlugin; import blue.lapis.common.economy.event.TransactionEvent; import blue.lapis.common.economy.event.TransactionException; import blue.lapis.common.economy.event.impl.TransactionEventImpl; import com.google.common.base.Preconditions; import com.google.common.util.concurrent.FutureCallback;
* @param amount The amount to reduce the account balance by * @return This object for further modification */ public Transaction subtract(double amount) { delta -= amount; return this; } /** * Express a constant balance that the account should be changed to * * @param amount The amount that the new account balance should be * @return This object for further modification */ public Transaction setAbsolute(double amount) { balance = amount; return this; } /** * Causes a TransactionEvent to be fired for this Transaction, and if the event is not cancelled, hands * this Transaction to the EconomyAccount for final processing. This final processing may complete * asynchronously, and may fail, so it's important to register a FutureCallback to handle the result of the * transaction. * * @param onResult A callback for when the transaction is complete */ public void commit(FutureCallback<Transaction> onResult) { validateState(Status.INCOMPLETE); status = Status.IN_TRANSIT;
// Path: src/main/java/blue/lapis/common/LapisCommonsPlugin.java // @Plugin(id = "lapis-commons", name = "LapisCommons", version = "1.0.0-SNAPSHOT") // public class LapisCommonsPlugin { // private static LapisCommonsPlugin instance; // // private final Game game; // private final PluginContainer container; // // @Inject // protected Logger logger; // // @Inject // public LapisCommonsPlugin(Game game, PluginContainer container) { // this.game = game; // this.container = container; // } // // /** // * Gets the instance of the LapisCommons plugin. // * // * @return The currently loaded plugin instance or null if the plugin is not loaded. // */ // public static LapisCommonsPlugin getInstance() { // return instance; // } // // /** // * Gets the instance the {@link Game} instance of the current server implementation. // * // * @return The game instance of the server implementation or null if the plugin is not loaded. // */ // public static Game getGame() { // return getInstance().game; // } // // /** // * Gets the plugin logger of the LapisCommons plugin. // * // * @return The plugin logger for this plugin or null if the plugin is not loaded // */ // public static Logger getLogger() { // return getInstance().logger; // } // // @Subscribe // public void initialize(PreInitializationEvent event) { // instance = this; // } // } // // Path: src/main/java/blue/lapis/common/economy/event/TransactionEvent.java // public interface TransactionEvent extends EconomyEvent, Cancellable { // // Transaction getTransaction(); // } // // Path: src/main/java/blue/lapis/common/economy/event/TransactionException.java // public class TransactionException extends Exception { // // private final Transaction transaction; // // public TransactionException(final Transaction t) { // this.transaction = t; // } // // public TransactionException(final String message, final Transaction t) { // super(message); // this.transaction = t; // } // // public Transaction getTransaction() { // return transaction; // } // } // // Path: src/main/java/blue/lapis/common/economy/event/impl/TransactionEventImpl.java // public class TransactionEventImpl extends EconomyEventImpl implements TransactionEvent { // private final Transaction transaction; // private boolean cancelled = false; // // public TransactionEventImpl(Transaction transaction) { // super(Preconditions.checkNotNull(transaction, "transaction").getAccount()); // this.transaction = transaction; // } // // @Override // public Transaction getTransaction() { // return transaction; // } // // @Override // public void setCancelled(boolean cancelled) { // this.cancelled = cancelled; // } // // @Override // public boolean isCancelled() { // return cancelled; // } // } // Path: src/main/java/blue/lapis/common/economy/Transaction.java import javax.annotation.Nullable; import blue.lapis.common.LapisCommonsPlugin; import blue.lapis.common.economy.event.TransactionEvent; import blue.lapis.common.economy.event.TransactionException; import blue.lapis.common.economy.event.impl.TransactionEventImpl; import com.google.common.base.Preconditions; import com.google.common.util.concurrent.FutureCallback; * @param amount The amount to reduce the account balance by * @return This object for further modification */ public Transaction subtract(double amount) { delta -= amount; return this; } /** * Express a constant balance that the account should be changed to * * @param amount The amount that the new account balance should be * @return This object for further modification */ public Transaction setAbsolute(double amount) { balance = amount; return this; } /** * Causes a TransactionEvent to be fired for this Transaction, and if the event is not cancelled, hands * this Transaction to the EconomyAccount for final processing. This final processing may complete * asynchronously, and may fail, so it's important to register a FutureCallback to handle the result of the * transaction. * * @param onResult A callback for when the transaction is complete */ public void commit(FutureCallback<Transaction> onResult) { validateState(Status.INCOMPLETE); status = Status.IN_TRANSIT;
TransactionEvent event = new TransactionEventImpl(this);
LapisBlue/Commons
src/main/java/blue/lapis/common/economy/Transaction.java
// Path: src/main/java/blue/lapis/common/LapisCommonsPlugin.java // @Plugin(id = "lapis-commons", name = "LapisCommons", version = "1.0.0-SNAPSHOT") // public class LapisCommonsPlugin { // private static LapisCommonsPlugin instance; // // private final Game game; // private final PluginContainer container; // // @Inject // protected Logger logger; // // @Inject // public LapisCommonsPlugin(Game game, PluginContainer container) { // this.game = game; // this.container = container; // } // // /** // * Gets the instance of the LapisCommons plugin. // * // * @return The currently loaded plugin instance or null if the plugin is not loaded. // */ // public static LapisCommonsPlugin getInstance() { // return instance; // } // // /** // * Gets the instance the {@link Game} instance of the current server implementation. // * // * @return The game instance of the server implementation or null if the plugin is not loaded. // */ // public static Game getGame() { // return getInstance().game; // } // // /** // * Gets the plugin logger of the LapisCommons plugin. // * // * @return The plugin logger for this plugin or null if the plugin is not loaded // */ // public static Logger getLogger() { // return getInstance().logger; // } // // @Subscribe // public void initialize(PreInitializationEvent event) { // instance = this; // } // } // // Path: src/main/java/blue/lapis/common/economy/event/TransactionEvent.java // public interface TransactionEvent extends EconomyEvent, Cancellable { // // Transaction getTransaction(); // } // // Path: src/main/java/blue/lapis/common/economy/event/TransactionException.java // public class TransactionException extends Exception { // // private final Transaction transaction; // // public TransactionException(final Transaction t) { // this.transaction = t; // } // // public TransactionException(final String message, final Transaction t) { // super(message); // this.transaction = t; // } // // public Transaction getTransaction() { // return transaction; // } // } // // Path: src/main/java/blue/lapis/common/economy/event/impl/TransactionEventImpl.java // public class TransactionEventImpl extends EconomyEventImpl implements TransactionEvent { // private final Transaction transaction; // private boolean cancelled = false; // // public TransactionEventImpl(Transaction transaction) { // super(Preconditions.checkNotNull(transaction, "transaction").getAccount()); // this.transaction = transaction; // } // // @Override // public Transaction getTransaction() { // return transaction; // } // // @Override // public void setCancelled(boolean cancelled) { // this.cancelled = cancelled; // } // // @Override // public boolean isCancelled() { // return cancelled; // } // }
import javax.annotation.Nullable; import blue.lapis.common.LapisCommonsPlugin; import blue.lapis.common.economy.event.TransactionEvent; import blue.lapis.common.economy.event.TransactionException; import blue.lapis.common.economy.event.impl.TransactionEventImpl; import com.google.common.base.Preconditions; import com.google.common.util.concurrent.FutureCallback;
* @return This object for further modification */ public Transaction subtract(double amount) { delta -= amount; return this; } /** * Express a constant balance that the account should be changed to * * @param amount The amount that the new account balance should be * @return This object for further modification */ public Transaction setAbsolute(double amount) { balance = amount; return this; } /** * Causes a TransactionEvent to be fired for this Transaction, and if the event is not cancelled, hands * this Transaction to the EconomyAccount for final processing. This final processing may complete * asynchronously, and may fail, so it's important to register a FutureCallback to handle the result of the * transaction. * * @param onResult A callback for when the transaction is complete */ public void commit(FutureCallback<Transaction> onResult) { validateState(Status.INCOMPLETE); status = Status.IN_TRANSIT; TransactionEvent event = new TransactionEventImpl(this);
// Path: src/main/java/blue/lapis/common/LapisCommonsPlugin.java // @Plugin(id = "lapis-commons", name = "LapisCommons", version = "1.0.0-SNAPSHOT") // public class LapisCommonsPlugin { // private static LapisCommonsPlugin instance; // // private final Game game; // private final PluginContainer container; // // @Inject // protected Logger logger; // // @Inject // public LapisCommonsPlugin(Game game, PluginContainer container) { // this.game = game; // this.container = container; // } // // /** // * Gets the instance of the LapisCommons plugin. // * // * @return The currently loaded plugin instance or null if the plugin is not loaded. // */ // public static LapisCommonsPlugin getInstance() { // return instance; // } // // /** // * Gets the instance the {@link Game} instance of the current server implementation. // * // * @return The game instance of the server implementation or null if the plugin is not loaded. // */ // public static Game getGame() { // return getInstance().game; // } // // /** // * Gets the plugin logger of the LapisCommons plugin. // * // * @return The plugin logger for this plugin or null if the plugin is not loaded // */ // public static Logger getLogger() { // return getInstance().logger; // } // // @Subscribe // public void initialize(PreInitializationEvent event) { // instance = this; // } // } // // Path: src/main/java/blue/lapis/common/economy/event/TransactionEvent.java // public interface TransactionEvent extends EconomyEvent, Cancellable { // // Transaction getTransaction(); // } // // Path: src/main/java/blue/lapis/common/economy/event/TransactionException.java // public class TransactionException extends Exception { // // private final Transaction transaction; // // public TransactionException(final Transaction t) { // this.transaction = t; // } // // public TransactionException(final String message, final Transaction t) { // super(message); // this.transaction = t; // } // // public Transaction getTransaction() { // return transaction; // } // } // // Path: src/main/java/blue/lapis/common/economy/event/impl/TransactionEventImpl.java // public class TransactionEventImpl extends EconomyEventImpl implements TransactionEvent { // private final Transaction transaction; // private boolean cancelled = false; // // public TransactionEventImpl(Transaction transaction) { // super(Preconditions.checkNotNull(transaction, "transaction").getAccount()); // this.transaction = transaction; // } // // @Override // public Transaction getTransaction() { // return transaction; // } // // @Override // public void setCancelled(boolean cancelled) { // this.cancelled = cancelled; // } // // @Override // public boolean isCancelled() { // return cancelled; // } // } // Path: src/main/java/blue/lapis/common/economy/Transaction.java import javax.annotation.Nullable; import blue.lapis.common.LapisCommonsPlugin; import blue.lapis.common.economy.event.TransactionEvent; import blue.lapis.common.economy.event.TransactionException; import blue.lapis.common.economy.event.impl.TransactionEventImpl; import com.google.common.base.Preconditions; import com.google.common.util.concurrent.FutureCallback; * @return This object for further modification */ public Transaction subtract(double amount) { delta -= amount; return this; } /** * Express a constant balance that the account should be changed to * * @param amount The amount that the new account balance should be * @return This object for further modification */ public Transaction setAbsolute(double amount) { balance = amount; return this; } /** * Causes a TransactionEvent to be fired for this Transaction, and if the event is not cancelled, hands * this Transaction to the EconomyAccount for final processing. This final processing may complete * asynchronously, and may fail, so it's important to register a FutureCallback to handle the result of the * transaction. * * @param onResult A callback for when the transaction is complete */ public void commit(FutureCallback<Transaction> onResult) { validateState(Status.INCOMPLETE); status = Status.IN_TRANSIT; TransactionEvent event = new TransactionEventImpl(this);
LapisCommonsPlugin.getGame().getEventManager().post(event);
LapisBlue/Commons
src/main/java/blue/lapis/common/economy/Transaction.java
// Path: src/main/java/blue/lapis/common/LapisCommonsPlugin.java // @Plugin(id = "lapis-commons", name = "LapisCommons", version = "1.0.0-SNAPSHOT") // public class LapisCommonsPlugin { // private static LapisCommonsPlugin instance; // // private final Game game; // private final PluginContainer container; // // @Inject // protected Logger logger; // // @Inject // public LapisCommonsPlugin(Game game, PluginContainer container) { // this.game = game; // this.container = container; // } // // /** // * Gets the instance of the LapisCommons plugin. // * // * @return The currently loaded plugin instance or null if the plugin is not loaded. // */ // public static LapisCommonsPlugin getInstance() { // return instance; // } // // /** // * Gets the instance the {@link Game} instance of the current server implementation. // * // * @return The game instance of the server implementation or null if the plugin is not loaded. // */ // public static Game getGame() { // return getInstance().game; // } // // /** // * Gets the plugin logger of the LapisCommons plugin. // * // * @return The plugin logger for this plugin or null if the plugin is not loaded // */ // public static Logger getLogger() { // return getInstance().logger; // } // // @Subscribe // public void initialize(PreInitializationEvent event) { // instance = this; // } // } // // Path: src/main/java/blue/lapis/common/economy/event/TransactionEvent.java // public interface TransactionEvent extends EconomyEvent, Cancellable { // // Transaction getTransaction(); // } // // Path: src/main/java/blue/lapis/common/economy/event/TransactionException.java // public class TransactionException extends Exception { // // private final Transaction transaction; // // public TransactionException(final Transaction t) { // this.transaction = t; // } // // public TransactionException(final String message, final Transaction t) { // super(message); // this.transaction = t; // } // // public Transaction getTransaction() { // return transaction; // } // } // // Path: src/main/java/blue/lapis/common/economy/event/impl/TransactionEventImpl.java // public class TransactionEventImpl extends EconomyEventImpl implements TransactionEvent { // private final Transaction transaction; // private boolean cancelled = false; // // public TransactionEventImpl(Transaction transaction) { // super(Preconditions.checkNotNull(transaction, "transaction").getAccount()); // this.transaction = transaction; // } // // @Override // public Transaction getTransaction() { // return transaction; // } // // @Override // public void setCancelled(boolean cancelled) { // this.cancelled = cancelled; // } // // @Override // public boolean isCancelled() { // return cancelled; // } // }
import javax.annotation.Nullable; import blue.lapis.common.LapisCommonsPlugin; import blue.lapis.common.economy.event.TransactionEvent; import blue.lapis.common.economy.event.TransactionException; import blue.lapis.common.economy.event.impl.TransactionEventImpl; import com.google.common.base.Preconditions; import com.google.common.util.concurrent.FutureCallback;
return this; } /** * Express a constant balance that the account should be changed to * * @param amount The amount that the new account balance should be * @return This object for further modification */ public Transaction setAbsolute(double amount) { balance = amount; return this; } /** * Causes a TransactionEvent to be fired for this Transaction, and if the event is not cancelled, hands * this Transaction to the EconomyAccount for final processing. This final processing may complete * asynchronously, and may fail, so it's important to register a FutureCallback to handle the result of the * transaction. * * @param onResult A callback for when the transaction is complete */ public void commit(FutureCallback<Transaction> onResult) { validateState(Status.INCOMPLETE); status = Status.IN_TRANSIT; TransactionEvent event = new TransactionEventImpl(this); LapisCommonsPlugin.getGame().getEventManager().post(event); if (event.isCancelled()) { status = Status.CANCELLED;
// Path: src/main/java/blue/lapis/common/LapisCommonsPlugin.java // @Plugin(id = "lapis-commons", name = "LapisCommons", version = "1.0.0-SNAPSHOT") // public class LapisCommonsPlugin { // private static LapisCommonsPlugin instance; // // private final Game game; // private final PluginContainer container; // // @Inject // protected Logger logger; // // @Inject // public LapisCommonsPlugin(Game game, PluginContainer container) { // this.game = game; // this.container = container; // } // // /** // * Gets the instance of the LapisCommons plugin. // * // * @return The currently loaded plugin instance or null if the plugin is not loaded. // */ // public static LapisCommonsPlugin getInstance() { // return instance; // } // // /** // * Gets the instance the {@link Game} instance of the current server implementation. // * // * @return The game instance of the server implementation or null if the plugin is not loaded. // */ // public static Game getGame() { // return getInstance().game; // } // // /** // * Gets the plugin logger of the LapisCommons plugin. // * // * @return The plugin logger for this plugin or null if the plugin is not loaded // */ // public static Logger getLogger() { // return getInstance().logger; // } // // @Subscribe // public void initialize(PreInitializationEvent event) { // instance = this; // } // } // // Path: src/main/java/blue/lapis/common/economy/event/TransactionEvent.java // public interface TransactionEvent extends EconomyEvent, Cancellable { // // Transaction getTransaction(); // } // // Path: src/main/java/blue/lapis/common/economy/event/TransactionException.java // public class TransactionException extends Exception { // // private final Transaction transaction; // // public TransactionException(final Transaction t) { // this.transaction = t; // } // // public TransactionException(final String message, final Transaction t) { // super(message); // this.transaction = t; // } // // public Transaction getTransaction() { // return transaction; // } // } // // Path: src/main/java/blue/lapis/common/economy/event/impl/TransactionEventImpl.java // public class TransactionEventImpl extends EconomyEventImpl implements TransactionEvent { // private final Transaction transaction; // private boolean cancelled = false; // // public TransactionEventImpl(Transaction transaction) { // super(Preconditions.checkNotNull(transaction, "transaction").getAccount()); // this.transaction = transaction; // } // // @Override // public Transaction getTransaction() { // return transaction; // } // // @Override // public void setCancelled(boolean cancelled) { // this.cancelled = cancelled; // } // // @Override // public boolean isCancelled() { // return cancelled; // } // } // Path: src/main/java/blue/lapis/common/economy/Transaction.java import javax.annotation.Nullable; import blue.lapis.common.LapisCommonsPlugin; import blue.lapis.common.economy.event.TransactionEvent; import blue.lapis.common.economy.event.TransactionException; import blue.lapis.common.economy.event.impl.TransactionEventImpl; import com.google.common.base.Preconditions; import com.google.common.util.concurrent.FutureCallback; return this; } /** * Express a constant balance that the account should be changed to * * @param amount The amount that the new account balance should be * @return This object for further modification */ public Transaction setAbsolute(double amount) { balance = amount; return this; } /** * Causes a TransactionEvent to be fired for this Transaction, and if the event is not cancelled, hands * this Transaction to the EconomyAccount for final processing. This final processing may complete * asynchronously, and may fail, so it's important to register a FutureCallback to handle the result of the * transaction. * * @param onResult A callback for when the transaction is complete */ public void commit(FutureCallback<Transaction> onResult) { validateState(Status.INCOMPLETE); status = Status.IN_TRANSIT; TransactionEvent event = new TransactionEventImpl(this); LapisCommonsPlugin.getGame().getEventManager().post(event); if (event.isCancelled()) { status = Status.CANCELLED;
onResult.onFailure(new TransactionException("Transaction cancelled.", this));
LapisBlue/Commons
src/test/java/blue/lapis/common/command/TokenParserTest.java
// Path: src/test/java/blue/lapis/common/CommonsTests.java // public final class CommonsTests { // // public static void mockPlugin() { // Game game = mock(Game.class); // PluginContainer container = mock(PluginContainer.class); // // LapisCommonsPlugin plugin = new LapisCommonsPlugin(game, container); // plugin.logger = LoggerFactory.getLogger(LapisCommonsPlugin.class); // // PreInitializationEvent init = mock(PreInitializationEvent.class); // plugin.initialize(init); // } // // public static void mockPlayers(String... players) { // List<Player> playerList = Lists.newArrayListWithCapacity(players.length); // for (String name : players) { // Player player = mock(Player.class); // when(player.getName()).thenReturn(name); // playerList.add(player); // } // // Game game = LapisCommonsPlugin.getGame(); // Server server = mock(Server.class); // when(server.getOnlinePlayers()).thenReturn(ImmutableList.copyOf(playerList)); // when(game.getServer()).thenReturn(server); // } // } // // Path: src/main/java/blue/lapis/common/command/token/InvalidTokenException.java // public class InvalidTokenException extends RuntimeException { // // private String token; // private Class<?> expectedType; // // public InvalidTokenException(String token, Class<?> expectedType) { // this.token = token; // this.expectedType = expectedType; // } // // /** // * @return the token that the TokenParser attempted to resolve // */ // public String getToken() { // return token; // } // // /** // * @return the Class of the object which the TokenParser creates // */ // public Class<?> getExpectedType() { // return expectedType; // } // } // // Path: src/main/java/blue/lapis/common/command/token/TokenParser.java // public interface TokenParser<T> { // // /** // * Parse the provided parser and return a typesafe object for it. // * // * @param source the Player, console, or command block which initiated this object resolution // * @param token the token to be resolved into an object of type {@code T} // * @return an object of type T which corresponds to the String entered // * // * @throws InvalidTokenException if the String does not appear to match any object // */ // T parse(CommandSource source, String token); // // /** // * Get tab-complete suggestions for this parser // * // * @param source The Player, CommandBlock, etc. responsible for this token // * @param token The token to generate tab-complete suggestions for // * @return a List of possible completions, or an empty List if none are available // */ // List<String> suggest(CommandSource source, String token); // } // // Path: src/main/java/blue/lapis/common/command/token/TokenParserRegistry.java // public class TokenParserRegistry { // // private static final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); // private static final Map<Class<?>, TokenParser<?>> tokenParserMap = Maps.newHashMap(); // // static { // register(Player.class, new PlayerTokenParser()); // register(Integer.class, new IntegerTokenParser()); // register(Boolean.class, new BooleanTokenParser()); // } // // // @SuppressWarnings("unchecked") // @Nullable // public static <T> TokenParser<T> get(Class<T> clazz) { // TokenParser<T> t; // lock.readLock().lock(); // { // t = (TokenParser<T>) tokenParserMap.get(clazz); // } // lock.readLock().unlock(); // return t; // } // // public static <T> void register(Class<T> clazz, TokenParser<T> parser) { // lock.writeLock().lock(); // { // tokenParserMap.put(clazz, parser); // } // lock.writeLock().unlock(); // } // }
import blue.lapis.common.command.token.TokenParser; import blue.lapis.common.command.token.TokenParserRegistry; import junit.framework.AssertionFailedError; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.spongepowered.api.entity.player.Player; import org.spongepowered.api.util.command.CommandSource; import javax.annotation.Nonnull; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; import blue.lapis.common.CommonsTests; import blue.lapis.common.command.token.InvalidTokenException;
/* * LapisCommons * Copyright (c) 2014, Lapis <https://github.com/LapisBlue> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package blue.lapis.common.command; public class TokenParserTest { private final CommandSource source = mock(CommandSource.class); @Before public void initTests() {
// Path: src/test/java/blue/lapis/common/CommonsTests.java // public final class CommonsTests { // // public static void mockPlugin() { // Game game = mock(Game.class); // PluginContainer container = mock(PluginContainer.class); // // LapisCommonsPlugin plugin = new LapisCommonsPlugin(game, container); // plugin.logger = LoggerFactory.getLogger(LapisCommonsPlugin.class); // // PreInitializationEvent init = mock(PreInitializationEvent.class); // plugin.initialize(init); // } // // public static void mockPlayers(String... players) { // List<Player> playerList = Lists.newArrayListWithCapacity(players.length); // for (String name : players) { // Player player = mock(Player.class); // when(player.getName()).thenReturn(name); // playerList.add(player); // } // // Game game = LapisCommonsPlugin.getGame(); // Server server = mock(Server.class); // when(server.getOnlinePlayers()).thenReturn(ImmutableList.copyOf(playerList)); // when(game.getServer()).thenReturn(server); // } // } // // Path: src/main/java/blue/lapis/common/command/token/InvalidTokenException.java // public class InvalidTokenException extends RuntimeException { // // private String token; // private Class<?> expectedType; // // public InvalidTokenException(String token, Class<?> expectedType) { // this.token = token; // this.expectedType = expectedType; // } // // /** // * @return the token that the TokenParser attempted to resolve // */ // public String getToken() { // return token; // } // // /** // * @return the Class of the object which the TokenParser creates // */ // public Class<?> getExpectedType() { // return expectedType; // } // } // // Path: src/main/java/blue/lapis/common/command/token/TokenParser.java // public interface TokenParser<T> { // // /** // * Parse the provided parser and return a typesafe object for it. // * // * @param source the Player, console, or command block which initiated this object resolution // * @param token the token to be resolved into an object of type {@code T} // * @return an object of type T which corresponds to the String entered // * // * @throws InvalidTokenException if the String does not appear to match any object // */ // T parse(CommandSource source, String token); // // /** // * Get tab-complete suggestions for this parser // * // * @param source The Player, CommandBlock, etc. responsible for this token // * @param token The token to generate tab-complete suggestions for // * @return a List of possible completions, or an empty List if none are available // */ // List<String> suggest(CommandSource source, String token); // } // // Path: src/main/java/blue/lapis/common/command/token/TokenParserRegistry.java // public class TokenParserRegistry { // // private static final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); // private static final Map<Class<?>, TokenParser<?>> tokenParserMap = Maps.newHashMap(); // // static { // register(Player.class, new PlayerTokenParser()); // register(Integer.class, new IntegerTokenParser()); // register(Boolean.class, new BooleanTokenParser()); // } // // // @SuppressWarnings("unchecked") // @Nullable // public static <T> TokenParser<T> get(Class<T> clazz) { // TokenParser<T> t; // lock.readLock().lock(); // { // t = (TokenParser<T>) tokenParserMap.get(clazz); // } // lock.readLock().unlock(); // return t; // } // // public static <T> void register(Class<T> clazz, TokenParser<T> parser) { // lock.writeLock().lock(); // { // tokenParserMap.put(clazz, parser); // } // lock.writeLock().unlock(); // } // } // Path: src/test/java/blue/lapis/common/command/TokenParserTest.java import blue.lapis.common.command.token.TokenParser; import blue.lapis.common.command.token.TokenParserRegistry; import junit.framework.AssertionFailedError; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.spongepowered.api.entity.player.Player; import org.spongepowered.api.util.command.CommandSource; import javax.annotation.Nonnull; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; import blue.lapis.common.CommonsTests; import blue.lapis.common.command.token.InvalidTokenException; /* * LapisCommons * Copyright (c) 2014, Lapis <https://github.com/LapisBlue> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package blue.lapis.common.command; public class TokenParserTest { private final CommandSource source = mock(CommandSource.class); @Before public void initTests() {
CommonsTests.mockPlugin();
LapisBlue/Commons
src/test/java/blue/lapis/common/command/TokenParserTest.java
// Path: src/test/java/blue/lapis/common/CommonsTests.java // public final class CommonsTests { // // public static void mockPlugin() { // Game game = mock(Game.class); // PluginContainer container = mock(PluginContainer.class); // // LapisCommonsPlugin plugin = new LapisCommonsPlugin(game, container); // plugin.logger = LoggerFactory.getLogger(LapisCommonsPlugin.class); // // PreInitializationEvent init = mock(PreInitializationEvent.class); // plugin.initialize(init); // } // // public static void mockPlayers(String... players) { // List<Player> playerList = Lists.newArrayListWithCapacity(players.length); // for (String name : players) { // Player player = mock(Player.class); // when(player.getName()).thenReturn(name); // playerList.add(player); // } // // Game game = LapisCommonsPlugin.getGame(); // Server server = mock(Server.class); // when(server.getOnlinePlayers()).thenReturn(ImmutableList.copyOf(playerList)); // when(game.getServer()).thenReturn(server); // } // } // // Path: src/main/java/blue/lapis/common/command/token/InvalidTokenException.java // public class InvalidTokenException extends RuntimeException { // // private String token; // private Class<?> expectedType; // // public InvalidTokenException(String token, Class<?> expectedType) { // this.token = token; // this.expectedType = expectedType; // } // // /** // * @return the token that the TokenParser attempted to resolve // */ // public String getToken() { // return token; // } // // /** // * @return the Class of the object which the TokenParser creates // */ // public Class<?> getExpectedType() { // return expectedType; // } // } // // Path: src/main/java/blue/lapis/common/command/token/TokenParser.java // public interface TokenParser<T> { // // /** // * Parse the provided parser and return a typesafe object for it. // * // * @param source the Player, console, or command block which initiated this object resolution // * @param token the token to be resolved into an object of type {@code T} // * @return an object of type T which corresponds to the String entered // * // * @throws InvalidTokenException if the String does not appear to match any object // */ // T parse(CommandSource source, String token); // // /** // * Get tab-complete suggestions for this parser // * // * @param source The Player, CommandBlock, etc. responsible for this token // * @param token The token to generate tab-complete suggestions for // * @return a List of possible completions, or an empty List if none are available // */ // List<String> suggest(CommandSource source, String token); // } // // Path: src/main/java/blue/lapis/common/command/token/TokenParserRegistry.java // public class TokenParserRegistry { // // private static final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); // private static final Map<Class<?>, TokenParser<?>> tokenParserMap = Maps.newHashMap(); // // static { // register(Player.class, new PlayerTokenParser()); // register(Integer.class, new IntegerTokenParser()); // register(Boolean.class, new BooleanTokenParser()); // } // // // @SuppressWarnings("unchecked") // @Nullable // public static <T> TokenParser<T> get(Class<T> clazz) { // TokenParser<T> t; // lock.readLock().lock(); // { // t = (TokenParser<T>) tokenParserMap.get(clazz); // } // lock.readLock().unlock(); // return t; // } // // public static <T> void register(Class<T> clazz, TokenParser<T> parser) { // lock.writeLock().lock(); // { // tokenParserMap.put(clazz, parser); // } // lock.writeLock().unlock(); // } // }
import blue.lapis.common.command.token.TokenParser; import blue.lapis.common.command.token.TokenParserRegistry; import junit.framework.AssertionFailedError; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.spongepowered.api.entity.player.Player; import org.spongepowered.api.util.command.CommandSource; import javax.annotation.Nonnull; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; import blue.lapis.common.CommonsTests; import blue.lapis.common.command.token.InvalidTokenException;
/* * LapisCommons * Copyright (c) 2014, Lapis <https://github.com/LapisBlue> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package blue.lapis.common.command; public class TokenParserTest { private final CommandSource source = mock(CommandSource.class); @Before public void initTests() { CommonsTests.mockPlugin(); } @Test public void resolvePlayers() { CommonsTests.mockPlayers("Foo", "Bar", "Baz", "Lorem", "Ipsum", "Marco", "Polo", "Foot");
// Path: src/test/java/blue/lapis/common/CommonsTests.java // public final class CommonsTests { // // public static void mockPlugin() { // Game game = mock(Game.class); // PluginContainer container = mock(PluginContainer.class); // // LapisCommonsPlugin plugin = new LapisCommonsPlugin(game, container); // plugin.logger = LoggerFactory.getLogger(LapisCommonsPlugin.class); // // PreInitializationEvent init = mock(PreInitializationEvent.class); // plugin.initialize(init); // } // // public static void mockPlayers(String... players) { // List<Player> playerList = Lists.newArrayListWithCapacity(players.length); // for (String name : players) { // Player player = mock(Player.class); // when(player.getName()).thenReturn(name); // playerList.add(player); // } // // Game game = LapisCommonsPlugin.getGame(); // Server server = mock(Server.class); // when(server.getOnlinePlayers()).thenReturn(ImmutableList.copyOf(playerList)); // when(game.getServer()).thenReturn(server); // } // } // // Path: src/main/java/blue/lapis/common/command/token/InvalidTokenException.java // public class InvalidTokenException extends RuntimeException { // // private String token; // private Class<?> expectedType; // // public InvalidTokenException(String token, Class<?> expectedType) { // this.token = token; // this.expectedType = expectedType; // } // // /** // * @return the token that the TokenParser attempted to resolve // */ // public String getToken() { // return token; // } // // /** // * @return the Class of the object which the TokenParser creates // */ // public Class<?> getExpectedType() { // return expectedType; // } // } // // Path: src/main/java/blue/lapis/common/command/token/TokenParser.java // public interface TokenParser<T> { // // /** // * Parse the provided parser and return a typesafe object for it. // * // * @param source the Player, console, or command block which initiated this object resolution // * @param token the token to be resolved into an object of type {@code T} // * @return an object of type T which corresponds to the String entered // * // * @throws InvalidTokenException if the String does not appear to match any object // */ // T parse(CommandSource source, String token); // // /** // * Get tab-complete suggestions for this parser // * // * @param source The Player, CommandBlock, etc. responsible for this token // * @param token The token to generate tab-complete suggestions for // * @return a List of possible completions, or an empty List if none are available // */ // List<String> suggest(CommandSource source, String token); // } // // Path: src/main/java/blue/lapis/common/command/token/TokenParserRegistry.java // public class TokenParserRegistry { // // private static final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); // private static final Map<Class<?>, TokenParser<?>> tokenParserMap = Maps.newHashMap(); // // static { // register(Player.class, new PlayerTokenParser()); // register(Integer.class, new IntegerTokenParser()); // register(Boolean.class, new BooleanTokenParser()); // } // // // @SuppressWarnings("unchecked") // @Nullable // public static <T> TokenParser<T> get(Class<T> clazz) { // TokenParser<T> t; // lock.readLock().lock(); // { // t = (TokenParser<T>) tokenParserMap.get(clazz); // } // lock.readLock().unlock(); // return t; // } // // public static <T> void register(Class<T> clazz, TokenParser<T> parser) { // lock.writeLock().lock(); // { // tokenParserMap.put(clazz, parser); // } // lock.writeLock().unlock(); // } // } // Path: src/test/java/blue/lapis/common/command/TokenParserTest.java import blue.lapis.common.command.token.TokenParser; import blue.lapis.common.command.token.TokenParserRegistry; import junit.framework.AssertionFailedError; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.spongepowered.api.entity.player.Player; import org.spongepowered.api.util.command.CommandSource; import javax.annotation.Nonnull; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; import blue.lapis.common.CommonsTests; import blue.lapis.common.command.token.InvalidTokenException; /* * LapisCommons * Copyright (c) 2014, Lapis <https://github.com/LapisBlue> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package blue.lapis.common.command; public class TokenParserTest { private final CommandSource source = mock(CommandSource.class); @Before public void initTests() { CommonsTests.mockPlugin(); } @Test public void resolvePlayers() { CommonsTests.mockPlayers("Foo", "Bar", "Baz", "Lorem", "Ipsum", "Marco", "Polo", "Foot");
TokenParser<Player> parser = getParser(Player.class);
LapisBlue/Commons
src/test/java/blue/lapis/common/command/TokenParserTest.java
// Path: src/test/java/blue/lapis/common/CommonsTests.java // public final class CommonsTests { // // public static void mockPlugin() { // Game game = mock(Game.class); // PluginContainer container = mock(PluginContainer.class); // // LapisCommonsPlugin plugin = new LapisCommonsPlugin(game, container); // plugin.logger = LoggerFactory.getLogger(LapisCommonsPlugin.class); // // PreInitializationEvent init = mock(PreInitializationEvent.class); // plugin.initialize(init); // } // // public static void mockPlayers(String... players) { // List<Player> playerList = Lists.newArrayListWithCapacity(players.length); // for (String name : players) { // Player player = mock(Player.class); // when(player.getName()).thenReturn(name); // playerList.add(player); // } // // Game game = LapisCommonsPlugin.getGame(); // Server server = mock(Server.class); // when(server.getOnlinePlayers()).thenReturn(ImmutableList.copyOf(playerList)); // when(game.getServer()).thenReturn(server); // } // } // // Path: src/main/java/blue/lapis/common/command/token/InvalidTokenException.java // public class InvalidTokenException extends RuntimeException { // // private String token; // private Class<?> expectedType; // // public InvalidTokenException(String token, Class<?> expectedType) { // this.token = token; // this.expectedType = expectedType; // } // // /** // * @return the token that the TokenParser attempted to resolve // */ // public String getToken() { // return token; // } // // /** // * @return the Class of the object which the TokenParser creates // */ // public Class<?> getExpectedType() { // return expectedType; // } // } // // Path: src/main/java/blue/lapis/common/command/token/TokenParser.java // public interface TokenParser<T> { // // /** // * Parse the provided parser and return a typesafe object for it. // * // * @param source the Player, console, or command block which initiated this object resolution // * @param token the token to be resolved into an object of type {@code T} // * @return an object of type T which corresponds to the String entered // * // * @throws InvalidTokenException if the String does not appear to match any object // */ // T parse(CommandSource source, String token); // // /** // * Get tab-complete suggestions for this parser // * // * @param source The Player, CommandBlock, etc. responsible for this token // * @param token The token to generate tab-complete suggestions for // * @return a List of possible completions, or an empty List if none are available // */ // List<String> suggest(CommandSource source, String token); // } // // Path: src/main/java/blue/lapis/common/command/token/TokenParserRegistry.java // public class TokenParserRegistry { // // private static final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); // private static final Map<Class<?>, TokenParser<?>> tokenParserMap = Maps.newHashMap(); // // static { // register(Player.class, new PlayerTokenParser()); // register(Integer.class, new IntegerTokenParser()); // register(Boolean.class, new BooleanTokenParser()); // } // // // @SuppressWarnings("unchecked") // @Nullable // public static <T> TokenParser<T> get(Class<T> clazz) { // TokenParser<T> t; // lock.readLock().lock(); // { // t = (TokenParser<T>) tokenParserMap.get(clazz); // } // lock.readLock().unlock(); // return t; // } // // public static <T> void register(Class<T> clazz, TokenParser<T> parser) { // lock.writeLock().lock(); // { // tokenParserMap.put(clazz, parser); // } // lock.writeLock().unlock(); // } // }
import blue.lapis.common.command.token.TokenParser; import blue.lapis.common.command.token.TokenParserRegistry; import junit.framework.AssertionFailedError; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.spongepowered.api.entity.player.Player; import org.spongepowered.api.util.command.CommandSource; import javax.annotation.Nonnull; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; import blue.lapis.common.CommonsTests; import blue.lapis.common.command.token.InvalidTokenException;
assertParseFail(parser, "1E3"); // would like to see this accepted as 1000 instead. } @Test public void resolveBooleans() { TokenParser<Boolean> parser = getParser(Boolean.class); assertTrue(parser.parse(source, "true")); assertTrue(parser.parse(source, "yEs")); assertTrue(parser.parse(source, "On")); assertTrue(parser.parse(source, "1")); assertFalse(parser.parse(source, "FalSE")); assertFalse(parser.parse(source, "no")); assertFalse(parser.parse(source, "oFF")); assertFalse(parser.parse(source, "0")); } @Test public void invalidBooleans() { TokenParser<Boolean> parser = getParser(Boolean.class); assertParseFail(parser, "96588"); assertParseFail(parser, "hiho"); assertParseFail(parser, "000001"); assertParseFail(parser, "1.0"); } @Nonnull private <T> TokenParser<T> getParser(Class<T> type) {
// Path: src/test/java/blue/lapis/common/CommonsTests.java // public final class CommonsTests { // // public static void mockPlugin() { // Game game = mock(Game.class); // PluginContainer container = mock(PluginContainer.class); // // LapisCommonsPlugin plugin = new LapisCommonsPlugin(game, container); // plugin.logger = LoggerFactory.getLogger(LapisCommonsPlugin.class); // // PreInitializationEvent init = mock(PreInitializationEvent.class); // plugin.initialize(init); // } // // public static void mockPlayers(String... players) { // List<Player> playerList = Lists.newArrayListWithCapacity(players.length); // for (String name : players) { // Player player = mock(Player.class); // when(player.getName()).thenReturn(name); // playerList.add(player); // } // // Game game = LapisCommonsPlugin.getGame(); // Server server = mock(Server.class); // when(server.getOnlinePlayers()).thenReturn(ImmutableList.copyOf(playerList)); // when(game.getServer()).thenReturn(server); // } // } // // Path: src/main/java/blue/lapis/common/command/token/InvalidTokenException.java // public class InvalidTokenException extends RuntimeException { // // private String token; // private Class<?> expectedType; // // public InvalidTokenException(String token, Class<?> expectedType) { // this.token = token; // this.expectedType = expectedType; // } // // /** // * @return the token that the TokenParser attempted to resolve // */ // public String getToken() { // return token; // } // // /** // * @return the Class of the object which the TokenParser creates // */ // public Class<?> getExpectedType() { // return expectedType; // } // } // // Path: src/main/java/blue/lapis/common/command/token/TokenParser.java // public interface TokenParser<T> { // // /** // * Parse the provided parser and return a typesafe object for it. // * // * @param source the Player, console, or command block which initiated this object resolution // * @param token the token to be resolved into an object of type {@code T} // * @return an object of type T which corresponds to the String entered // * // * @throws InvalidTokenException if the String does not appear to match any object // */ // T parse(CommandSource source, String token); // // /** // * Get tab-complete suggestions for this parser // * // * @param source The Player, CommandBlock, etc. responsible for this token // * @param token The token to generate tab-complete suggestions for // * @return a List of possible completions, or an empty List if none are available // */ // List<String> suggest(CommandSource source, String token); // } // // Path: src/main/java/blue/lapis/common/command/token/TokenParserRegistry.java // public class TokenParserRegistry { // // private static final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); // private static final Map<Class<?>, TokenParser<?>> tokenParserMap = Maps.newHashMap(); // // static { // register(Player.class, new PlayerTokenParser()); // register(Integer.class, new IntegerTokenParser()); // register(Boolean.class, new BooleanTokenParser()); // } // // // @SuppressWarnings("unchecked") // @Nullable // public static <T> TokenParser<T> get(Class<T> clazz) { // TokenParser<T> t; // lock.readLock().lock(); // { // t = (TokenParser<T>) tokenParserMap.get(clazz); // } // lock.readLock().unlock(); // return t; // } // // public static <T> void register(Class<T> clazz, TokenParser<T> parser) { // lock.writeLock().lock(); // { // tokenParserMap.put(clazz, parser); // } // lock.writeLock().unlock(); // } // } // Path: src/test/java/blue/lapis/common/command/TokenParserTest.java import blue.lapis.common.command.token.TokenParser; import blue.lapis.common.command.token.TokenParserRegistry; import junit.framework.AssertionFailedError; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.spongepowered.api.entity.player.Player; import org.spongepowered.api.util.command.CommandSource; import javax.annotation.Nonnull; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; import blue.lapis.common.CommonsTests; import blue.lapis.common.command.token.InvalidTokenException; assertParseFail(parser, "1E3"); // would like to see this accepted as 1000 instead. } @Test public void resolveBooleans() { TokenParser<Boolean> parser = getParser(Boolean.class); assertTrue(parser.parse(source, "true")); assertTrue(parser.parse(source, "yEs")); assertTrue(parser.parse(source, "On")); assertTrue(parser.parse(source, "1")); assertFalse(parser.parse(source, "FalSE")); assertFalse(parser.parse(source, "no")); assertFalse(parser.parse(source, "oFF")); assertFalse(parser.parse(source, "0")); } @Test public void invalidBooleans() { TokenParser<Boolean> parser = getParser(Boolean.class); assertParseFail(parser, "96588"); assertParseFail(parser, "hiho"); assertParseFail(parser, "000001"); assertParseFail(parser, "1.0"); } @Nonnull private <T> TokenParser<T> getParser(Class<T> type) {
TokenParser<T> parser = TokenParserRegistry.get(type);
LapisBlue/Commons
src/test/java/blue/lapis/common/command/TokenParserTest.java
// Path: src/test/java/blue/lapis/common/CommonsTests.java // public final class CommonsTests { // // public static void mockPlugin() { // Game game = mock(Game.class); // PluginContainer container = mock(PluginContainer.class); // // LapisCommonsPlugin plugin = new LapisCommonsPlugin(game, container); // plugin.logger = LoggerFactory.getLogger(LapisCommonsPlugin.class); // // PreInitializationEvent init = mock(PreInitializationEvent.class); // plugin.initialize(init); // } // // public static void mockPlayers(String... players) { // List<Player> playerList = Lists.newArrayListWithCapacity(players.length); // for (String name : players) { // Player player = mock(Player.class); // when(player.getName()).thenReturn(name); // playerList.add(player); // } // // Game game = LapisCommonsPlugin.getGame(); // Server server = mock(Server.class); // when(server.getOnlinePlayers()).thenReturn(ImmutableList.copyOf(playerList)); // when(game.getServer()).thenReturn(server); // } // } // // Path: src/main/java/blue/lapis/common/command/token/InvalidTokenException.java // public class InvalidTokenException extends RuntimeException { // // private String token; // private Class<?> expectedType; // // public InvalidTokenException(String token, Class<?> expectedType) { // this.token = token; // this.expectedType = expectedType; // } // // /** // * @return the token that the TokenParser attempted to resolve // */ // public String getToken() { // return token; // } // // /** // * @return the Class of the object which the TokenParser creates // */ // public Class<?> getExpectedType() { // return expectedType; // } // } // // Path: src/main/java/blue/lapis/common/command/token/TokenParser.java // public interface TokenParser<T> { // // /** // * Parse the provided parser and return a typesafe object for it. // * // * @param source the Player, console, or command block which initiated this object resolution // * @param token the token to be resolved into an object of type {@code T} // * @return an object of type T which corresponds to the String entered // * // * @throws InvalidTokenException if the String does not appear to match any object // */ // T parse(CommandSource source, String token); // // /** // * Get tab-complete suggestions for this parser // * // * @param source The Player, CommandBlock, etc. responsible for this token // * @param token The token to generate tab-complete suggestions for // * @return a List of possible completions, or an empty List if none are available // */ // List<String> suggest(CommandSource source, String token); // } // // Path: src/main/java/blue/lapis/common/command/token/TokenParserRegistry.java // public class TokenParserRegistry { // // private static final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); // private static final Map<Class<?>, TokenParser<?>> tokenParserMap = Maps.newHashMap(); // // static { // register(Player.class, new PlayerTokenParser()); // register(Integer.class, new IntegerTokenParser()); // register(Boolean.class, new BooleanTokenParser()); // } // // // @SuppressWarnings("unchecked") // @Nullable // public static <T> TokenParser<T> get(Class<T> clazz) { // TokenParser<T> t; // lock.readLock().lock(); // { // t = (TokenParser<T>) tokenParserMap.get(clazz); // } // lock.readLock().unlock(); // return t; // } // // public static <T> void register(Class<T> clazz, TokenParser<T> parser) { // lock.writeLock().lock(); // { // tokenParserMap.put(clazz, parser); // } // lock.writeLock().unlock(); // } // }
import blue.lapis.common.command.token.TokenParser; import blue.lapis.common.command.token.TokenParserRegistry; import junit.framework.AssertionFailedError; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.spongepowered.api.entity.player.Player; import org.spongepowered.api.util.command.CommandSource; import javax.annotation.Nonnull; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; import blue.lapis.common.CommonsTests; import blue.lapis.common.command.token.InvalidTokenException;
assertTrue(parser.parse(source, "On")); assertTrue(parser.parse(source, "1")); assertFalse(parser.parse(source, "FalSE")); assertFalse(parser.parse(source, "no")); assertFalse(parser.parse(source, "oFF")); assertFalse(parser.parse(source, "0")); } @Test public void invalidBooleans() { TokenParser<Boolean> parser = getParser(Boolean.class); assertParseFail(parser, "96588"); assertParseFail(parser, "hiho"); assertParseFail(parser, "000001"); assertParseFail(parser, "1.0"); } @Nonnull private <T> TokenParser<T> getParser(Class<T> type) { TokenParser<T> parser = TokenParserRegistry.get(type); assertNotNull(parser); return parser; } private void assertParseFail(TokenParser t, String s) throws AssertionFailedError { try { t.parse(source, s); Assert.fail("No exception was thrown.");
// Path: src/test/java/blue/lapis/common/CommonsTests.java // public final class CommonsTests { // // public static void mockPlugin() { // Game game = mock(Game.class); // PluginContainer container = mock(PluginContainer.class); // // LapisCommonsPlugin plugin = new LapisCommonsPlugin(game, container); // plugin.logger = LoggerFactory.getLogger(LapisCommonsPlugin.class); // // PreInitializationEvent init = mock(PreInitializationEvent.class); // plugin.initialize(init); // } // // public static void mockPlayers(String... players) { // List<Player> playerList = Lists.newArrayListWithCapacity(players.length); // for (String name : players) { // Player player = mock(Player.class); // when(player.getName()).thenReturn(name); // playerList.add(player); // } // // Game game = LapisCommonsPlugin.getGame(); // Server server = mock(Server.class); // when(server.getOnlinePlayers()).thenReturn(ImmutableList.copyOf(playerList)); // when(game.getServer()).thenReturn(server); // } // } // // Path: src/main/java/blue/lapis/common/command/token/InvalidTokenException.java // public class InvalidTokenException extends RuntimeException { // // private String token; // private Class<?> expectedType; // // public InvalidTokenException(String token, Class<?> expectedType) { // this.token = token; // this.expectedType = expectedType; // } // // /** // * @return the token that the TokenParser attempted to resolve // */ // public String getToken() { // return token; // } // // /** // * @return the Class of the object which the TokenParser creates // */ // public Class<?> getExpectedType() { // return expectedType; // } // } // // Path: src/main/java/blue/lapis/common/command/token/TokenParser.java // public interface TokenParser<T> { // // /** // * Parse the provided parser and return a typesafe object for it. // * // * @param source the Player, console, or command block which initiated this object resolution // * @param token the token to be resolved into an object of type {@code T} // * @return an object of type T which corresponds to the String entered // * // * @throws InvalidTokenException if the String does not appear to match any object // */ // T parse(CommandSource source, String token); // // /** // * Get tab-complete suggestions for this parser // * // * @param source The Player, CommandBlock, etc. responsible for this token // * @param token The token to generate tab-complete suggestions for // * @return a List of possible completions, or an empty List if none are available // */ // List<String> suggest(CommandSource source, String token); // } // // Path: src/main/java/blue/lapis/common/command/token/TokenParserRegistry.java // public class TokenParserRegistry { // // private static final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); // private static final Map<Class<?>, TokenParser<?>> tokenParserMap = Maps.newHashMap(); // // static { // register(Player.class, new PlayerTokenParser()); // register(Integer.class, new IntegerTokenParser()); // register(Boolean.class, new BooleanTokenParser()); // } // // // @SuppressWarnings("unchecked") // @Nullable // public static <T> TokenParser<T> get(Class<T> clazz) { // TokenParser<T> t; // lock.readLock().lock(); // { // t = (TokenParser<T>) tokenParserMap.get(clazz); // } // lock.readLock().unlock(); // return t; // } // // public static <T> void register(Class<T> clazz, TokenParser<T> parser) { // lock.writeLock().lock(); // { // tokenParserMap.put(clazz, parser); // } // lock.writeLock().unlock(); // } // } // Path: src/test/java/blue/lapis/common/command/TokenParserTest.java import blue.lapis.common.command.token.TokenParser; import blue.lapis.common.command.token.TokenParserRegistry; import junit.framework.AssertionFailedError; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.spongepowered.api.entity.player.Player; import org.spongepowered.api.util.command.CommandSource; import javax.annotation.Nonnull; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; import blue.lapis.common.CommonsTests; import blue.lapis.common.command.token.InvalidTokenException; assertTrue(parser.parse(source, "On")); assertTrue(parser.parse(source, "1")); assertFalse(parser.parse(source, "FalSE")); assertFalse(parser.parse(source, "no")); assertFalse(parser.parse(source, "oFF")); assertFalse(parser.parse(source, "0")); } @Test public void invalidBooleans() { TokenParser<Boolean> parser = getParser(Boolean.class); assertParseFail(parser, "96588"); assertParseFail(parser, "hiho"); assertParseFail(parser, "000001"); assertParseFail(parser, "1.0"); } @Nonnull private <T> TokenParser<T> getParser(Class<T> type) { TokenParser<T> parser = TokenParserRegistry.get(type); assertNotNull(parser); return parser; } private void assertParseFail(TokenParser t, String s) throws AssertionFailedError { try { t.parse(source, s); Assert.fail("No exception was thrown.");
} catch (InvalidTokenException ignored) {
LapisBlue/Commons
src/main/java/blue/lapis/common/permission/impl/CompoundGroup.java
// Path: src/main/java/blue/lapis/common/command/impl/Parsing.java // public class Parsing { // // public static String toLowerCase(String s) { // return s.toLowerCase(Locale.ENGLISH); // } // // public static boolean startsWithIgnoreCase(String s, String start) { // return s.regionMatches(true, 0, start, 0, start.length()); // } // // public static ImmutableList<String> split(String s, String delimiter) { // ImmutableList.Builder<String> builder = ImmutableList.builder(); // int tokenEnd = s.indexOf(delimiter); // int loc = 0; // while (tokenEnd >= 0) { // if (tokenEnd > loc) { // builder.add(s.substring(loc, tokenEnd)); // } // loc = tokenEnd + delimiter.length(); // tokenEnd = s.indexOf(delimiter, loc); // } // if (loc < s.length()) builder.add(s.substring(loc, s.length())); // // return builder.build(); // } // // public static String join(List<String> strings) { // int length = 0; // for (String s : strings) { // length += s.length(); // } // // char[] value = new char[length]; // int count = 0; // for (String s : strings) { // int len = s.length(); // if (len == 0) continue; // int newCount = count + len; // s.getChars(0, len, value, count); // count = newCount; // } // return new String(value); // } // // public static String join(List<String> strings, String delimiter) { // int length = 0; // for (String s : strings) { // length += s.length(); // } // length += delimiter.length() * (strings.size() - 1); // // char[] value = new char[length]; // int count = 0; // int numStrings = strings.size(); // for (String s : strings) { // int len = s.length(); // if (len == 0) continue; // int newCount = count + len; // s.getChars(0, len, value, count); // count = newCount; // // numStrings--; // if (numStrings > 0) { // len = delimiter.length(); // if (len == 0) continue; // newCount = count + len; // delimiter.getChars(0, len, value, count); // count = newCount; // } // } // return new String(value); // } // // } // // Path: src/main/java/blue/lapis/common/permission/Group.java // public interface Group { // // public static int MAX_SEARCH_DEPTH = 16; // public static final Group ALL_GROUPS = new StandardGroup("root"); // // public String getId(); // // public ImmutableSet<Group> getInheritors(); // // public boolean hasInheritor(Group superset); // // public void addInheritor(Group superset); // // public ImmutableSet<Group> getInheritance(); // // public boolean inheritsFrom(Group subset); // // public void inheritFrom(Group subset); // // public boolean declaresPermission(String node, Group origin); // // public boolean grantsPermission(String node, int depth, Group origin); // // }
import blue.lapis.common.command.impl.Parsing; import blue.lapis.common.permission.Group; import com.google.common.base.Preconditions; import java.util.List;
/* * LapisCommons * Copyright (c) 2014, Lapis <https://github.com/LapisBlue> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package blue.lapis.common.permission.impl; /** * Represents a conditional permission, such as x&y=>{ foo } */ public class CompoundGroup extends StandardGroup { private IndexedSet<Group> supers; public CompoundGroup(String name) { super(name);
// Path: src/main/java/blue/lapis/common/command/impl/Parsing.java // public class Parsing { // // public static String toLowerCase(String s) { // return s.toLowerCase(Locale.ENGLISH); // } // // public static boolean startsWithIgnoreCase(String s, String start) { // return s.regionMatches(true, 0, start, 0, start.length()); // } // // public static ImmutableList<String> split(String s, String delimiter) { // ImmutableList.Builder<String> builder = ImmutableList.builder(); // int tokenEnd = s.indexOf(delimiter); // int loc = 0; // while (tokenEnd >= 0) { // if (tokenEnd > loc) { // builder.add(s.substring(loc, tokenEnd)); // } // loc = tokenEnd + delimiter.length(); // tokenEnd = s.indexOf(delimiter, loc); // } // if (loc < s.length()) builder.add(s.substring(loc, s.length())); // // return builder.build(); // } // // public static String join(List<String> strings) { // int length = 0; // for (String s : strings) { // length += s.length(); // } // // char[] value = new char[length]; // int count = 0; // for (String s : strings) { // int len = s.length(); // if (len == 0) continue; // int newCount = count + len; // s.getChars(0, len, value, count); // count = newCount; // } // return new String(value); // } // // public static String join(List<String> strings, String delimiter) { // int length = 0; // for (String s : strings) { // length += s.length(); // } // length += delimiter.length() * (strings.size() - 1); // // char[] value = new char[length]; // int count = 0; // int numStrings = strings.size(); // for (String s : strings) { // int len = s.length(); // if (len == 0) continue; // int newCount = count + len; // s.getChars(0, len, value, count); // count = newCount; // // numStrings--; // if (numStrings > 0) { // len = delimiter.length(); // if (len == 0) continue; // newCount = count + len; // delimiter.getChars(0, len, value, count); // count = newCount; // } // } // return new String(value); // } // // } // // Path: src/main/java/blue/lapis/common/permission/Group.java // public interface Group { // // public static int MAX_SEARCH_DEPTH = 16; // public static final Group ALL_GROUPS = new StandardGroup("root"); // // public String getId(); // // public ImmutableSet<Group> getInheritors(); // // public boolean hasInheritor(Group superset); // // public void addInheritor(Group superset); // // public ImmutableSet<Group> getInheritance(); // // public boolean inheritsFrom(Group subset); // // public void inheritFrom(Group subset); // // public boolean declaresPermission(String node, Group origin); // // public boolean grantsPermission(String node, int depth, Group origin); // // } // Path: src/main/java/blue/lapis/common/permission/impl/CompoundGroup.java import blue.lapis.common.command.impl.Parsing; import blue.lapis.common.permission.Group; import com.google.common.base.Preconditions; import java.util.List; /* * LapisCommons * Copyright (c) 2014, Lapis <https://github.com/LapisBlue> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package blue.lapis.common.permission.impl; /** * Represents a conditional permission, such as x&y=>{ foo } */ public class CompoundGroup extends StandardGroup { private IndexedSet<Group> supers; public CompoundGroup(String name) { super(name);
List<String> implication = Parsing.split(name, "=>");
namlit/siteswap_generator
app/src/main/java/namlit/siteswapgenerator/AddFilterDialog.java
// Path: app/src/main/java/siteswaplib/Filter.java // public abstract class Filter implements Serializable { // // public enum FilterType {NUMBER_FILTER, PATTERN_FILTER, INTERFACE_FILTER, // LOCAL_PATTERN_FILTER, LOCAL_INTERFACE_FILTER}; // // public abstract boolean isFulfilled(Siteswap siteswap); // // /** // * The filter is only tested at/up to index position. This function can be // * used during siteswap generation to test, if a partly generated siteswap // * would fulfill the filter condition. Returns true, if the filter is currently // * fulfilled or might be fulfilled later, when the complete siteswap is // * generated. Returns False, if it is not possible anymore, to fulfill the filter // * condition. // * */ // public abstract boolean isPartlyFulfilled(Siteswap siteswap, int index); // // public abstract String toParsableString(); // public abstract Filter fromParsableString(String str); // }
import android.content.Context; import androidx.fragment.app.DialogFragment; import siteswaplib.Filter;
/* * Siteswap Generator: Android App for generating juggling siteswaps * Copyright (C) 2017 Tilman Sinning * * 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 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package namlit.siteswapgenerator; /** * Created by tilman on 29.10.17. */ public class AddFilterDialog extends DialogFragment { public interface FilterDialogListener {
// Path: app/src/main/java/siteswaplib/Filter.java // public abstract class Filter implements Serializable { // // public enum FilterType {NUMBER_FILTER, PATTERN_FILTER, INTERFACE_FILTER, // LOCAL_PATTERN_FILTER, LOCAL_INTERFACE_FILTER}; // // public abstract boolean isFulfilled(Siteswap siteswap); // // /** // * The filter is only tested at/up to index position. This function can be // * used during siteswap generation to test, if a partly generated siteswap // * would fulfill the filter condition. Returns true, if the filter is currently // * fulfilled or might be fulfilled later, when the complete siteswap is // * generated. Returns False, if it is not possible anymore, to fulfill the filter // * condition. // * */ // public abstract boolean isPartlyFulfilled(Siteswap siteswap, int index); // // public abstract String toParsableString(); // public abstract Filter fromParsableString(String str); // } // Path: app/src/main/java/namlit/siteswapgenerator/AddFilterDialog.java import android.content.Context; import androidx.fragment.app.DialogFragment; import siteswaplib.Filter; /* * Siteswap Generator: Android App for generating juggling siteswaps * Copyright (C) 2017 Tilman Sinning * * 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 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package namlit.siteswapgenerator; /** * Created by tilman on 29.10.17. */ public class AddFilterDialog extends DialogFragment { public interface FilterDialogListener {
public void onAddSiteswapFilter(Filter filter);
namlit/siteswap_generator
app/src/main/java/siteswaplib/FilterList.java
// Path: app/src/main/java/siteswaplib/NumberFilter.java // public enum Type {GREATER_EQUAL, SMALLER_EQUAL, EQUAL}
import siteswaplib.NumberFilter.Type; import java.io.Serializable; import java.util.LinkedList; import java.util.List;
/* * Siteswap Generator: Android App for generating juggling siteswaps * Copyright (C) 2017 Tilman Sinning * * 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 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package siteswaplib; public class FilterList extends LinkedList<Filter> implements Serializable { public FilterList() { } public FilterList(int numberOfJugglers, int numberOfSynchronousHands) { addDefaultFilters(numberOfJugglers, numberOfSynchronousHands); } // TODO add and use method updateNumberOfJugglersAndSynchronousHands public void addDefaultFilters(int numberOfJugglers, int minThrow, int numberOfSynchronousHands) { if (numberOfJugglers <= 1) return; // remove Filters first, to avoid duplicate filters removeDefaultFilters(numberOfJugglers, minThrow, numberOfSynchronousHands);
// Path: app/src/main/java/siteswaplib/NumberFilter.java // public enum Type {GREATER_EQUAL, SMALLER_EQUAL, EQUAL} // Path: app/src/main/java/siteswaplib/FilterList.java import siteswaplib.NumberFilter.Type; import java.io.Serializable; import java.util.LinkedList; import java.util.List; /* * Siteswap Generator: Android App for generating juggling siteswaps * Copyright (C) 2017 Tilman Sinning * * 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 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package siteswaplib; public class FilterList extends LinkedList<Filter> implements Serializable { public FilterList() { } public FilterList(int numberOfJugglers, int numberOfSynchronousHands) { addDefaultFilters(numberOfJugglers, numberOfSynchronousHands); } // TODO add and use method updateNumberOfJugglersAndSynchronousHands public void addDefaultFilters(int numberOfJugglers, int minThrow, int numberOfSynchronousHands) { if (numberOfJugglers <= 1) return; // remove Filters first, to avoid duplicate filters removeDefaultFilters(numberOfJugglers, minThrow, numberOfSynchronousHands);
addFirst(new NumberFilter(Siteswap.PASS, Type.GREATER_EQUAL, 1, numberOfSynchronousHands));
MinhasKamal/AlgorithmImplementations
thread/shortestJob/nonpremitive/CPU.java
// Path: thread/utilClasses/Process.java // public class Process { // public String jobName; // public int arrivalTime; // public int cpuTime; // public int priority; // public char symbol; // // public Process(){ // this.jobName = ""; // this.arrivalTime = 0; // this.cpuTime = 0; // this.priority = 1; // this.symbol = '0'; // } // // public Process(String jobName, int arrivalTime, int cpuTime, char symbol){ // this.jobName = jobName; // this.arrivalTime = arrivalTime; // this.cpuTime = cpuTime; // this.priority = 1; // this.symbol = symbol; // } // // public Process(String jobName, int arrivalTime, int cpuTime, int priority, char symbol){ // this.jobName = jobName; // this.arrivalTime = arrivalTime; // this.cpuTime = cpuTime; // this.priority = priority; // this.symbol = symbol; // } // // } // // Path: thread/utilClasses/Result.java // public class Result { // public String jobName; // public char symbol; // public float waitingTime; // // public Result() { // this.jobName = "EMPTY"; // this.symbol = ' '; // waitingTime = -1; // } // // public Result(String jobName, char symbol){ // this.jobName = jobName; // this.symbol = symbol; // waitingTime = -1; // } // // public Result(String jobName, char symbol, float waitingTime){ // this.jobName = jobName; // this.symbol = symbol; // this.waitingTime = waitingTime; // } // }
import java.util.Queue; import thread.utilClasses.Process; import thread.utilClasses.Result; import java.util.LinkedList;
/************************************************************************************************ * Developer: Minhas Kamal(BSSE-0509, IIT, DU) * * Date: Sep-2014 * *************************************************************************************************/ package thread.shortestJob.nonpremitive; public class CPU { private final int CPU_CYCLE_TIME = 100; public int time;
// Path: thread/utilClasses/Process.java // public class Process { // public String jobName; // public int arrivalTime; // public int cpuTime; // public int priority; // public char symbol; // // public Process(){ // this.jobName = ""; // this.arrivalTime = 0; // this.cpuTime = 0; // this.priority = 1; // this.symbol = '0'; // } // // public Process(String jobName, int arrivalTime, int cpuTime, char symbol){ // this.jobName = jobName; // this.arrivalTime = arrivalTime; // this.cpuTime = cpuTime; // this.priority = 1; // this.symbol = symbol; // } // // public Process(String jobName, int arrivalTime, int cpuTime, int priority, char symbol){ // this.jobName = jobName; // this.arrivalTime = arrivalTime; // this.cpuTime = cpuTime; // this.priority = priority; // this.symbol = symbol; // } // // } // // Path: thread/utilClasses/Result.java // public class Result { // public String jobName; // public char symbol; // public float waitingTime; // // public Result() { // this.jobName = "EMPTY"; // this.symbol = ' '; // waitingTime = -1; // } // // public Result(String jobName, char symbol){ // this.jobName = jobName; // this.symbol = symbol; // waitingTime = -1; // } // // public Result(String jobName, char symbol, float waitingTime){ // this.jobName = jobName; // this.symbol = symbol; // this.waitingTime = waitingTime; // } // } // Path: thread/shortestJob/nonpremitive/CPU.java import java.util.Queue; import thread.utilClasses.Process; import thread.utilClasses.Result; import java.util.LinkedList; /************************************************************************************************ * Developer: Minhas Kamal(BSSE-0509, IIT, DU) * * Date: Sep-2014 * *************************************************************************************************/ package thread.shortestJob.nonpremitive; public class CPU { private final int CPU_CYCLE_TIME = 100; public int time;
public Queue<Process> waitingQueue = new LinkedList<Process>();
MinhasKamal/AlgorithmImplementations
thread/shortestJob/nonpremitive/CPU.java
// Path: thread/utilClasses/Process.java // public class Process { // public String jobName; // public int arrivalTime; // public int cpuTime; // public int priority; // public char symbol; // // public Process(){ // this.jobName = ""; // this.arrivalTime = 0; // this.cpuTime = 0; // this.priority = 1; // this.symbol = '0'; // } // // public Process(String jobName, int arrivalTime, int cpuTime, char symbol){ // this.jobName = jobName; // this.arrivalTime = arrivalTime; // this.cpuTime = cpuTime; // this.priority = 1; // this.symbol = symbol; // } // // public Process(String jobName, int arrivalTime, int cpuTime, int priority, char symbol){ // this.jobName = jobName; // this.arrivalTime = arrivalTime; // this.cpuTime = cpuTime; // this.priority = priority; // this.symbol = symbol; // } // // } // // Path: thread/utilClasses/Result.java // public class Result { // public String jobName; // public char symbol; // public float waitingTime; // // public Result() { // this.jobName = "EMPTY"; // this.symbol = ' '; // waitingTime = -1; // } // // public Result(String jobName, char symbol){ // this.jobName = jobName; // this.symbol = symbol; // waitingTime = -1; // } // // public Result(String jobName, char symbol, float waitingTime){ // this.jobName = jobName; // this.symbol = symbol; // this.waitingTime = waitingTime; // } // }
import java.util.Queue; import thread.utilClasses.Process; import thread.utilClasses.Result; import java.util.LinkedList;
/************************************************************************************************ * Developer: Minhas Kamal(BSSE-0509, IIT, DU) * * Date: Sep-2014 * *************************************************************************************************/ package thread.shortestJob.nonpremitive; public class CPU { private final int CPU_CYCLE_TIME = 100; public int time; public Queue<Process> waitingQueue = new LinkedList<Process>();
// Path: thread/utilClasses/Process.java // public class Process { // public String jobName; // public int arrivalTime; // public int cpuTime; // public int priority; // public char symbol; // // public Process(){ // this.jobName = ""; // this.arrivalTime = 0; // this.cpuTime = 0; // this.priority = 1; // this.symbol = '0'; // } // // public Process(String jobName, int arrivalTime, int cpuTime, char symbol){ // this.jobName = jobName; // this.arrivalTime = arrivalTime; // this.cpuTime = cpuTime; // this.priority = 1; // this.symbol = symbol; // } // // public Process(String jobName, int arrivalTime, int cpuTime, int priority, char symbol){ // this.jobName = jobName; // this.arrivalTime = arrivalTime; // this.cpuTime = cpuTime; // this.priority = priority; // this.symbol = symbol; // } // // } // // Path: thread/utilClasses/Result.java // public class Result { // public String jobName; // public char symbol; // public float waitingTime; // // public Result() { // this.jobName = "EMPTY"; // this.symbol = ' '; // waitingTime = -1; // } // // public Result(String jobName, char symbol){ // this.jobName = jobName; // this.symbol = symbol; // waitingTime = -1; // } // // public Result(String jobName, char symbol, float waitingTime){ // this.jobName = jobName; // this.symbol = symbol; // this.waitingTime = waitingTime; // } // } // Path: thread/shortestJob/nonpremitive/CPU.java import java.util.Queue; import thread.utilClasses.Process; import thread.utilClasses.Result; import java.util.LinkedList; /************************************************************************************************ * Developer: Minhas Kamal(BSSE-0509, IIT, DU) * * Date: Sep-2014 * *************************************************************************************************/ package thread.shortestJob.nonpremitive; public class CPU { private final int CPU_CYCLE_TIME = 100; public int time; public Queue<Process> waitingQueue = new LinkedList<Process>();
public Queue<Result> result = new LinkedList<Result>();
MinhasKamal/AlgorithmImplementations
thread/shortestJob/premitive/CPU.java
// Path: thread/utilClasses/Process.java // public class Process { // public String jobName; // public int arrivalTime; // public int cpuTime; // public int priority; // public char symbol; // // public Process(){ // this.jobName = ""; // this.arrivalTime = 0; // this.cpuTime = 0; // this.priority = 1; // this.symbol = '0'; // } // // public Process(String jobName, int arrivalTime, int cpuTime, char symbol){ // this.jobName = jobName; // this.arrivalTime = arrivalTime; // this.cpuTime = cpuTime; // this.priority = 1; // this.symbol = symbol; // } // // public Process(String jobName, int arrivalTime, int cpuTime, int priority, char symbol){ // this.jobName = jobName; // this.arrivalTime = arrivalTime; // this.cpuTime = cpuTime; // this.priority = priority; // this.symbol = symbol; // } // // } // // Path: thread/utilClasses/Result.java // public class Result { // public String jobName; // public char symbol; // public float waitingTime; // // public Result() { // this.jobName = "EMPTY"; // this.symbol = ' '; // waitingTime = -1; // } // // public Result(String jobName, char symbol){ // this.jobName = jobName; // this.symbol = symbol; // waitingTime = -1; // } // // public Result(String jobName, char symbol, float waitingTime){ // this.jobName = jobName; // this.symbol = symbol; // this.waitingTime = waitingTime; // } // }
import java.util.Queue; import thread.utilClasses.Process; import thread.utilClasses.Result; import java.util.LinkedList;
/************************************************************************************************ * Developer: Minhas Kamal(BSSE-0509, IIT, DU) * * Date: Sep-2014 * *************************************************************************************************/ package thread.shortestJob.premitive; public class CPU { private final int CPU_CYCLE_TIME = 100; public int time;
// Path: thread/utilClasses/Process.java // public class Process { // public String jobName; // public int arrivalTime; // public int cpuTime; // public int priority; // public char symbol; // // public Process(){ // this.jobName = ""; // this.arrivalTime = 0; // this.cpuTime = 0; // this.priority = 1; // this.symbol = '0'; // } // // public Process(String jobName, int arrivalTime, int cpuTime, char symbol){ // this.jobName = jobName; // this.arrivalTime = arrivalTime; // this.cpuTime = cpuTime; // this.priority = 1; // this.symbol = symbol; // } // // public Process(String jobName, int arrivalTime, int cpuTime, int priority, char symbol){ // this.jobName = jobName; // this.arrivalTime = arrivalTime; // this.cpuTime = cpuTime; // this.priority = priority; // this.symbol = symbol; // } // // } // // Path: thread/utilClasses/Result.java // public class Result { // public String jobName; // public char symbol; // public float waitingTime; // // public Result() { // this.jobName = "EMPTY"; // this.symbol = ' '; // waitingTime = -1; // } // // public Result(String jobName, char symbol){ // this.jobName = jobName; // this.symbol = symbol; // waitingTime = -1; // } // // public Result(String jobName, char symbol, float waitingTime){ // this.jobName = jobName; // this.symbol = symbol; // this.waitingTime = waitingTime; // } // } // Path: thread/shortestJob/premitive/CPU.java import java.util.Queue; import thread.utilClasses.Process; import thread.utilClasses.Result; import java.util.LinkedList; /************************************************************************************************ * Developer: Minhas Kamal(BSSE-0509, IIT, DU) * * Date: Sep-2014 * *************************************************************************************************/ package thread.shortestJob.premitive; public class CPU { private final int CPU_CYCLE_TIME = 100; public int time;
public Queue<Process> waitingQueue = new LinkedList<Process>();
MinhasKamal/AlgorithmImplementations
thread/shortestJob/premitive/CPU.java
// Path: thread/utilClasses/Process.java // public class Process { // public String jobName; // public int arrivalTime; // public int cpuTime; // public int priority; // public char symbol; // // public Process(){ // this.jobName = ""; // this.arrivalTime = 0; // this.cpuTime = 0; // this.priority = 1; // this.symbol = '0'; // } // // public Process(String jobName, int arrivalTime, int cpuTime, char symbol){ // this.jobName = jobName; // this.arrivalTime = arrivalTime; // this.cpuTime = cpuTime; // this.priority = 1; // this.symbol = symbol; // } // // public Process(String jobName, int arrivalTime, int cpuTime, int priority, char symbol){ // this.jobName = jobName; // this.arrivalTime = arrivalTime; // this.cpuTime = cpuTime; // this.priority = priority; // this.symbol = symbol; // } // // } // // Path: thread/utilClasses/Result.java // public class Result { // public String jobName; // public char symbol; // public float waitingTime; // // public Result() { // this.jobName = "EMPTY"; // this.symbol = ' '; // waitingTime = -1; // } // // public Result(String jobName, char symbol){ // this.jobName = jobName; // this.symbol = symbol; // waitingTime = -1; // } // // public Result(String jobName, char symbol, float waitingTime){ // this.jobName = jobName; // this.symbol = symbol; // this.waitingTime = waitingTime; // } // }
import java.util.Queue; import thread.utilClasses.Process; import thread.utilClasses.Result; import java.util.LinkedList;
/************************************************************************************************ * Developer: Minhas Kamal(BSSE-0509, IIT, DU) * * Date: Sep-2014 * *************************************************************************************************/ package thread.shortestJob.premitive; public class CPU { private final int CPU_CYCLE_TIME = 100; public int time; public Queue<Process> waitingQueue = new LinkedList<Process>();
// Path: thread/utilClasses/Process.java // public class Process { // public String jobName; // public int arrivalTime; // public int cpuTime; // public int priority; // public char symbol; // // public Process(){ // this.jobName = ""; // this.arrivalTime = 0; // this.cpuTime = 0; // this.priority = 1; // this.symbol = '0'; // } // // public Process(String jobName, int arrivalTime, int cpuTime, char symbol){ // this.jobName = jobName; // this.arrivalTime = arrivalTime; // this.cpuTime = cpuTime; // this.priority = 1; // this.symbol = symbol; // } // // public Process(String jobName, int arrivalTime, int cpuTime, int priority, char symbol){ // this.jobName = jobName; // this.arrivalTime = arrivalTime; // this.cpuTime = cpuTime; // this.priority = priority; // this.symbol = symbol; // } // // } // // Path: thread/utilClasses/Result.java // public class Result { // public String jobName; // public char symbol; // public float waitingTime; // // public Result() { // this.jobName = "EMPTY"; // this.symbol = ' '; // waitingTime = -1; // } // // public Result(String jobName, char symbol){ // this.jobName = jobName; // this.symbol = symbol; // waitingTime = -1; // } // // public Result(String jobName, char symbol, float waitingTime){ // this.jobName = jobName; // this.symbol = symbol; // this.waitingTime = waitingTime; // } // } // Path: thread/shortestJob/premitive/CPU.java import java.util.Queue; import thread.utilClasses.Process; import thread.utilClasses.Result; import java.util.LinkedList; /************************************************************************************************ * Developer: Minhas Kamal(BSSE-0509, IIT, DU) * * Date: Sep-2014 * *************************************************************************************************/ package thread.shortestJob.premitive; public class CPU { private final int CPU_CYCLE_TIME = 100; public int time; public Queue<Process> waitingQueue = new LinkedList<Process>();
public Queue<Result> result = new LinkedList<Result>();
MinhasKamal/AlgorithmImplementations
thread/priorityBased/premitive/CPU.java
// Path: thread/utilClasses/Process.java // public class Process { // public String jobName; // public int arrivalTime; // public int cpuTime; // public int priority; // public char symbol; // // public Process(){ // this.jobName = ""; // this.arrivalTime = 0; // this.cpuTime = 0; // this.priority = 1; // this.symbol = '0'; // } // // public Process(String jobName, int arrivalTime, int cpuTime, char symbol){ // this.jobName = jobName; // this.arrivalTime = arrivalTime; // this.cpuTime = cpuTime; // this.priority = 1; // this.symbol = symbol; // } // // public Process(String jobName, int arrivalTime, int cpuTime, int priority, char symbol){ // this.jobName = jobName; // this.arrivalTime = arrivalTime; // this.cpuTime = cpuTime; // this.priority = priority; // this.symbol = symbol; // } // // } // // Path: thread/utilClasses/Result.java // public class Result { // public String jobName; // public char symbol; // public float waitingTime; // // public Result() { // this.jobName = "EMPTY"; // this.symbol = ' '; // waitingTime = -1; // } // // public Result(String jobName, char symbol){ // this.jobName = jobName; // this.symbol = symbol; // waitingTime = -1; // } // // public Result(String jobName, char symbol, float waitingTime){ // this.jobName = jobName; // this.symbol = symbol; // this.waitingTime = waitingTime; // } // }
import java.util.Queue; import thread.utilClasses.Process; import thread.utilClasses.Result; import java.util.LinkedList;
/************************************************************************************************ * Developer: Minhas Kamal(BSSE-0509, IIT, DU) * * Date: Sep-2014 * *************************************************************************************************/ package thread.priorityBased.premitive; public class CPU { private final int CPU_CYCLE_TIME = 100; public int time = 0;
// Path: thread/utilClasses/Process.java // public class Process { // public String jobName; // public int arrivalTime; // public int cpuTime; // public int priority; // public char symbol; // // public Process(){ // this.jobName = ""; // this.arrivalTime = 0; // this.cpuTime = 0; // this.priority = 1; // this.symbol = '0'; // } // // public Process(String jobName, int arrivalTime, int cpuTime, char symbol){ // this.jobName = jobName; // this.arrivalTime = arrivalTime; // this.cpuTime = cpuTime; // this.priority = 1; // this.symbol = symbol; // } // // public Process(String jobName, int arrivalTime, int cpuTime, int priority, char symbol){ // this.jobName = jobName; // this.arrivalTime = arrivalTime; // this.cpuTime = cpuTime; // this.priority = priority; // this.symbol = symbol; // } // // } // // Path: thread/utilClasses/Result.java // public class Result { // public String jobName; // public char symbol; // public float waitingTime; // // public Result() { // this.jobName = "EMPTY"; // this.symbol = ' '; // waitingTime = -1; // } // // public Result(String jobName, char symbol){ // this.jobName = jobName; // this.symbol = symbol; // waitingTime = -1; // } // // public Result(String jobName, char symbol, float waitingTime){ // this.jobName = jobName; // this.symbol = symbol; // this.waitingTime = waitingTime; // } // } // Path: thread/priorityBased/premitive/CPU.java import java.util.Queue; import thread.utilClasses.Process; import thread.utilClasses.Result; import java.util.LinkedList; /************************************************************************************************ * Developer: Minhas Kamal(BSSE-0509, IIT, DU) * * Date: Sep-2014 * *************************************************************************************************/ package thread.priorityBased.premitive; public class CPU { private final int CPU_CYCLE_TIME = 100; public int time = 0;
public Queue<Process> waitingQueue = new LinkedList<Process>();
MinhasKamal/AlgorithmImplementations
thread/priorityBased/premitive/CPU.java
// Path: thread/utilClasses/Process.java // public class Process { // public String jobName; // public int arrivalTime; // public int cpuTime; // public int priority; // public char symbol; // // public Process(){ // this.jobName = ""; // this.arrivalTime = 0; // this.cpuTime = 0; // this.priority = 1; // this.symbol = '0'; // } // // public Process(String jobName, int arrivalTime, int cpuTime, char symbol){ // this.jobName = jobName; // this.arrivalTime = arrivalTime; // this.cpuTime = cpuTime; // this.priority = 1; // this.symbol = symbol; // } // // public Process(String jobName, int arrivalTime, int cpuTime, int priority, char symbol){ // this.jobName = jobName; // this.arrivalTime = arrivalTime; // this.cpuTime = cpuTime; // this.priority = priority; // this.symbol = symbol; // } // // } // // Path: thread/utilClasses/Result.java // public class Result { // public String jobName; // public char symbol; // public float waitingTime; // // public Result() { // this.jobName = "EMPTY"; // this.symbol = ' '; // waitingTime = -1; // } // // public Result(String jobName, char symbol){ // this.jobName = jobName; // this.symbol = symbol; // waitingTime = -1; // } // // public Result(String jobName, char symbol, float waitingTime){ // this.jobName = jobName; // this.symbol = symbol; // this.waitingTime = waitingTime; // } // }
import java.util.Queue; import thread.utilClasses.Process; import thread.utilClasses.Result; import java.util.LinkedList;
/************************************************************************************************ * Developer: Minhas Kamal(BSSE-0509, IIT, DU) * * Date: Sep-2014 * *************************************************************************************************/ package thread.priorityBased.premitive; public class CPU { private final int CPU_CYCLE_TIME = 100; public int time = 0; public Queue<Process> waitingQueue = new LinkedList<Process>();
// Path: thread/utilClasses/Process.java // public class Process { // public String jobName; // public int arrivalTime; // public int cpuTime; // public int priority; // public char symbol; // // public Process(){ // this.jobName = ""; // this.arrivalTime = 0; // this.cpuTime = 0; // this.priority = 1; // this.symbol = '0'; // } // // public Process(String jobName, int arrivalTime, int cpuTime, char symbol){ // this.jobName = jobName; // this.arrivalTime = arrivalTime; // this.cpuTime = cpuTime; // this.priority = 1; // this.symbol = symbol; // } // // public Process(String jobName, int arrivalTime, int cpuTime, int priority, char symbol){ // this.jobName = jobName; // this.arrivalTime = arrivalTime; // this.cpuTime = cpuTime; // this.priority = priority; // this.symbol = symbol; // } // // } // // Path: thread/utilClasses/Result.java // public class Result { // public String jobName; // public char symbol; // public float waitingTime; // // public Result() { // this.jobName = "EMPTY"; // this.symbol = ' '; // waitingTime = -1; // } // // public Result(String jobName, char symbol){ // this.jobName = jobName; // this.symbol = symbol; // waitingTime = -1; // } // // public Result(String jobName, char symbol, float waitingTime){ // this.jobName = jobName; // this.symbol = symbol; // this.waitingTime = waitingTime; // } // } // Path: thread/priorityBased/premitive/CPU.java import java.util.Queue; import thread.utilClasses.Process; import thread.utilClasses.Result; import java.util.LinkedList; /************************************************************************************************ * Developer: Minhas Kamal(BSSE-0509, IIT, DU) * * Date: Sep-2014 * *************************************************************************************************/ package thread.priorityBased.premitive; public class CPU { private final int CPU_CYCLE_TIME = 100; public int time = 0; public Queue<Process> waitingQueue = new LinkedList<Process>();
public Queue<Result> result = new LinkedList<Result>();
MinhasKamal/AlgorithmImplementations
thread/priorityBased/nonpremitive/CPU.java
// Path: thread/utilClasses/Process.java // public class Process { // public String jobName; // public int arrivalTime; // public int cpuTime; // public int priority; // public char symbol; // // public Process(){ // this.jobName = ""; // this.arrivalTime = 0; // this.cpuTime = 0; // this.priority = 1; // this.symbol = '0'; // } // // public Process(String jobName, int arrivalTime, int cpuTime, char symbol){ // this.jobName = jobName; // this.arrivalTime = arrivalTime; // this.cpuTime = cpuTime; // this.priority = 1; // this.symbol = symbol; // } // // public Process(String jobName, int arrivalTime, int cpuTime, int priority, char symbol){ // this.jobName = jobName; // this.arrivalTime = arrivalTime; // this.cpuTime = cpuTime; // this.priority = priority; // this.symbol = symbol; // } // // } // // Path: thread/utilClasses/Result.java // public class Result { // public String jobName; // public char symbol; // public float waitingTime; // // public Result() { // this.jobName = "EMPTY"; // this.symbol = ' '; // waitingTime = -1; // } // // public Result(String jobName, char symbol){ // this.jobName = jobName; // this.symbol = symbol; // waitingTime = -1; // } // // public Result(String jobName, char symbol, float waitingTime){ // this.jobName = jobName; // this.symbol = symbol; // this.waitingTime = waitingTime; // } // }
import java.util.Queue; import thread.utilClasses.Process; import thread.utilClasses.Result; import java.util.LinkedList;
/************************************************************************************************ * Developer: Minhas Kamal(BSSE-0509, IIT, DU) * * Date: Sep-2014 * *************************************************************************************************/ package thread.priorityBased.nonpremitive; public class CPU { private final int CPU_CYCLE_TIME = 100; public int time;
// Path: thread/utilClasses/Process.java // public class Process { // public String jobName; // public int arrivalTime; // public int cpuTime; // public int priority; // public char symbol; // // public Process(){ // this.jobName = ""; // this.arrivalTime = 0; // this.cpuTime = 0; // this.priority = 1; // this.symbol = '0'; // } // // public Process(String jobName, int arrivalTime, int cpuTime, char symbol){ // this.jobName = jobName; // this.arrivalTime = arrivalTime; // this.cpuTime = cpuTime; // this.priority = 1; // this.symbol = symbol; // } // // public Process(String jobName, int arrivalTime, int cpuTime, int priority, char symbol){ // this.jobName = jobName; // this.arrivalTime = arrivalTime; // this.cpuTime = cpuTime; // this.priority = priority; // this.symbol = symbol; // } // // } // // Path: thread/utilClasses/Result.java // public class Result { // public String jobName; // public char symbol; // public float waitingTime; // // public Result() { // this.jobName = "EMPTY"; // this.symbol = ' '; // waitingTime = -1; // } // // public Result(String jobName, char symbol){ // this.jobName = jobName; // this.symbol = symbol; // waitingTime = -1; // } // // public Result(String jobName, char symbol, float waitingTime){ // this.jobName = jobName; // this.symbol = symbol; // this.waitingTime = waitingTime; // } // } // Path: thread/priorityBased/nonpremitive/CPU.java import java.util.Queue; import thread.utilClasses.Process; import thread.utilClasses.Result; import java.util.LinkedList; /************************************************************************************************ * Developer: Minhas Kamal(BSSE-0509, IIT, DU) * * Date: Sep-2014 * *************************************************************************************************/ package thread.priorityBased.nonpremitive; public class CPU { private final int CPU_CYCLE_TIME = 100; public int time;
public Queue<Process> waitingQueue = new LinkedList<Process>();
MinhasKamal/AlgorithmImplementations
thread/priorityBased/nonpremitive/CPU.java
// Path: thread/utilClasses/Process.java // public class Process { // public String jobName; // public int arrivalTime; // public int cpuTime; // public int priority; // public char symbol; // // public Process(){ // this.jobName = ""; // this.arrivalTime = 0; // this.cpuTime = 0; // this.priority = 1; // this.symbol = '0'; // } // // public Process(String jobName, int arrivalTime, int cpuTime, char symbol){ // this.jobName = jobName; // this.arrivalTime = arrivalTime; // this.cpuTime = cpuTime; // this.priority = 1; // this.symbol = symbol; // } // // public Process(String jobName, int arrivalTime, int cpuTime, int priority, char symbol){ // this.jobName = jobName; // this.arrivalTime = arrivalTime; // this.cpuTime = cpuTime; // this.priority = priority; // this.symbol = symbol; // } // // } // // Path: thread/utilClasses/Result.java // public class Result { // public String jobName; // public char symbol; // public float waitingTime; // // public Result() { // this.jobName = "EMPTY"; // this.symbol = ' '; // waitingTime = -1; // } // // public Result(String jobName, char symbol){ // this.jobName = jobName; // this.symbol = symbol; // waitingTime = -1; // } // // public Result(String jobName, char symbol, float waitingTime){ // this.jobName = jobName; // this.symbol = symbol; // this.waitingTime = waitingTime; // } // }
import java.util.Queue; import thread.utilClasses.Process; import thread.utilClasses.Result; import java.util.LinkedList;
/************************************************************************************************ * Developer: Minhas Kamal(BSSE-0509, IIT, DU) * * Date: Sep-2014 * *************************************************************************************************/ package thread.priorityBased.nonpremitive; public class CPU { private final int CPU_CYCLE_TIME = 100; public int time; public Queue<Process> waitingQueue = new LinkedList<Process>();
// Path: thread/utilClasses/Process.java // public class Process { // public String jobName; // public int arrivalTime; // public int cpuTime; // public int priority; // public char symbol; // // public Process(){ // this.jobName = ""; // this.arrivalTime = 0; // this.cpuTime = 0; // this.priority = 1; // this.symbol = '0'; // } // // public Process(String jobName, int arrivalTime, int cpuTime, char symbol){ // this.jobName = jobName; // this.arrivalTime = arrivalTime; // this.cpuTime = cpuTime; // this.priority = 1; // this.symbol = symbol; // } // // public Process(String jobName, int arrivalTime, int cpuTime, int priority, char symbol){ // this.jobName = jobName; // this.arrivalTime = arrivalTime; // this.cpuTime = cpuTime; // this.priority = priority; // this.symbol = symbol; // } // // } // // Path: thread/utilClasses/Result.java // public class Result { // public String jobName; // public char symbol; // public float waitingTime; // // public Result() { // this.jobName = "EMPTY"; // this.symbol = ' '; // waitingTime = -1; // } // // public Result(String jobName, char symbol){ // this.jobName = jobName; // this.symbol = symbol; // waitingTime = -1; // } // // public Result(String jobName, char symbol, float waitingTime){ // this.jobName = jobName; // this.symbol = symbol; // this.waitingTime = waitingTime; // } // } // Path: thread/priorityBased/nonpremitive/CPU.java import java.util.Queue; import thread.utilClasses.Process; import thread.utilClasses.Result; import java.util.LinkedList; /************************************************************************************************ * Developer: Minhas Kamal(BSSE-0509, IIT, DU) * * Date: Sep-2014 * *************************************************************************************************/ package thread.priorityBased.nonpremitive; public class CPU { private final int CPU_CYCLE_TIME = 100; public int time; public Queue<Process> waitingQueue = new LinkedList<Process>();
public Queue<Result> result = new LinkedList<Result>();
universal-automata/liblevenshtein-java
src/test/java/com/github/liblevenshtein/assertion/CandidateAssertionsTest.java
// Path: src/main/java/com/github/liblevenshtein/distance/IDistance.java // public interface IDistance<Term> extends Serializable { // // /** // * Finds the distance between two terms, {@code v} and {@code w}. The distance // * between two terms is complemented by their similarity, which is determined // * by subtracting their distance from the maximum distance they may be apart. // * @param v Term to compare with {@code w} // * @param w Term to compare with {@code v} // * @return Distance between {@code v} and {@code w} // */ // int between(Term v, Term w); // } // // Path: src/main/java/com/github/liblevenshtein/transducer/Candidate.java // @Value // public class Candidate implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Candidate term from the dictionary automaton. // * @return Candidate term from the dictionary automaton. // */ // private final String term; // // /** // * Distance between the candidate term and the query term. // * @return Distance between the candidate term and the query term. // */ // private final int distance; // } // // Path: src/test/java/com/github/liblevenshtein/assertion/CandidateAssertions.java // public static CandidateAssertions assertThat(final Candidate actual) { // return new CandidateAssertions(actual); // }
import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import com.github.liblevenshtein.distance.IDistance; import com.github.liblevenshtein.transducer.Candidate; import static com.github.liblevenshtein.assertion.CandidateAssertions.assertThat;
package com.github.liblevenshtein.assertion; public class CandidateAssertionsTest { private static final String FOO = "foo"; private static final String BAR = "bar";
// Path: src/main/java/com/github/liblevenshtein/distance/IDistance.java // public interface IDistance<Term> extends Serializable { // // /** // * Finds the distance between two terms, {@code v} and {@code w}. The distance // * between two terms is complemented by their similarity, which is determined // * by subtracting their distance from the maximum distance they may be apart. // * @param v Term to compare with {@code w} // * @param w Term to compare with {@code v} // * @return Distance between {@code v} and {@code w} // */ // int between(Term v, Term w); // } // // Path: src/main/java/com/github/liblevenshtein/transducer/Candidate.java // @Value // public class Candidate implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Candidate term from the dictionary automaton. // * @return Candidate term from the dictionary automaton. // */ // private final String term; // // /** // * Distance between the candidate term and the query term. // * @return Distance between the candidate term and the query term. // */ // private final int distance; // } // // Path: src/test/java/com/github/liblevenshtein/assertion/CandidateAssertions.java // public static CandidateAssertions assertThat(final Candidate actual) { // return new CandidateAssertions(actual); // } // Path: src/test/java/com/github/liblevenshtein/assertion/CandidateAssertionsTest.java import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import com.github.liblevenshtein.distance.IDistance; import com.github.liblevenshtein.transducer.Candidate; import static com.github.liblevenshtein.assertion.CandidateAssertions.assertThat; package com.github.liblevenshtein.assertion; public class CandidateAssertionsTest { private static final String FOO = "foo"; private static final String BAR = "bar";
private final ThreadLocal<IDistance<String>> distance = new ThreadLocal<>();
universal-automata/liblevenshtein-java
src/test/java/com/github/liblevenshtein/assertion/CandidateAssertionsTest.java
// Path: src/main/java/com/github/liblevenshtein/distance/IDistance.java // public interface IDistance<Term> extends Serializable { // // /** // * Finds the distance between two terms, {@code v} and {@code w}. The distance // * between two terms is complemented by their similarity, which is determined // * by subtracting their distance from the maximum distance they may be apart. // * @param v Term to compare with {@code w} // * @param w Term to compare with {@code v} // * @return Distance between {@code v} and {@code w} // */ // int between(Term v, Term w); // } // // Path: src/main/java/com/github/liblevenshtein/transducer/Candidate.java // @Value // public class Candidate implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Candidate term from the dictionary automaton. // * @return Candidate term from the dictionary automaton. // */ // private final String term; // // /** // * Distance between the candidate term and the query term. // * @return Distance between the candidate term and the query term. // */ // private final int distance; // } // // Path: src/test/java/com/github/liblevenshtein/assertion/CandidateAssertions.java // public static CandidateAssertions assertThat(final Candidate actual) { // return new CandidateAssertions(actual); // }
import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import com.github.liblevenshtein.distance.IDistance; import com.github.liblevenshtein.transducer.Candidate; import static com.github.liblevenshtein.assertion.CandidateAssertions.assertThat;
package com.github.liblevenshtein.assertion; public class CandidateAssertionsTest { private static final String FOO = "foo"; private static final String BAR = "bar"; private final ThreadLocal<IDistance<String>> distance = new ThreadLocal<>(); @BeforeMethod @SuppressWarnings("unchecked") public void setUp() { distance.set(mock(IDistance.class)); } @Test public void testHasDistance() {
// Path: src/main/java/com/github/liblevenshtein/distance/IDistance.java // public interface IDistance<Term> extends Serializable { // // /** // * Finds the distance between two terms, {@code v} and {@code w}. The distance // * between two terms is complemented by their similarity, which is determined // * by subtracting their distance from the maximum distance they may be apart. // * @param v Term to compare with {@code w} // * @param w Term to compare with {@code v} // * @return Distance between {@code v} and {@code w} // */ // int between(Term v, Term w); // } // // Path: src/main/java/com/github/liblevenshtein/transducer/Candidate.java // @Value // public class Candidate implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Candidate term from the dictionary automaton. // * @return Candidate term from the dictionary automaton. // */ // private final String term; // // /** // * Distance between the candidate term and the query term. // * @return Distance between the candidate term and the query term. // */ // private final int distance; // } // // Path: src/test/java/com/github/liblevenshtein/assertion/CandidateAssertions.java // public static CandidateAssertions assertThat(final Candidate actual) { // return new CandidateAssertions(actual); // } // Path: src/test/java/com/github/liblevenshtein/assertion/CandidateAssertionsTest.java import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import com.github.liblevenshtein.distance.IDistance; import com.github.liblevenshtein.transducer.Candidate; import static com.github.liblevenshtein.assertion.CandidateAssertions.assertThat; package com.github.liblevenshtein.assertion; public class CandidateAssertionsTest { private static final String FOO = "foo"; private static final String BAR = "bar"; private final ThreadLocal<IDistance<String>> distance = new ThreadLocal<>(); @BeforeMethod @SuppressWarnings("unchecked") public void setUp() { distance.set(mock(IDistance.class)); } @Test public void testHasDistance() {
final Candidate candidate = new Candidate(BAR, 3);
universal-automata/liblevenshtein-java
src/test/java/com/github/liblevenshtein/assertion/CandidateAssertionsTest.java
// Path: src/main/java/com/github/liblevenshtein/distance/IDistance.java // public interface IDistance<Term> extends Serializable { // // /** // * Finds the distance between two terms, {@code v} and {@code w}. The distance // * between two terms is complemented by their similarity, which is determined // * by subtracting their distance from the maximum distance they may be apart. // * @param v Term to compare with {@code w} // * @param w Term to compare with {@code v} // * @return Distance between {@code v} and {@code w} // */ // int between(Term v, Term w); // } // // Path: src/main/java/com/github/liblevenshtein/transducer/Candidate.java // @Value // public class Candidate implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Candidate term from the dictionary automaton. // * @return Candidate term from the dictionary automaton. // */ // private final String term; // // /** // * Distance between the candidate term and the query term. // * @return Distance between the candidate term and the query term. // */ // private final int distance; // } // // Path: src/test/java/com/github/liblevenshtein/assertion/CandidateAssertions.java // public static CandidateAssertions assertThat(final Candidate actual) { // return new CandidateAssertions(actual); // }
import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import com.github.liblevenshtein.distance.IDistance; import com.github.liblevenshtein.transducer.Candidate; import static com.github.liblevenshtein.assertion.CandidateAssertions.assertThat;
package com.github.liblevenshtein.assertion; public class CandidateAssertionsTest { private static final String FOO = "foo"; private static final String BAR = "bar"; private final ThreadLocal<IDistance<String>> distance = new ThreadLocal<>(); @BeforeMethod @SuppressWarnings("unchecked") public void setUp() { distance.set(mock(IDistance.class)); } @Test public void testHasDistance() { final Candidate candidate = new Candidate(BAR, 3); when(distance.get().between(FOO, BAR)).thenReturn(3);
// Path: src/main/java/com/github/liblevenshtein/distance/IDistance.java // public interface IDistance<Term> extends Serializable { // // /** // * Finds the distance between two terms, {@code v} and {@code w}. The distance // * between two terms is complemented by their similarity, which is determined // * by subtracting their distance from the maximum distance they may be apart. // * @param v Term to compare with {@code w} // * @param w Term to compare with {@code v} // * @return Distance between {@code v} and {@code w} // */ // int between(Term v, Term w); // } // // Path: src/main/java/com/github/liblevenshtein/transducer/Candidate.java // @Value // public class Candidate implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Candidate term from the dictionary automaton. // * @return Candidate term from the dictionary automaton. // */ // private final String term; // // /** // * Distance between the candidate term and the query term. // * @return Distance between the candidate term and the query term. // */ // private final int distance; // } // // Path: src/test/java/com/github/liblevenshtein/assertion/CandidateAssertions.java // public static CandidateAssertions assertThat(final Candidate actual) { // return new CandidateAssertions(actual); // } // Path: src/test/java/com/github/liblevenshtein/assertion/CandidateAssertionsTest.java import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import com.github.liblevenshtein.distance.IDistance; import com.github.liblevenshtein.transducer.Candidate; import static com.github.liblevenshtein.assertion.CandidateAssertions.assertThat; package com.github.liblevenshtein.assertion; public class CandidateAssertionsTest { private static final String FOO = "foo"; private static final String BAR = "bar"; private final ThreadLocal<IDistance<String>> distance = new ThreadLocal<>(); @BeforeMethod @SuppressWarnings("unchecked") public void setUp() { distance.set(mock(IDistance.class)); } @Test public void testHasDistance() { final Candidate candidate = new Candidate(BAR, 3); when(distance.get().between(FOO, BAR)).thenReturn(3);
assertThat(candidate).hasDistance(distance.get(), FOO);
universal-automata/liblevenshtein-java
src/test/java/com/github/liblevenshtein/transducer/MergeFunctionTest.java
// Path: src/main/java/com/github/liblevenshtein/transducer/factory/PositionFactory.java // @NoArgsConstructor // public class PositionFactory implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Builds a dummy position. // * @return Dummy position. // */ // public Position build() { // return new Position(-1, -1); // } // // /** // * Builds a position vector for the standard, Levenshtein algorihtm. // * @param termIndex Current index of the spelling candidate. // * @param numErrors Number of accumulated errors at index {@code termIndex}. // * @return New position vector having index {@code termIndex} and error // * {@code numErrors}. // */ // public Position build(final int termIndex, final int numErrors) { // return new Position(termIndex, numErrors); // } // // /** // * Builds a position vector for the transposition and merge-and-split, // * Levenshtein algorihtms. // * @param termIndex Current index of the spelling candidate. // * @param numErrors Number of accumulated errors at index {@code termIndex}. // * @param isSpecial Either {@code 1} or {@code 0}, depending on whether the // * position is a special case (numErrors.g. a transposition position). // * @return New position vector having index {@code termIndex}, error // * {@code numErrors}, and special marker {@code isSpecial}. // */ // public Position build(final int termIndex, final int numErrors, final boolean isSpecial) { // if (isSpecial) { // return new SpecialPosition(termIndex, numErrors); // } // // return new Position(termIndex, numErrors); // } // } // // Path: src/main/java/com/github/liblevenshtein/transducer/factory/StateFactory.java // public class StateFactory implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Builds a new, Levenshtein state with the given position vectors. // * @param positions Array of position vectors to link into the state. // * @return New state having the position vectors. // */ // public State build(final Position... positions) { // final State state = new State(); // // Position prev = null; // for (final Position curr : positions) { // state.insertAfter(prev, curr); // prev = curr; // } // // return state; // } // }
import org.testng.annotations.Test; import static org.assertj.core.api.Assertions.assertThat; import com.github.liblevenshtein.transducer.factory.PositionFactory; import com.github.liblevenshtein.transducer.factory.StateFactory;
package com.github.liblevenshtein.transducer; public class MergeFunctionTest { private final StateFactory stateFactory = new StateFactory();
// Path: src/main/java/com/github/liblevenshtein/transducer/factory/PositionFactory.java // @NoArgsConstructor // public class PositionFactory implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Builds a dummy position. // * @return Dummy position. // */ // public Position build() { // return new Position(-1, -1); // } // // /** // * Builds a position vector for the standard, Levenshtein algorihtm. // * @param termIndex Current index of the spelling candidate. // * @param numErrors Number of accumulated errors at index {@code termIndex}. // * @return New position vector having index {@code termIndex} and error // * {@code numErrors}. // */ // public Position build(final int termIndex, final int numErrors) { // return new Position(termIndex, numErrors); // } // // /** // * Builds a position vector for the transposition and merge-and-split, // * Levenshtein algorihtms. // * @param termIndex Current index of the spelling candidate. // * @param numErrors Number of accumulated errors at index {@code termIndex}. // * @param isSpecial Either {@code 1} or {@code 0}, depending on whether the // * position is a special case (numErrors.g. a transposition position). // * @return New position vector having index {@code termIndex}, error // * {@code numErrors}, and special marker {@code isSpecial}. // */ // public Position build(final int termIndex, final int numErrors, final boolean isSpecial) { // if (isSpecial) { // return new SpecialPosition(termIndex, numErrors); // } // // return new Position(termIndex, numErrors); // } // } // // Path: src/main/java/com/github/liblevenshtein/transducer/factory/StateFactory.java // public class StateFactory implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Builds a new, Levenshtein state with the given position vectors. // * @param positions Array of position vectors to link into the state. // * @return New state having the position vectors. // */ // public State build(final Position... positions) { // final State state = new State(); // // Position prev = null; // for (final Position curr : positions) { // state.insertAfter(prev, curr); // prev = curr; // } // // return state; // } // } // Path: src/test/java/com/github/liblevenshtein/transducer/MergeFunctionTest.java import org.testng.annotations.Test; import static org.assertj.core.api.Assertions.assertThat; import com.github.liblevenshtein.transducer.factory.PositionFactory; import com.github.liblevenshtein.transducer.factory.StateFactory; package com.github.liblevenshtein.transducer; public class MergeFunctionTest { private final StateFactory stateFactory = new StateFactory();
private final PositionFactory positionFactory = new PositionFactory();
universal-automata/liblevenshtein-java
src/main/java/com/github/liblevenshtein/transducer/PositionTransitionFunction.java
// Path: src/main/java/com/github/liblevenshtein/transducer/factory/PositionFactory.java // @NoArgsConstructor // public class PositionFactory implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Builds a dummy position. // * @return Dummy position. // */ // public Position build() { // return new Position(-1, -1); // } // // /** // * Builds a position vector for the standard, Levenshtein algorihtm. // * @param termIndex Current index of the spelling candidate. // * @param numErrors Number of accumulated errors at index {@code termIndex}. // * @return New position vector having index {@code termIndex} and error // * {@code numErrors}. // */ // public Position build(final int termIndex, final int numErrors) { // return new Position(termIndex, numErrors); // } // // /** // * Builds a position vector for the transposition and merge-and-split, // * Levenshtein algorihtms. // * @param termIndex Current index of the spelling candidate. // * @param numErrors Number of accumulated errors at index {@code termIndex}. // * @param isSpecial Either {@code 1} or {@code 0}, depending on whether the // * position is a special case (numErrors.g. a transposition position). // * @return New position vector having index {@code termIndex}, error // * {@code numErrors}, and special marker {@code isSpecial}. // */ // public Position build(final int termIndex, final int numErrors, final boolean isSpecial) { // if (isSpecial) { // return new SpecialPosition(termIndex, numErrors); // } // // return new Position(termIndex, numErrors); // } // } // // Path: src/main/java/com/github/liblevenshtein/transducer/factory/StateFactory.java // public class StateFactory implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Builds a new, Levenshtein state with the given position vectors. // * @param positions Array of position vectors to link into the state. // * @return New state having the position vectors. // */ // public State build(final Position... positions) { // final State state = new State(); // // Position prev = null; // for (final Position curr : positions) { // state.insertAfter(prev, curr); // prev = curr; // } // // return state; // } // }
import java.io.Serializable; import lombok.Setter; import com.github.liblevenshtein.transducer.factory.PositionFactory; import com.github.liblevenshtein.transducer.factory.StateFactory;
package com.github.liblevenshtein.transducer; /** * Implements common logic shared among the position-transition functions, which * for their specific algorithm take one of the positions in a state and a few * parameters, and return all posible positions leading from that one, under the * constraints of the given paramters and the Levenshtein algorithm. * @author Dylon Edwards * @since 2.1.0 */ @Setter public abstract class PositionTransitionFunction implements Serializable { private static final long serialVersionUID = 1L; /** * Builds and caches states for the transducer. */
// Path: src/main/java/com/github/liblevenshtein/transducer/factory/PositionFactory.java // @NoArgsConstructor // public class PositionFactory implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Builds a dummy position. // * @return Dummy position. // */ // public Position build() { // return new Position(-1, -1); // } // // /** // * Builds a position vector for the standard, Levenshtein algorihtm. // * @param termIndex Current index of the spelling candidate. // * @param numErrors Number of accumulated errors at index {@code termIndex}. // * @return New position vector having index {@code termIndex} and error // * {@code numErrors}. // */ // public Position build(final int termIndex, final int numErrors) { // return new Position(termIndex, numErrors); // } // // /** // * Builds a position vector for the transposition and merge-and-split, // * Levenshtein algorihtms. // * @param termIndex Current index of the spelling candidate. // * @param numErrors Number of accumulated errors at index {@code termIndex}. // * @param isSpecial Either {@code 1} or {@code 0}, depending on whether the // * position is a special case (numErrors.g. a transposition position). // * @return New position vector having index {@code termIndex}, error // * {@code numErrors}, and special marker {@code isSpecial}. // */ // public Position build(final int termIndex, final int numErrors, final boolean isSpecial) { // if (isSpecial) { // return new SpecialPosition(termIndex, numErrors); // } // // return new Position(termIndex, numErrors); // } // } // // Path: src/main/java/com/github/liblevenshtein/transducer/factory/StateFactory.java // public class StateFactory implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Builds a new, Levenshtein state with the given position vectors. // * @param positions Array of position vectors to link into the state. // * @return New state having the position vectors. // */ // public State build(final Position... positions) { // final State state = new State(); // // Position prev = null; // for (final Position curr : positions) { // state.insertAfter(prev, curr); // prev = curr; // } // // return state; // } // } // Path: src/main/java/com/github/liblevenshtein/transducer/PositionTransitionFunction.java import java.io.Serializable; import lombok.Setter; import com.github.liblevenshtein.transducer.factory.PositionFactory; import com.github.liblevenshtein.transducer.factory.StateFactory; package com.github.liblevenshtein.transducer; /** * Implements common logic shared among the position-transition functions, which * for their specific algorithm take one of the positions in a state and a few * parameters, and return all posible positions leading from that one, under the * constraints of the given paramters and the Levenshtein algorithm. * @author Dylon Edwards * @since 2.1.0 */ @Setter public abstract class PositionTransitionFunction implements Serializable { private static final long serialVersionUID = 1L; /** * Builds and caches states for the transducer. */
protected StateFactory stateFactory;
universal-automata/liblevenshtein-java
src/main/java/com/github/liblevenshtein/transducer/PositionTransitionFunction.java
// Path: src/main/java/com/github/liblevenshtein/transducer/factory/PositionFactory.java // @NoArgsConstructor // public class PositionFactory implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Builds a dummy position. // * @return Dummy position. // */ // public Position build() { // return new Position(-1, -1); // } // // /** // * Builds a position vector for the standard, Levenshtein algorihtm. // * @param termIndex Current index of the spelling candidate. // * @param numErrors Number of accumulated errors at index {@code termIndex}. // * @return New position vector having index {@code termIndex} and error // * {@code numErrors}. // */ // public Position build(final int termIndex, final int numErrors) { // return new Position(termIndex, numErrors); // } // // /** // * Builds a position vector for the transposition and merge-and-split, // * Levenshtein algorihtms. // * @param termIndex Current index of the spelling candidate. // * @param numErrors Number of accumulated errors at index {@code termIndex}. // * @param isSpecial Either {@code 1} or {@code 0}, depending on whether the // * position is a special case (numErrors.g. a transposition position). // * @return New position vector having index {@code termIndex}, error // * {@code numErrors}, and special marker {@code isSpecial}. // */ // public Position build(final int termIndex, final int numErrors, final boolean isSpecial) { // if (isSpecial) { // return new SpecialPosition(termIndex, numErrors); // } // // return new Position(termIndex, numErrors); // } // } // // Path: src/main/java/com/github/liblevenshtein/transducer/factory/StateFactory.java // public class StateFactory implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Builds a new, Levenshtein state with the given position vectors. // * @param positions Array of position vectors to link into the state. // * @return New state having the position vectors. // */ // public State build(final Position... positions) { // final State state = new State(); // // Position prev = null; // for (final Position curr : positions) { // state.insertAfter(prev, curr); // prev = curr; // } // // return state; // } // }
import java.io.Serializable; import lombok.Setter; import com.github.liblevenshtein.transducer.factory.PositionFactory; import com.github.liblevenshtein.transducer.factory.StateFactory;
package com.github.liblevenshtein.transducer; /** * Implements common logic shared among the position-transition functions, which * for their specific algorithm take one of the positions in a state and a few * parameters, and return all posible positions leading from that one, under the * constraints of the given paramters and the Levenshtein algorithm. * @author Dylon Edwards * @since 2.1.0 */ @Setter public abstract class PositionTransitionFunction implements Serializable { private static final long serialVersionUID = 1L; /** * Builds and caches states for the transducer. */ protected StateFactory stateFactory; /** * Builds and caches positions for states in the transducer. */
// Path: src/main/java/com/github/liblevenshtein/transducer/factory/PositionFactory.java // @NoArgsConstructor // public class PositionFactory implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Builds a dummy position. // * @return Dummy position. // */ // public Position build() { // return new Position(-1, -1); // } // // /** // * Builds a position vector for the standard, Levenshtein algorihtm. // * @param termIndex Current index of the spelling candidate. // * @param numErrors Number of accumulated errors at index {@code termIndex}. // * @return New position vector having index {@code termIndex} and error // * {@code numErrors}. // */ // public Position build(final int termIndex, final int numErrors) { // return new Position(termIndex, numErrors); // } // // /** // * Builds a position vector for the transposition and merge-and-split, // * Levenshtein algorihtms. // * @param termIndex Current index of the spelling candidate. // * @param numErrors Number of accumulated errors at index {@code termIndex}. // * @param isSpecial Either {@code 1} or {@code 0}, depending on whether the // * position is a special case (numErrors.g. a transposition position). // * @return New position vector having index {@code termIndex}, error // * {@code numErrors}, and special marker {@code isSpecial}. // */ // public Position build(final int termIndex, final int numErrors, final boolean isSpecial) { // if (isSpecial) { // return new SpecialPosition(termIndex, numErrors); // } // // return new Position(termIndex, numErrors); // } // } // // Path: src/main/java/com/github/liblevenshtein/transducer/factory/StateFactory.java // public class StateFactory implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Builds a new, Levenshtein state with the given position vectors. // * @param positions Array of position vectors to link into the state. // * @return New state having the position vectors. // */ // public State build(final Position... positions) { // final State state = new State(); // // Position prev = null; // for (final Position curr : positions) { // state.insertAfter(prev, curr); // prev = curr; // } // // return state; // } // } // Path: src/main/java/com/github/liblevenshtein/transducer/PositionTransitionFunction.java import java.io.Serializable; import lombok.Setter; import com.github.liblevenshtein.transducer.factory.PositionFactory; import com.github.liblevenshtein.transducer.factory.StateFactory; package com.github.liblevenshtein.transducer; /** * Implements common logic shared among the position-transition functions, which * for their specific algorithm take one of the positions in a state and a few * parameters, and return all posible positions leading from that one, under the * constraints of the given paramters and the Levenshtein algorithm. * @author Dylon Edwards * @since 2.1.0 */ @Setter public abstract class PositionTransitionFunction implements Serializable { private static final long serialVersionUID = 1L; /** * Builds and caches states for the transducer. */ protected StateFactory stateFactory; /** * Builds and caches positions for states in the transducer. */
protected PositionFactory positionFactory;
universal-automata/liblevenshtein-java
src/test/java/com/github/liblevenshtein/assertion/CandidateAssertions.java
// Path: src/main/java/com/github/liblevenshtein/distance/IDistance.java // public interface IDistance<Term> extends Serializable { // // /** // * Finds the distance between two terms, {@code v} and {@code w}. The distance // * between two terms is complemented by their similarity, which is determined // * by subtracting their distance from the maximum distance they may be apart. // * @param v Term to compare with {@code w} // * @param w Term to compare with {@code v} // * @return Distance between {@code v} and {@code w} // */ // int between(Term v, Term w); // } // // Path: src/main/java/com/github/liblevenshtein/transducer/Candidate.java // @Value // public class Candidate implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Candidate term from the dictionary automaton. // * @return Candidate term from the dictionary automaton. // */ // private final String term; // // /** // * Distance between the candidate term and the query term. // * @return Distance between the candidate term and the query term. // */ // private final int distance; // }
import org.assertj.core.api.AbstractAssert; import com.github.liblevenshtein.distance.IDistance; import com.github.liblevenshtein.transducer.Candidate;
package com.github.liblevenshtein.assertion; /** * AssertJ-style assertions for {@link Candidate}s. */ public class CandidateAssertions extends AbstractAssert<CandidateAssertions, Candidate> { /** * Constructs a new {@link Candidate} to assert-against. * @param actual {@link Candidate} to assert-against. */ public CandidateAssertions(final Candidate actual) { super(actual, CandidateAssertions.class); } /** * Builds a new {@link Candidate} to assert-against. * @param actual {@link Candidate} to assert-against. * @return A new {@link Candidate} to assert-against. */ public static CandidateAssertions assertThat(final Candidate actual) { return new CandidateAssertions(actual); } /** * Asserts that the actual distance is the expected distance from the query * term, as specified by the distance function. * @param distance Distance function for validation. * @param queryTerm Term whose distance from the spelling candidate is to be * determined. * @return This {@link CandidateAssertions} for fluency. * @throws AssertionError When the actual distance differs from what's * expected. */ public CandidateAssertions hasDistance(
// Path: src/main/java/com/github/liblevenshtein/distance/IDistance.java // public interface IDistance<Term> extends Serializable { // // /** // * Finds the distance between two terms, {@code v} and {@code w}. The distance // * between two terms is complemented by their similarity, which is determined // * by subtracting their distance from the maximum distance they may be apart. // * @param v Term to compare with {@code w} // * @param w Term to compare with {@code v} // * @return Distance between {@code v} and {@code w} // */ // int between(Term v, Term w); // } // // Path: src/main/java/com/github/liblevenshtein/transducer/Candidate.java // @Value // public class Candidate implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Candidate term from the dictionary automaton. // * @return Candidate term from the dictionary automaton. // */ // private final String term; // // /** // * Distance between the candidate term and the query term. // * @return Distance between the candidate term and the query term. // */ // private final int distance; // } // Path: src/test/java/com/github/liblevenshtein/assertion/CandidateAssertions.java import org.assertj.core.api.AbstractAssert; import com.github.liblevenshtein.distance.IDistance; import com.github.liblevenshtein.transducer.Candidate; package com.github.liblevenshtein.assertion; /** * AssertJ-style assertions for {@link Candidate}s. */ public class CandidateAssertions extends AbstractAssert<CandidateAssertions, Candidate> { /** * Constructs a new {@link Candidate} to assert-against. * @param actual {@link Candidate} to assert-against. */ public CandidateAssertions(final Candidate actual) { super(actual, CandidateAssertions.class); } /** * Builds a new {@link Candidate} to assert-against. * @param actual {@link Candidate} to assert-against. * @return A new {@link Candidate} to assert-against. */ public static CandidateAssertions assertThat(final Candidate actual) { return new CandidateAssertions(actual); } /** * Asserts that the actual distance is the expected distance from the query * term, as specified by the distance function. * @param distance Distance function for validation. * @param queryTerm Term whose distance from the spelling candidate is to be * determined. * @return This {@link CandidateAssertions} for fluency. * @throws AssertionError When the actual distance differs from what's * expected. */ public CandidateAssertions hasDistance(
final IDistance<String> distance,
universal-automata/liblevenshtein-java
src/test/java/com/github/liblevenshtein/assertion/SetAssertionsTest.java
// Path: src/test/java/com/github/liblevenshtein/assertion/SetAssertions.java // public static <Type> SetAssertions<Type> assertThat(final Set<Type> actual) { // return new SetAssertions<Type>(actual); // }
import java.util.Arrays; import java.util.HashSet; import java.util.Set; import org.testng.annotations.Test; import static com.github.liblevenshtein.assertion.SetAssertions.assertThat;
package com.github.liblevenshtein.assertion; public class SetAssertionsTest { @Test public void testContains() {
// Path: src/test/java/com/github/liblevenshtein/assertion/SetAssertions.java // public static <Type> SetAssertions<Type> assertThat(final Set<Type> actual) { // return new SetAssertions<Type>(actual); // } // Path: src/test/java/com/github/liblevenshtein/assertion/SetAssertionsTest.java import java.util.Arrays; import java.util.HashSet; import java.util.Set; import org.testng.annotations.Test; import static com.github.liblevenshtein.assertion.SetAssertions.assertThat; package com.github.liblevenshtein.assertion; public class SetAssertionsTest { @Test public void testContains() {
assertThat(set(1, 2, 3)).contains(2);
universal-automata/liblevenshtein-java
src/test/java/com/github/liblevenshtein/transducer/factory/CandidateFactoryTest.java
// Path: src/main/java/com/github/liblevenshtein/transducer/Candidate.java // @Value // public class Candidate implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Candidate term from the dictionary automaton. // * @return Candidate term from the dictionary automaton. // */ // private final String term; // // /** // * Distance between the candidate term and the query term. // * @return Distance between the candidate term and the query term. // */ // private final int distance; // }
import com.github.liblevenshtein.transducer.Candidate; import org.testng.annotations.Test; import static org.assertj.core.api.Assertions.assertThat; import lombok.val;
package com.github.liblevenshtein.transducer.factory; public class CandidateFactoryTest { private static final String FOO = "foo"; @Test public void testWithDistance() { val candidateFactory = new CandidateFactory.WithDistance();
// Path: src/main/java/com/github/liblevenshtein/transducer/Candidate.java // @Value // public class Candidate implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Candidate term from the dictionary automaton. // * @return Candidate term from the dictionary automaton. // */ // private final String term; // // /** // * Distance between the candidate term and the query term. // * @return Distance between the candidate term and the query term. // */ // private final int distance; // } // Path: src/test/java/com/github/liblevenshtein/transducer/factory/CandidateFactoryTest.java import com.github.liblevenshtein.transducer.Candidate; import org.testng.annotations.Test; import static org.assertj.core.api.Assertions.assertThat; import lombok.val; package com.github.liblevenshtein.transducer.factory; public class CandidateFactoryTest { private static final String FOO = "foo"; @Test public void testWithDistance() { val candidateFactory = new CandidateFactory.WithDistance();
final Candidate candidate = candidateFactory.build(FOO, 2);
universal-automata/liblevenshtein-java
src/test/java/com/github/liblevenshtein/transducer/StateTransitionFunctionTest.java
// Path: src/main/java/com/github/liblevenshtein/transducer/factory/PositionFactory.java // @NoArgsConstructor // public class PositionFactory implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Builds a dummy position. // * @return Dummy position. // */ // public Position build() { // return new Position(-1, -1); // } // // /** // * Builds a position vector for the standard, Levenshtein algorihtm. // * @param termIndex Current index of the spelling candidate. // * @param numErrors Number of accumulated errors at index {@code termIndex}. // * @return New position vector having index {@code termIndex} and error // * {@code numErrors}. // */ // public Position build(final int termIndex, final int numErrors) { // return new Position(termIndex, numErrors); // } // // /** // * Builds a position vector for the transposition and merge-and-split, // * Levenshtein algorihtms. // * @param termIndex Current index of the spelling candidate. // * @param numErrors Number of accumulated errors at index {@code termIndex}. // * @param isSpecial Either {@code 1} or {@code 0}, depending on whether the // * position is a special case (numErrors.g. a transposition position). // * @return New position vector having index {@code termIndex}, error // * {@code numErrors}, and special marker {@code isSpecial}. // */ // public Position build(final int termIndex, final int numErrors, final boolean isSpecial) { // if (isSpecial) { // return new SpecialPosition(termIndex, numErrors); // } // // return new Position(termIndex, numErrors); // } // } // // Path: src/main/java/com/github/liblevenshtein/transducer/factory/PositionTransitionFactory.java // @Setter // @NoArgsConstructor(access = AccessLevel.PROTECTED) // public abstract class PositionTransitionFactory implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Builds Levenshtein states. // */ // protected StateFactory stateFactory; // // /** // * Builds Levenshtein positions. // */ // protected PositionFactory positionFactory; // // /** // * Builds a new position-transition function. // * @return New position-transition function. // */ // public abstract PositionTransitionFunction build(); // // /** // * Builds position-transition functions for standard, Levenshtein states. // * @author Dylon Edwards // * @since 2.1.0 // */ // public static class ForStandardPositions extends PositionTransitionFactory { // // private static final long serialVersionUID = 1L; // // /** // * {@inheritDoc} // */ // @Override // public PositionTransitionFunction build() { // return new StandardPositionTransitionFunction() // .stateFactory(stateFactory) // .positionFactory(positionFactory); // } // } // // /** // * Builds position-transition functions for transposition, Levenshtein states. // * @author Dylon Edwards // * @since 2.1.0 // */ // public static class ForTranspositionPositions extends PositionTransitionFactory { // // private static final long serialVersionUID = 1L; // // /** // * {@inheritDoc} // */ // @Override // public PositionTransitionFunction build() { // return new TranspositionPositionTransitionFunction() // .stateFactory(stateFactory) // .positionFactory(positionFactory); // } // } // // /** // * Builds position-transition functions for merge-and-split, Levenshtein states. // * @author Dylon Edwards // * @since 2.1.0 // */ // public static class ForMergeAndSplitPositions extends PositionTransitionFactory { // // private static final long serialVersionUID = 1L; // // /** // * {@inheritDoc} // */ // @Override // public PositionTransitionFunction build() { // return new MergeAndSplitPositionTransitionFunction() // .stateFactory(stateFactory) // .positionFactory(positionFactory); // } // } // } // // Path: src/main/java/com/github/liblevenshtein/transducer/factory/StateFactory.java // public class StateFactory implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Builds a new, Levenshtein state with the given position vectors. // * @param positions Array of position vectors to link into the state. // * @return New state having the position vectors. // */ // public State build(final Position... positions) { // final State state = new State(); // // Position prev = null; // for (final Position curr : positions) { // state.insertAfter(prev, curr); // prev = curr; // } // // return state; // } // } // // Path: src/test/java/com/github/liblevenshtein/assertion/StateTransitionFunctionAssertions.java // public static StateTransitionFunctionAssertions assertThat( // final StateTransitionFunction actual) { // return new StateTransitionFunctionAssertions(actual); // }
import java.util.Arrays; import org.testng.annotations.BeforeTest; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import com.github.liblevenshtein.transducer.factory.PositionFactory; import com.github.liblevenshtein.transducer.factory.PositionTransitionFactory; import com.github.liblevenshtein.transducer.factory.StateFactory; import static com.github.liblevenshtein.assertion.StateTransitionFunctionAssertions.assertThat;
package com.github.liblevenshtein.transducer; /** * These tests were taken from the transition tables on page 29 of "Fast String * Correction with Levenshtein Automata". */ public class StateTransitionFunctionTest { private static final int N = 1; private static final int W = 5;
// Path: src/main/java/com/github/liblevenshtein/transducer/factory/PositionFactory.java // @NoArgsConstructor // public class PositionFactory implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Builds a dummy position. // * @return Dummy position. // */ // public Position build() { // return new Position(-1, -1); // } // // /** // * Builds a position vector for the standard, Levenshtein algorihtm. // * @param termIndex Current index of the spelling candidate. // * @param numErrors Number of accumulated errors at index {@code termIndex}. // * @return New position vector having index {@code termIndex} and error // * {@code numErrors}. // */ // public Position build(final int termIndex, final int numErrors) { // return new Position(termIndex, numErrors); // } // // /** // * Builds a position vector for the transposition and merge-and-split, // * Levenshtein algorihtms. // * @param termIndex Current index of the spelling candidate. // * @param numErrors Number of accumulated errors at index {@code termIndex}. // * @param isSpecial Either {@code 1} or {@code 0}, depending on whether the // * position is a special case (numErrors.g. a transposition position). // * @return New position vector having index {@code termIndex}, error // * {@code numErrors}, and special marker {@code isSpecial}. // */ // public Position build(final int termIndex, final int numErrors, final boolean isSpecial) { // if (isSpecial) { // return new SpecialPosition(termIndex, numErrors); // } // // return new Position(termIndex, numErrors); // } // } // // Path: src/main/java/com/github/liblevenshtein/transducer/factory/PositionTransitionFactory.java // @Setter // @NoArgsConstructor(access = AccessLevel.PROTECTED) // public abstract class PositionTransitionFactory implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Builds Levenshtein states. // */ // protected StateFactory stateFactory; // // /** // * Builds Levenshtein positions. // */ // protected PositionFactory positionFactory; // // /** // * Builds a new position-transition function. // * @return New position-transition function. // */ // public abstract PositionTransitionFunction build(); // // /** // * Builds position-transition functions for standard, Levenshtein states. // * @author Dylon Edwards // * @since 2.1.0 // */ // public static class ForStandardPositions extends PositionTransitionFactory { // // private static final long serialVersionUID = 1L; // // /** // * {@inheritDoc} // */ // @Override // public PositionTransitionFunction build() { // return new StandardPositionTransitionFunction() // .stateFactory(stateFactory) // .positionFactory(positionFactory); // } // } // // /** // * Builds position-transition functions for transposition, Levenshtein states. // * @author Dylon Edwards // * @since 2.1.0 // */ // public static class ForTranspositionPositions extends PositionTransitionFactory { // // private static final long serialVersionUID = 1L; // // /** // * {@inheritDoc} // */ // @Override // public PositionTransitionFunction build() { // return new TranspositionPositionTransitionFunction() // .stateFactory(stateFactory) // .positionFactory(positionFactory); // } // } // // /** // * Builds position-transition functions for merge-and-split, Levenshtein states. // * @author Dylon Edwards // * @since 2.1.0 // */ // public static class ForMergeAndSplitPositions extends PositionTransitionFactory { // // private static final long serialVersionUID = 1L; // // /** // * {@inheritDoc} // */ // @Override // public PositionTransitionFunction build() { // return new MergeAndSplitPositionTransitionFunction() // .stateFactory(stateFactory) // .positionFactory(positionFactory); // } // } // } // // Path: src/main/java/com/github/liblevenshtein/transducer/factory/StateFactory.java // public class StateFactory implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Builds a new, Levenshtein state with the given position vectors. // * @param positions Array of position vectors to link into the state. // * @return New state having the position vectors. // */ // public State build(final Position... positions) { // final State state = new State(); // // Position prev = null; // for (final Position curr : positions) { // state.insertAfter(prev, curr); // prev = curr; // } // // return state; // } // } // // Path: src/test/java/com/github/liblevenshtein/assertion/StateTransitionFunctionAssertions.java // public static StateTransitionFunctionAssertions assertThat( // final StateTransitionFunction actual) { // return new StateTransitionFunctionAssertions(actual); // } // Path: src/test/java/com/github/liblevenshtein/transducer/StateTransitionFunctionTest.java import java.util.Arrays; import org.testng.annotations.BeforeTest; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import com.github.liblevenshtein.transducer.factory.PositionFactory; import com.github.liblevenshtein.transducer.factory.PositionTransitionFactory; import com.github.liblevenshtein.transducer.factory.StateFactory; import static com.github.liblevenshtein.assertion.StateTransitionFunctionAssertions.assertThat; package com.github.liblevenshtein.transducer; /** * These tests were taken from the transition tables on page 29 of "Fast String * Correction with Levenshtein Automata". */ public class StateTransitionFunctionTest { private static final int N = 1; private static final int W = 5;
private final PositionFactory positionFactory = new PositionFactory();
universal-automata/liblevenshtein-java
src/test/java/com/github/liblevenshtein/transducer/StateTransitionFunctionTest.java
// Path: src/main/java/com/github/liblevenshtein/transducer/factory/PositionFactory.java // @NoArgsConstructor // public class PositionFactory implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Builds a dummy position. // * @return Dummy position. // */ // public Position build() { // return new Position(-1, -1); // } // // /** // * Builds a position vector for the standard, Levenshtein algorihtm. // * @param termIndex Current index of the spelling candidate. // * @param numErrors Number of accumulated errors at index {@code termIndex}. // * @return New position vector having index {@code termIndex} and error // * {@code numErrors}. // */ // public Position build(final int termIndex, final int numErrors) { // return new Position(termIndex, numErrors); // } // // /** // * Builds a position vector for the transposition and merge-and-split, // * Levenshtein algorihtms. // * @param termIndex Current index of the spelling candidate. // * @param numErrors Number of accumulated errors at index {@code termIndex}. // * @param isSpecial Either {@code 1} or {@code 0}, depending on whether the // * position is a special case (numErrors.g. a transposition position). // * @return New position vector having index {@code termIndex}, error // * {@code numErrors}, and special marker {@code isSpecial}. // */ // public Position build(final int termIndex, final int numErrors, final boolean isSpecial) { // if (isSpecial) { // return new SpecialPosition(termIndex, numErrors); // } // // return new Position(termIndex, numErrors); // } // } // // Path: src/main/java/com/github/liblevenshtein/transducer/factory/PositionTransitionFactory.java // @Setter // @NoArgsConstructor(access = AccessLevel.PROTECTED) // public abstract class PositionTransitionFactory implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Builds Levenshtein states. // */ // protected StateFactory stateFactory; // // /** // * Builds Levenshtein positions. // */ // protected PositionFactory positionFactory; // // /** // * Builds a new position-transition function. // * @return New position-transition function. // */ // public abstract PositionTransitionFunction build(); // // /** // * Builds position-transition functions for standard, Levenshtein states. // * @author Dylon Edwards // * @since 2.1.0 // */ // public static class ForStandardPositions extends PositionTransitionFactory { // // private static final long serialVersionUID = 1L; // // /** // * {@inheritDoc} // */ // @Override // public PositionTransitionFunction build() { // return new StandardPositionTransitionFunction() // .stateFactory(stateFactory) // .positionFactory(positionFactory); // } // } // // /** // * Builds position-transition functions for transposition, Levenshtein states. // * @author Dylon Edwards // * @since 2.1.0 // */ // public static class ForTranspositionPositions extends PositionTransitionFactory { // // private static final long serialVersionUID = 1L; // // /** // * {@inheritDoc} // */ // @Override // public PositionTransitionFunction build() { // return new TranspositionPositionTransitionFunction() // .stateFactory(stateFactory) // .positionFactory(positionFactory); // } // } // // /** // * Builds position-transition functions for merge-and-split, Levenshtein states. // * @author Dylon Edwards // * @since 2.1.0 // */ // public static class ForMergeAndSplitPositions extends PositionTransitionFactory { // // private static final long serialVersionUID = 1L; // // /** // * {@inheritDoc} // */ // @Override // public PositionTransitionFunction build() { // return new MergeAndSplitPositionTransitionFunction() // .stateFactory(stateFactory) // .positionFactory(positionFactory); // } // } // } // // Path: src/main/java/com/github/liblevenshtein/transducer/factory/StateFactory.java // public class StateFactory implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Builds a new, Levenshtein state with the given position vectors. // * @param positions Array of position vectors to link into the state. // * @return New state having the position vectors. // */ // public State build(final Position... positions) { // final State state = new State(); // // Position prev = null; // for (final Position curr : positions) { // state.insertAfter(prev, curr); // prev = curr; // } // // return state; // } // } // // Path: src/test/java/com/github/liblevenshtein/assertion/StateTransitionFunctionAssertions.java // public static StateTransitionFunctionAssertions assertThat( // final StateTransitionFunction actual) { // return new StateTransitionFunctionAssertions(actual); // }
import java.util.Arrays; import org.testng.annotations.BeforeTest; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import com.github.liblevenshtein.transducer.factory.PositionFactory; import com.github.liblevenshtein.transducer.factory.PositionTransitionFactory; import com.github.liblevenshtein.transducer.factory.StateFactory; import static com.github.liblevenshtein.assertion.StateTransitionFunctionAssertions.assertThat;
package com.github.liblevenshtein.transducer; /** * These tests were taken from the transition tables on page 29 of "Fast String * Correction with Levenshtein Automata". */ public class StateTransitionFunctionTest { private static final int N = 1; private static final int W = 5; private final PositionFactory positionFactory = new PositionFactory();
// Path: src/main/java/com/github/liblevenshtein/transducer/factory/PositionFactory.java // @NoArgsConstructor // public class PositionFactory implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Builds a dummy position. // * @return Dummy position. // */ // public Position build() { // return new Position(-1, -1); // } // // /** // * Builds a position vector for the standard, Levenshtein algorihtm. // * @param termIndex Current index of the spelling candidate. // * @param numErrors Number of accumulated errors at index {@code termIndex}. // * @return New position vector having index {@code termIndex} and error // * {@code numErrors}. // */ // public Position build(final int termIndex, final int numErrors) { // return new Position(termIndex, numErrors); // } // // /** // * Builds a position vector for the transposition and merge-and-split, // * Levenshtein algorihtms. // * @param termIndex Current index of the spelling candidate. // * @param numErrors Number of accumulated errors at index {@code termIndex}. // * @param isSpecial Either {@code 1} or {@code 0}, depending on whether the // * position is a special case (numErrors.g. a transposition position). // * @return New position vector having index {@code termIndex}, error // * {@code numErrors}, and special marker {@code isSpecial}. // */ // public Position build(final int termIndex, final int numErrors, final boolean isSpecial) { // if (isSpecial) { // return new SpecialPosition(termIndex, numErrors); // } // // return new Position(termIndex, numErrors); // } // } // // Path: src/main/java/com/github/liblevenshtein/transducer/factory/PositionTransitionFactory.java // @Setter // @NoArgsConstructor(access = AccessLevel.PROTECTED) // public abstract class PositionTransitionFactory implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Builds Levenshtein states. // */ // protected StateFactory stateFactory; // // /** // * Builds Levenshtein positions. // */ // protected PositionFactory positionFactory; // // /** // * Builds a new position-transition function. // * @return New position-transition function. // */ // public abstract PositionTransitionFunction build(); // // /** // * Builds position-transition functions for standard, Levenshtein states. // * @author Dylon Edwards // * @since 2.1.0 // */ // public static class ForStandardPositions extends PositionTransitionFactory { // // private static final long serialVersionUID = 1L; // // /** // * {@inheritDoc} // */ // @Override // public PositionTransitionFunction build() { // return new StandardPositionTransitionFunction() // .stateFactory(stateFactory) // .positionFactory(positionFactory); // } // } // // /** // * Builds position-transition functions for transposition, Levenshtein states. // * @author Dylon Edwards // * @since 2.1.0 // */ // public static class ForTranspositionPositions extends PositionTransitionFactory { // // private static final long serialVersionUID = 1L; // // /** // * {@inheritDoc} // */ // @Override // public PositionTransitionFunction build() { // return new TranspositionPositionTransitionFunction() // .stateFactory(stateFactory) // .positionFactory(positionFactory); // } // } // // /** // * Builds position-transition functions for merge-and-split, Levenshtein states. // * @author Dylon Edwards // * @since 2.1.0 // */ // public static class ForMergeAndSplitPositions extends PositionTransitionFactory { // // private static final long serialVersionUID = 1L; // // /** // * {@inheritDoc} // */ // @Override // public PositionTransitionFunction build() { // return new MergeAndSplitPositionTransitionFunction() // .stateFactory(stateFactory) // .positionFactory(positionFactory); // } // } // } // // Path: src/main/java/com/github/liblevenshtein/transducer/factory/StateFactory.java // public class StateFactory implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Builds a new, Levenshtein state with the given position vectors. // * @param positions Array of position vectors to link into the state. // * @return New state having the position vectors. // */ // public State build(final Position... positions) { // final State state = new State(); // // Position prev = null; // for (final Position curr : positions) { // state.insertAfter(prev, curr); // prev = curr; // } // // return state; // } // } // // Path: src/test/java/com/github/liblevenshtein/assertion/StateTransitionFunctionAssertions.java // public static StateTransitionFunctionAssertions assertThat( // final StateTransitionFunction actual) { // return new StateTransitionFunctionAssertions(actual); // } // Path: src/test/java/com/github/liblevenshtein/transducer/StateTransitionFunctionTest.java import java.util.Arrays; import org.testng.annotations.BeforeTest; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import com.github.liblevenshtein.transducer.factory.PositionFactory; import com.github.liblevenshtein.transducer.factory.PositionTransitionFactory; import com.github.liblevenshtein.transducer.factory.StateFactory; import static com.github.liblevenshtein.assertion.StateTransitionFunctionAssertions.assertThat; package com.github.liblevenshtein.transducer; /** * These tests were taken from the transition tables on page 29 of "Fast String * Correction with Levenshtein Automata". */ public class StateTransitionFunctionTest { private static final int N = 1; private static final int W = 5; private final PositionFactory positionFactory = new PositionFactory();
private final StateFactory stateFactory = new StateFactory();
universal-automata/liblevenshtein-java
src/test/java/com/github/liblevenshtein/transducer/StateTransitionFunctionTest.java
// Path: src/main/java/com/github/liblevenshtein/transducer/factory/PositionFactory.java // @NoArgsConstructor // public class PositionFactory implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Builds a dummy position. // * @return Dummy position. // */ // public Position build() { // return new Position(-1, -1); // } // // /** // * Builds a position vector for the standard, Levenshtein algorihtm. // * @param termIndex Current index of the spelling candidate. // * @param numErrors Number of accumulated errors at index {@code termIndex}. // * @return New position vector having index {@code termIndex} and error // * {@code numErrors}. // */ // public Position build(final int termIndex, final int numErrors) { // return new Position(termIndex, numErrors); // } // // /** // * Builds a position vector for the transposition and merge-and-split, // * Levenshtein algorihtms. // * @param termIndex Current index of the spelling candidate. // * @param numErrors Number of accumulated errors at index {@code termIndex}. // * @param isSpecial Either {@code 1} or {@code 0}, depending on whether the // * position is a special case (numErrors.g. a transposition position). // * @return New position vector having index {@code termIndex}, error // * {@code numErrors}, and special marker {@code isSpecial}. // */ // public Position build(final int termIndex, final int numErrors, final boolean isSpecial) { // if (isSpecial) { // return new SpecialPosition(termIndex, numErrors); // } // // return new Position(termIndex, numErrors); // } // } // // Path: src/main/java/com/github/liblevenshtein/transducer/factory/PositionTransitionFactory.java // @Setter // @NoArgsConstructor(access = AccessLevel.PROTECTED) // public abstract class PositionTransitionFactory implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Builds Levenshtein states. // */ // protected StateFactory stateFactory; // // /** // * Builds Levenshtein positions. // */ // protected PositionFactory positionFactory; // // /** // * Builds a new position-transition function. // * @return New position-transition function. // */ // public abstract PositionTransitionFunction build(); // // /** // * Builds position-transition functions for standard, Levenshtein states. // * @author Dylon Edwards // * @since 2.1.0 // */ // public static class ForStandardPositions extends PositionTransitionFactory { // // private static final long serialVersionUID = 1L; // // /** // * {@inheritDoc} // */ // @Override // public PositionTransitionFunction build() { // return new StandardPositionTransitionFunction() // .stateFactory(stateFactory) // .positionFactory(positionFactory); // } // } // // /** // * Builds position-transition functions for transposition, Levenshtein states. // * @author Dylon Edwards // * @since 2.1.0 // */ // public static class ForTranspositionPositions extends PositionTransitionFactory { // // private static final long serialVersionUID = 1L; // // /** // * {@inheritDoc} // */ // @Override // public PositionTransitionFunction build() { // return new TranspositionPositionTransitionFunction() // .stateFactory(stateFactory) // .positionFactory(positionFactory); // } // } // // /** // * Builds position-transition functions for merge-and-split, Levenshtein states. // * @author Dylon Edwards // * @since 2.1.0 // */ // public static class ForMergeAndSplitPositions extends PositionTransitionFactory { // // private static final long serialVersionUID = 1L; // // /** // * {@inheritDoc} // */ // @Override // public PositionTransitionFunction build() { // return new MergeAndSplitPositionTransitionFunction() // .stateFactory(stateFactory) // .positionFactory(positionFactory); // } // } // } // // Path: src/main/java/com/github/liblevenshtein/transducer/factory/StateFactory.java // public class StateFactory implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Builds a new, Levenshtein state with the given position vectors. // * @param positions Array of position vectors to link into the state. // * @return New state having the position vectors. // */ // public State build(final Position... positions) { // final State state = new State(); // // Position prev = null; // for (final Position curr : positions) { // state.insertAfter(prev, curr); // prev = curr; // } // // return state; // } // } // // Path: src/test/java/com/github/liblevenshtein/assertion/StateTransitionFunctionAssertions.java // public static StateTransitionFunctionAssertions assertThat( // final StateTransitionFunction actual) { // return new StateTransitionFunctionAssertions(actual); // }
import java.util.Arrays; import org.testng.annotations.BeforeTest; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import com.github.liblevenshtein.transducer.factory.PositionFactory; import com.github.liblevenshtein.transducer.factory.PositionTransitionFactory; import com.github.liblevenshtein.transducer.factory.StateFactory; import static com.github.liblevenshtein.assertion.StateTransitionFunctionAssertions.assertThat;
package com.github.liblevenshtein.transducer; /** * These tests were taken from the transition tables on page 29 of "Fast String * Correction with Levenshtein Automata". */ public class StateTransitionFunctionTest { private static final int N = 1; private static final int W = 5; private final PositionFactory positionFactory = new PositionFactory(); private final StateFactory stateFactory = new StateFactory();
// Path: src/main/java/com/github/liblevenshtein/transducer/factory/PositionFactory.java // @NoArgsConstructor // public class PositionFactory implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Builds a dummy position. // * @return Dummy position. // */ // public Position build() { // return new Position(-1, -1); // } // // /** // * Builds a position vector for the standard, Levenshtein algorihtm. // * @param termIndex Current index of the spelling candidate. // * @param numErrors Number of accumulated errors at index {@code termIndex}. // * @return New position vector having index {@code termIndex} and error // * {@code numErrors}. // */ // public Position build(final int termIndex, final int numErrors) { // return new Position(termIndex, numErrors); // } // // /** // * Builds a position vector for the transposition and merge-and-split, // * Levenshtein algorihtms. // * @param termIndex Current index of the spelling candidate. // * @param numErrors Number of accumulated errors at index {@code termIndex}. // * @param isSpecial Either {@code 1} or {@code 0}, depending on whether the // * position is a special case (numErrors.g. a transposition position). // * @return New position vector having index {@code termIndex}, error // * {@code numErrors}, and special marker {@code isSpecial}. // */ // public Position build(final int termIndex, final int numErrors, final boolean isSpecial) { // if (isSpecial) { // return new SpecialPosition(termIndex, numErrors); // } // // return new Position(termIndex, numErrors); // } // } // // Path: src/main/java/com/github/liblevenshtein/transducer/factory/PositionTransitionFactory.java // @Setter // @NoArgsConstructor(access = AccessLevel.PROTECTED) // public abstract class PositionTransitionFactory implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Builds Levenshtein states. // */ // protected StateFactory stateFactory; // // /** // * Builds Levenshtein positions. // */ // protected PositionFactory positionFactory; // // /** // * Builds a new position-transition function. // * @return New position-transition function. // */ // public abstract PositionTransitionFunction build(); // // /** // * Builds position-transition functions for standard, Levenshtein states. // * @author Dylon Edwards // * @since 2.1.0 // */ // public static class ForStandardPositions extends PositionTransitionFactory { // // private static final long serialVersionUID = 1L; // // /** // * {@inheritDoc} // */ // @Override // public PositionTransitionFunction build() { // return new StandardPositionTransitionFunction() // .stateFactory(stateFactory) // .positionFactory(positionFactory); // } // } // // /** // * Builds position-transition functions for transposition, Levenshtein states. // * @author Dylon Edwards // * @since 2.1.0 // */ // public static class ForTranspositionPositions extends PositionTransitionFactory { // // private static final long serialVersionUID = 1L; // // /** // * {@inheritDoc} // */ // @Override // public PositionTransitionFunction build() { // return new TranspositionPositionTransitionFunction() // .stateFactory(stateFactory) // .positionFactory(positionFactory); // } // } // // /** // * Builds position-transition functions for merge-and-split, Levenshtein states. // * @author Dylon Edwards // * @since 2.1.0 // */ // public static class ForMergeAndSplitPositions extends PositionTransitionFactory { // // private static final long serialVersionUID = 1L; // // /** // * {@inheritDoc} // */ // @Override // public PositionTransitionFunction build() { // return new MergeAndSplitPositionTransitionFunction() // .stateFactory(stateFactory) // .positionFactory(positionFactory); // } // } // } // // Path: src/main/java/com/github/liblevenshtein/transducer/factory/StateFactory.java // public class StateFactory implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Builds a new, Levenshtein state with the given position vectors. // * @param positions Array of position vectors to link into the state. // * @return New state having the position vectors. // */ // public State build(final Position... positions) { // final State state = new State(); // // Position prev = null; // for (final Position curr : positions) { // state.insertAfter(prev, curr); // prev = curr; // } // // return state; // } // } // // Path: src/test/java/com/github/liblevenshtein/assertion/StateTransitionFunctionAssertions.java // public static StateTransitionFunctionAssertions assertThat( // final StateTransitionFunction actual) { // return new StateTransitionFunctionAssertions(actual); // } // Path: src/test/java/com/github/liblevenshtein/transducer/StateTransitionFunctionTest.java import java.util.Arrays; import org.testng.annotations.BeforeTest; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import com.github.liblevenshtein.transducer.factory.PositionFactory; import com.github.liblevenshtein.transducer.factory.PositionTransitionFactory; import com.github.liblevenshtein.transducer.factory.StateFactory; import static com.github.liblevenshtein.assertion.StateTransitionFunctionAssertions.assertThat; package com.github.liblevenshtein.transducer; /** * These tests were taken from the transition tables on page 29 of "Fast String * Correction with Levenshtein Automata". */ public class StateTransitionFunctionTest { private static final int N = 1; private static final int W = 5; private final PositionFactory positionFactory = new PositionFactory(); private final StateFactory stateFactory = new StateFactory();
private final PositionTransitionFactory transitionFactory =
universal-automata/liblevenshtein-java
src/test/java/com/github/liblevenshtein/assertion/IteratorAssertionsTest.java
// Path: src/test/java/com/github/liblevenshtein/assertion/IteratorAssertions.java // public static <Type> IteratorAssertions<Type> assertThat( // final Iterator<Type> actual) { // return new IteratorAssertions<>(actual); // }
import java.util.Arrays; import java.util.Iterator; import org.testng.annotations.Test; import static com.github.liblevenshtein.assertion.IteratorAssertions.assertThat;
package com.github.liblevenshtein.assertion; public class IteratorAssertionsTest { private static final String FOO = "foo"; private static final String BAR = "bar"; private static final String BAZ = "baz"; private static final String QUX = "qux"; @Test public void testOperations() {
// Path: src/test/java/com/github/liblevenshtein/assertion/IteratorAssertions.java // public static <Type> IteratorAssertions<Type> assertThat( // final Iterator<Type> actual) { // return new IteratorAssertions<>(actual); // } // Path: src/test/java/com/github/liblevenshtein/assertion/IteratorAssertionsTest.java import java.util.Arrays; import java.util.Iterator; import org.testng.annotations.Test; import static com.github.liblevenshtein.assertion.IteratorAssertions.assertThat; package com.github.liblevenshtein.assertion; public class IteratorAssertionsTest { private static final String FOO = "foo"; private static final String BAR = "bar"; private static final String BAZ = "baz"; private static final String QUX = "qux"; @Test public void testOperations() {
assertThat(iter(FOO, BAR, BAZ))
universal-automata/liblevenshtein-java
src/test/java/com/github/liblevenshtein/transducer/SpecialPositionDistanceFunctionTest.java
// Path: src/main/java/com/github/liblevenshtein/transducer/factory/PositionFactory.java // @NoArgsConstructor // public class PositionFactory implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Builds a dummy position. // * @return Dummy position. // */ // public Position build() { // return new Position(-1, -1); // } // // /** // * Builds a position vector for the standard, Levenshtein algorihtm. // * @param termIndex Current index of the spelling candidate. // * @param numErrors Number of accumulated errors at index {@code termIndex}. // * @return New position vector having index {@code termIndex} and error // * {@code numErrors}. // */ // public Position build(final int termIndex, final int numErrors) { // return new Position(termIndex, numErrors); // } // // /** // * Builds a position vector for the transposition and merge-and-split, // * Levenshtein algorihtms. // * @param termIndex Current index of the spelling candidate. // * @param numErrors Number of accumulated errors at index {@code termIndex}. // * @param isSpecial Either {@code 1} or {@code 0}, depending on whether the // * position is a special case (numErrors.g. a transposition position). // * @return New position vector having index {@code termIndex}, error // * {@code numErrors}, and special marker {@code isSpecial}. // */ // public Position build(final int termIndex, final int numErrors, final boolean isSpecial) { // if (isSpecial) { // return new SpecialPosition(termIndex, numErrors); // } // // return new Position(termIndex, numErrors); // } // } // // Path: src/main/java/com/github/liblevenshtein/transducer/factory/StateFactory.java // public class StateFactory implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Builds a new, Levenshtein state with the given position vectors. // * @param positions Array of position vectors to link into the state. // * @return New state having the position vectors. // */ // public State build(final Position... positions) { // final State state = new State(); // // Position prev = null; // for (final Position curr : positions) { // state.insertAfter(prev, curr); // prev = curr; // } // // return state; // } // } // // Path: src/test/java/com/github/liblevenshtein/assertion/DistanceFunctionAssertions.java // public static DistanceFunctionAssertions assertThat(final DistanceFunction actual) { // return new DistanceFunctionAssertions(actual); // }
import org.testng.annotations.Test; import lombok.val; import com.github.liblevenshtein.transducer.factory.PositionFactory; import com.github.liblevenshtein.transducer.factory.StateFactory; import static com.github.liblevenshtein.assertion.DistanceFunctionAssertions.assertThat;
package com.github.liblevenshtein.transducer; public class SpecialPositionDistanceFunctionTest { @Test public void testAt() {
// Path: src/main/java/com/github/liblevenshtein/transducer/factory/PositionFactory.java // @NoArgsConstructor // public class PositionFactory implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Builds a dummy position. // * @return Dummy position. // */ // public Position build() { // return new Position(-1, -1); // } // // /** // * Builds a position vector for the standard, Levenshtein algorihtm. // * @param termIndex Current index of the spelling candidate. // * @param numErrors Number of accumulated errors at index {@code termIndex}. // * @return New position vector having index {@code termIndex} and error // * {@code numErrors}. // */ // public Position build(final int termIndex, final int numErrors) { // return new Position(termIndex, numErrors); // } // // /** // * Builds a position vector for the transposition and merge-and-split, // * Levenshtein algorihtms. // * @param termIndex Current index of the spelling candidate. // * @param numErrors Number of accumulated errors at index {@code termIndex}. // * @param isSpecial Either {@code 1} or {@code 0}, depending on whether the // * position is a special case (numErrors.g. a transposition position). // * @return New position vector having index {@code termIndex}, error // * {@code numErrors}, and special marker {@code isSpecial}. // */ // public Position build(final int termIndex, final int numErrors, final boolean isSpecial) { // if (isSpecial) { // return new SpecialPosition(termIndex, numErrors); // } // // return new Position(termIndex, numErrors); // } // } // // Path: src/main/java/com/github/liblevenshtein/transducer/factory/StateFactory.java // public class StateFactory implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Builds a new, Levenshtein state with the given position vectors. // * @param positions Array of position vectors to link into the state. // * @return New state having the position vectors. // */ // public State build(final Position... positions) { // final State state = new State(); // // Position prev = null; // for (final Position curr : positions) { // state.insertAfter(prev, curr); // prev = curr; // } // // return state; // } // } // // Path: src/test/java/com/github/liblevenshtein/assertion/DistanceFunctionAssertions.java // public static DistanceFunctionAssertions assertThat(final DistanceFunction actual) { // return new DistanceFunctionAssertions(actual); // } // Path: src/test/java/com/github/liblevenshtein/transducer/SpecialPositionDistanceFunctionTest.java import org.testng.annotations.Test; import lombok.val; import com.github.liblevenshtein.transducer.factory.PositionFactory; import com.github.liblevenshtein.transducer.factory.StateFactory; import static com.github.liblevenshtein.assertion.DistanceFunctionAssertions.assertThat; package com.github.liblevenshtein.transducer; public class SpecialPositionDistanceFunctionTest { @Test public void testAt() {
val stateFactory = new StateFactory();
universal-automata/liblevenshtein-java
src/test/java/com/github/liblevenshtein/transducer/SpecialPositionDistanceFunctionTest.java
// Path: src/main/java/com/github/liblevenshtein/transducer/factory/PositionFactory.java // @NoArgsConstructor // public class PositionFactory implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Builds a dummy position. // * @return Dummy position. // */ // public Position build() { // return new Position(-1, -1); // } // // /** // * Builds a position vector for the standard, Levenshtein algorihtm. // * @param termIndex Current index of the spelling candidate. // * @param numErrors Number of accumulated errors at index {@code termIndex}. // * @return New position vector having index {@code termIndex} and error // * {@code numErrors}. // */ // public Position build(final int termIndex, final int numErrors) { // return new Position(termIndex, numErrors); // } // // /** // * Builds a position vector for the transposition and merge-and-split, // * Levenshtein algorihtms. // * @param termIndex Current index of the spelling candidate. // * @param numErrors Number of accumulated errors at index {@code termIndex}. // * @param isSpecial Either {@code 1} or {@code 0}, depending on whether the // * position is a special case (numErrors.g. a transposition position). // * @return New position vector having index {@code termIndex}, error // * {@code numErrors}, and special marker {@code isSpecial}. // */ // public Position build(final int termIndex, final int numErrors, final boolean isSpecial) { // if (isSpecial) { // return new SpecialPosition(termIndex, numErrors); // } // // return new Position(termIndex, numErrors); // } // } // // Path: src/main/java/com/github/liblevenshtein/transducer/factory/StateFactory.java // public class StateFactory implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Builds a new, Levenshtein state with the given position vectors. // * @param positions Array of position vectors to link into the state. // * @return New state having the position vectors. // */ // public State build(final Position... positions) { // final State state = new State(); // // Position prev = null; // for (final Position curr : positions) { // state.insertAfter(prev, curr); // prev = curr; // } // // return state; // } // } // // Path: src/test/java/com/github/liblevenshtein/assertion/DistanceFunctionAssertions.java // public static DistanceFunctionAssertions assertThat(final DistanceFunction actual) { // return new DistanceFunctionAssertions(actual); // }
import org.testng.annotations.Test; import lombok.val; import com.github.liblevenshtein.transducer.factory.PositionFactory; import com.github.liblevenshtein.transducer.factory.StateFactory; import static com.github.liblevenshtein.assertion.DistanceFunctionAssertions.assertThat;
package com.github.liblevenshtein.transducer; public class SpecialPositionDistanceFunctionTest { @Test public void testAt() { val stateFactory = new StateFactory();
// Path: src/main/java/com/github/liblevenshtein/transducer/factory/PositionFactory.java // @NoArgsConstructor // public class PositionFactory implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Builds a dummy position. // * @return Dummy position. // */ // public Position build() { // return new Position(-1, -1); // } // // /** // * Builds a position vector for the standard, Levenshtein algorihtm. // * @param termIndex Current index of the spelling candidate. // * @param numErrors Number of accumulated errors at index {@code termIndex}. // * @return New position vector having index {@code termIndex} and error // * {@code numErrors}. // */ // public Position build(final int termIndex, final int numErrors) { // return new Position(termIndex, numErrors); // } // // /** // * Builds a position vector for the transposition and merge-and-split, // * Levenshtein algorihtms. // * @param termIndex Current index of the spelling candidate. // * @param numErrors Number of accumulated errors at index {@code termIndex}. // * @param isSpecial Either {@code 1} or {@code 0}, depending on whether the // * position is a special case (numErrors.g. a transposition position). // * @return New position vector having index {@code termIndex}, error // * {@code numErrors}, and special marker {@code isSpecial}. // */ // public Position build(final int termIndex, final int numErrors, final boolean isSpecial) { // if (isSpecial) { // return new SpecialPosition(termIndex, numErrors); // } // // return new Position(termIndex, numErrors); // } // } // // Path: src/main/java/com/github/liblevenshtein/transducer/factory/StateFactory.java // public class StateFactory implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Builds a new, Levenshtein state with the given position vectors. // * @param positions Array of position vectors to link into the state. // * @return New state having the position vectors. // */ // public State build(final Position... positions) { // final State state = new State(); // // Position prev = null; // for (final Position curr : positions) { // state.insertAfter(prev, curr); // prev = curr; // } // // return state; // } // } // // Path: src/test/java/com/github/liblevenshtein/assertion/DistanceFunctionAssertions.java // public static DistanceFunctionAssertions assertThat(final DistanceFunction actual) { // return new DistanceFunctionAssertions(actual); // } // Path: src/test/java/com/github/liblevenshtein/transducer/SpecialPositionDistanceFunctionTest.java import org.testng.annotations.Test; import lombok.val; import com.github.liblevenshtein.transducer.factory.PositionFactory; import com.github.liblevenshtein.transducer.factory.StateFactory; import static com.github.liblevenshtein.assertion.DistanceFunctionAssertions.assertThat; package com.github.liblevenshtein.transducer; public class SpecialPositionDistanceFunctionTest { @Test public void testAt() { val stateFactory = new StateFactory();
val positionFactory = new PositionFactory();
universal-automata/liblevenshtein-java
src/test/java/com/github/liblevenshtein/transducer/SpecialPositionDistanceFunctionTest.java
// Path: src/main/java/com/github/liblevenshtein/transducer/factory/PositionFactory.java // @NoArgsConstructor // public class PositionFactory implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Builds a dummy position. // * @return Dummy position. // */ // public Position build() { // return new Position(-1, -1); // } // // /** // * Builds a position vector for the standard, Levenshtein algorihtm. // * @param termIndex Current index of the spelling candidate. // * @param numErrors Number of accumulated errors at index {@code termIndex}. // * @return New position vector having index {@code termIndex} and error // * {@code numErrors}. // */ // public Position build(final int termIndex, final int numErrors) { // return new Position(termIndex, numErrors); // } // // /** // * Builds a position vector for the transposition and merge-and-split, // * Levenshtein algorihtms. // * @param termIndex Current index of the spelling candidate. // * @param numErrors Number of accumulated errors at index {@code termIndex}. // * @param isSpecial Either {@code 1} or {@code 0}, depending on whether the // * position is a special case (numErrors.g. a transposition position). // * @return New position vector having index {@code termIndex}, error // * {@code numErrors}, and special marker {@code isSpecial}. // */ // public Position build(final int termIndex, final int numErrors, final boolean isSpecial) { // if (isSpecial) { // return new SpecialPosition(termIndex, numErrors); // } // // return new Position(termIndex, numErrors); // } // } // // Path: src/main/java/com/github/liblevenshtein/transducer/factory/StateFactory.java // public class StateFactory implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Builds a new, Levenshtein state with the given position vectors. // * @param positions Array of position vectors to link into the state. // * @return New state having the position vectors. // */ // public State build(final Position... positions) { // final State state = new State(); // // Position prev = null; // for (final Position curr : positions) { // state.insertAfter(prev, curr); // prev = curr; // } // // return state; // } // } // // Path: src/test/java/com/github/liblevenshtein/assertion/DistanceFunctionAssertions.java // public static DistanceFunctionAssertions assertThat(final DistanceFunction actual) { // return new DistanceFunctionAssertions(actual); // }
import org.testng.annotations.Test; import lombok.val; import com.github.liblevenshtein.transducer.factory.PositionFactory; import com.github.liblevenshtein.transducer.factory.StateFactory; import static com.github.liblevenshtein.assertion.DistanceFunctionAssertions.assertThat;
package com.github.liblevenshtein.transducer; public class SpecialPositionDistanceFunctionTest { @Test public void testAt() { val stateFactory = new StateFactory(); val positionFactory = new PositionFactory(); final State state = stateFactory.build( positionFactory.build(2, 3, false), positionFactory.build(1, 1, false), positionFactory.build(4, 2, true)); final DistanceFunction distance = new DistanceFunction.ForSpecialPositions();
// Path: src/main/java/com/github/liblevenshtein/transducer/factory/PositionFactory.java // @NoArgsConstructor // public class PositionFactory implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Builds a dummy position. // * @return Dummy position. // */ // public Position build() { // return new Position(-1, -1); // } // // /** // * Builds a position vector for the standard, Levenshtein algorihtm. // * @param termIndex Current index of the spelling candidate. // * @param numErrors Number of accumulated errors at index {@code termIndex}. // * @return New position vector having index {@code termIndex} and error // * {@code numErrors}. // */ // public Position build(final int termIndex, final int numErrors) { // return new Position(termIndex, numErrors); // } // // /** // * Builds a position vector for the transposition and merge-and-split, // * Levenshtein algorihtms. // * @param termIndex Current index of the spelling candidate. // * @param numErrors Number of accumulated errors at index {@code termIndex}. // * @param isSpecial Either {@code 1} or {@code 0}, depending on whether the // * position is a special case (numErrors.g. a transposition position). // * @return New position vector having index {@code termIndex}, error // * {@code numErrors}, and special marker {@code isSpecial}. // */ // public Position build(final int termIndex, final int numErrors, final boolean isSpecial) { // if (isSpecial) { // return new SpecialPosition(termIndex, numErrors); // } // // return new Position(termIndex, numErrors); // } // } // // Path: src/main/java/com/github/liblevenshtein/transducer/factory/StateFactory.java // public class StateFactory implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Builds a new, Levenshtein state with the given position vectors. // * @param positions Array of position vectors to link into the state. // * @return New state having the position vectors. // */ // public State build(final Position... positions) { // final State state = new State(); // // Position prev = null; // for (final Position curr : positions) { // state.insertAfter(prev, curr); // prev = curr; // } // // return state; // } // } // // Path: src/test/java/com/github/liblevenshtein/assertion/DistanceFunctionAssertions.java // public static DistanceFunctionAssertions assertThat(final DistanceFunction actual) { // return new DistanceFunctionAssertions(actual); // } // Path: src/test/java/com/github/liblevenshtein/transducer/SpecialPositionDistanceFunctionTest.java import org.testng.annotations.Test; import lombok.val; import com.github.liblevenshtein.transducer.factory.PositionFactory; import com.github.liblevenshtein.transducer.factory.StateFactory; import static com.github.liblevenshtein.assertion.DistanceFunctionAssertions.assertThat; package com.github.liblevenshtein.transducer; public class SpecialPositionDistanceFunctionTest { @Test public void testAt() { val stateFactory = new StateFactory(); val positionFactory = new PositionFactory(); final State state = stateFactory.build( positionFactory.build(2, 3, false), positionFactory.build(1, 1, false), positionFactory.build(4, 2, true)); final DistanceFunction distance = new DistanceFunction.ForSpecialPositions();
assertThat(distance).hasDistance(state, 4, 4);
universal-automata/liblevenshtein-java
src/main/java/com/github/liblevenshtein/distance/MemoizedTransposition.java
// Path: src/main/java/com/github/liblevenshtein/collection/SymmetricImmutablePair.java // @Value // public class SymmetricImmutablePair<Type extends Comparable<Type>> // implements Comparable<SymmetricImmutablePair<Type>>, Serializable { // // private static final long serialVersionUID = 1L; // // /** // * First element of this pair. // */ // private final Type first; // // /** // * Second element of this pair. // */ // private final Type second; // // /** // * Returned from {@link #hashCode()}. // */ // private final int hashCode; // // /** // * Constructs a new symmetric, immutable pair on the given parameters. The // * hashCode is determined upon construction, so the assumption is made that // * first and second are immutable or will not be mutated. If they or any of // * their hashable components are mutated post-construction, the hashCode will // * be incorrect and the behavior of instances of this pair in such structures // * as hash maps will be undefined (e.g. this pair may seem to "disappear" from // * the hash map, even though it's still there). // * @param first First element of this pair // * @param second Second element of this pair // */ // public SymmetricImmutablePair( // @NonNull final Type first, // @NonNull final Type second) { // // if (first.compareTo(second) < 0) { // this.first = first; // this.second = second; // } // else { // this.first = second; // this.second = first; // } // // this.hashCode = new HashCodeBuilder(541, 7873) // .append(this.first) // .append(this.second) // .toHashCode(); // } // // /** // * {@inheritDoc} // */ // @Override // public int compareTo(final SymmetricImmutablePair<Type> other) { // final int c = first.compareTo(other.first()); // if (0 == c) { // return second.compareTo(other.second()); // } // return c; // } // // /** // * {@inheritDoc} // */ // @Override // public boolean equals(final Object o) { // if (!(o instanceof SymmetricImmutablePair)) { // return false; // } // // @SuppressWarnings("unchecked") // final SymmetricImmutablePair<Type> other = (SymmetricImmutablePair<Type>) o; // return 0 == compareTo(other); // } // // /** // * {@inheritDoc} // */ // @Override // public int hashCode() { // return hashCode; // } // }
import lombok.val; import com.github.liblevenshtein.collection.SymmetricImmutablePair;
package com.github.liblevenshtein.distance; /** * Memoizes the distance between two terms, where the distance is calculated * using the standard Levenshtein distance extended with transposition. * @author Dylon Edwards * @since 2.1.0 */ public class MemoizedTransposition extends AbstractMemoized { private static final long serialVersionUID = 1L; /** * {@inheritDoc} */ @Override @SuppressWarnings("checkstyle:finalparameters") public int memoizedDistance(String v, String w) {
// Path: src/main/java/com/github/liblevenshtein/collection/SymmetricImmutablePair.java // @Value // public class SymmetricImmutablePair<Type extends Comparable<Type>> // implements Comparable<SymmetricImmutablePair<Type>>, Serializable { // // private static final long serialVersionUID = 1L; // // /** // * First element of this pair. // */ // private final Type first; // // /** // * Second element of this pair. // */ // private final Type second; // // /** // * Returned from {@link #hashCode()}. // */ // private final int hashCode; // // /** // * Constructs a new symmetric, immutable pair on the given parameters. The // * hashCode is determined upon construction, so the assumption is made that // * first and second are immutable or will not be mutated. If they or any of // * their hashable components are mutated post-construction, the hashCode will // * be incorrect and the behavior of instances of this pair in such structures // * as hash maps will be undefined (e.g. this pair may seem to "disappear" from // * the hash map, even though it's still there). // * @param first First element of this pair // * @param second Second element of this pair // */ // public SymmetricImmutablePair( // @NonNull final Type first, // @NonNull final Type second) { // // if (first.compareTo(second) < 0) { // this.first = first; // this.second = second; // } // else { // this.first = second; // this.second = first; // } // // this.hashCode = new HashCodeBuilder(541, 7873) // .append(this.first) // .append(this.second) // .toHashCode(); // } // // /** // * {@inheritDoc} // */ // @Override // public int compareTo(final SymmetricImmutablePair<Type> other) { // final int c = first.compareTo(other.first()); // if (0 == c) { // return second.compareTo(other.second()); // } // return c; // } // // /** // * {@inheritDoc} // */ // @Override // public boolean equals(final Object o) { // if (!(o instanceof SymmetricImmutablePair)) { // return false; // } // // @SuppressWarnings("unchecked") // final SymmetricImmutablePair<Type> other = (SymmetricImmutablePair<Type>) o; // return 0 == compareTo(other); // } // // /** // * {@inheritDoc} // */ // @Override // public int hashCode() { // return hashCode; // } // } // Path: src/main/java/com/github/liblevenshtein/distance/MemoizedTransposition.java import lombok.val; import com.github.liblevenshtein.collection.SymmetricImmutablePair; package com.github.liblevenshtein.distance; /** * Memoizes the distance between two terms, where the distance is calculated * using the standard Levenshtein distance extended with transposition. * @author Dylon Edwards * @since 2.1.0 */ public class MemoizedTransposition extends AbstractMemoized { private static final long serialVersionUID = 1L; /** * {@inheritDoc} */ @Override @SuppressWarnings("checkstyle:finalparameters") public int memoizedDistance(String v, String w) {
val key = new SymmetricImmutablePair<String>(v, w);
universal-automata/liblevenshtein-java
src/test/java/com/github/liblevenshtein/collection/dictionary/DawgTest.java
// Path: src/main/java/com/github/liblevenshtein/collection/dictionary/factory/DawgFactory.java // @Slf4j // public class DawgFactory implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Returns a new DAWG. // * @param terms Terms to insert into the DAWG // * @return A new DAWG, containing the terms. // */ // public Dawg build(@NonNull final Collection<String> terms) { // return build(terms, false); // } // // /** // * Returns a new DAWG. // * @param terms Terms to insert into the DAWG // * @param isSorted Whether terms has been sorted // * @return A new DAWG, containing the terms. // */ // public Dawg build( // @NonNull final Collection<String> terms, // final boolean isSorted) { // // if (terms instanceof SortedDawg) { // return (SortedDawg) terms; // } // // if (!isSorted) { // if (!(terms instanceof List)) { // return build(new ArrayList<String>(terms), false); // } // // Collections.sort((List<String>) terms); // } // // return new SortedDawg(terms); // } // // /** // * Returns the final function of the dictionary. // * @param dictionary Dawg whose final function should be returned // * @return The final function of the dictionary // */ // public IFinalFunction<DawgNode> finalFunction(@NonNull final Dawg dictionary) { // return dictionary; // } // // /** // * Returns the transition function of the dictionary. // * @param dictionary Dawg whose transition function should be returned // * @return The transition function of the dictionary // */ // public ITransitionFunction<DawgNode> transitionFunction(@NonNull final Dawg dictionary) { // return dictionary; // } // } // // Path: src/test/java/com/github/liblevenshtein/assertion/SetAssertions.java // public static <Type> SetAssertions<Type> assertThat(final Set<Type> actual) { // return new SetAssertions<Type>(actual); // }
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import com.google.common.base.Joiner; import org.testng.annotations.BeforeClass; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import static org.assertj.core.api.Assertions.assertThat; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import com.github.liblevenshtein.collection.dictionary.factory.DawgFactory; import static com.github.liblevenshtein.assertion.SetAssertions.assertThat;
package com.github.liblevenshtein.collection.dictionary; @Slf4j public class DawgTest { private List<String> terms;
// Path: src/main/java/com/github/liblevenshtein/collection/dictionary/factory/DawgFactory.java // @Slf4j // public class DawgFactory implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Returns a new DAWG. // * @param terms Terms to insert into the DAWG // * @return A new DAWG, containing the terms. // */ // public Dawg build(@NonNull final Collection<String> terms) { // return build(terms, false); // } // // /** // * Returns a new DAWG. // * @param terms Terms to insert into the DAWG // * @param isSorted Whether terms has been sorted // * @return A new DAWG, containing the terms. // */ // public Dawg build( // @NonNull final Collection<String> terms, // final boolean isSorted) { // // if (terms instanceof SortedDawg) { // return (SortedDawg) terms; // } // // if (!isSorted) { // if (!(terms instanceof List)) { // return build(new ArrayList<String>(terms), false); // } // // Collections.sort((List<String>) terms); // } // // return new SortedDawg(terms); // } // // /** // * Returns the final function of the dictionary. // * @param dictionary Dawg whose final function should be returned // * @return The final function of the dictionary // */ // public IFinalFunction<DawgNode> finalFunction(@NonNull final Dawg dictionary) { // return dictionary; // } // // /** // * Returns the transition function of the dictionary. // * @param dictionary Dawg whose transition function should be returned // * @return The transition function of the dictionary // */ // public ITransitionFunction<DawgNode> transitionFunction(@NonNull final Dawg dictionary) { // return dictionary; // } // } // // Path: src/test/java/com/github/liblevenshtein/assertion/SetAssertions.java // public static <Type> SetAssertions<Type> assertThat(final Set<Type> actual) { // return new SetAssertions<Type>(actual); // } // Path: src/test/java/com/github/liblevenshtein/collection/dictionary/DawgTest.java import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import com.google.common.base.Joiner; import org.testng.annotations.BeforeClass; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import static org.assertj.core.api.Assertions.assertThat; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import com.github.liblevenshtein.collection.dictionary.factory.DawgFactory; import static com.github.liblevenshtein.assertion.SetAssertions.assertThat; package com.github.liblevenshtein.collection.dictionary; @Slf4j public class DawgTest { private List<String> terms;
private DawgFactory dawgFactory;
universal-automata/liblevenshtein-java
src/test/java/com/github/liblevenshtein/collection/dictionary/DawgTest.java
// Path: src/main/java/com/github/liblevenshtein/collection/dictionary/factory/DawgFactory.java // @Slf4j // public class DawgFactory implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Returns a new DAWG. // * @param terms Terms to insert into the DAWG // * @return A new DAWG, containing the terms. // */ // public Dawg build(@NonNull final Collection<String> terms) { // return build(terms, false); // } // // /** // * Returns a new DAWG. // * @param terms Terms to insert into the DAWG // * @param isSorted Whether terms has been sorted // * @return A new DAWG, containing the terms. // */ // public Dawg build( // @NonNull final Collection<String> terms, // final boolean isSorted) { // // if (terms instanceof SortedDawg) { // return (SortedDawg) terms; // } // // if (!isSorted) { // if (!(terms instanceof List)) { // return build(new ArrayList<String>(terms), false); // } // // Collections.sort((List<String>) terms); // } // // return new SortedDawg(terms); // } // // /** // * Returns the final function of the dictionary. // * @param dictionary Dawg whose final function should be returned // * @return The final function of the dictionary // */ // public IFinalFunction<DawgNode> finalFunction(@NonNull final Dawg dictionary) { // return dictionary; // } // // /** // * Returns the transition function of the dictionary. // * @param dictionary Dawg whose transition function should be returned // * @return The transition function of the dictionary // */ // public ITransitionFunction<DawgNode> transitionFunction(@NonNull final Dawg dictionary) { // return dictionary; // } // } // // Path: src/test/java/com/github/liblevenshtein/assertion/SetAssertions.java // public static <Type> SetAssertions<Type> assertThat(final Set<Type> actual) { // return new SetAssertions<Type>(actual); // }
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import com.google.common.base.Joiner; import org.testng.annotations.BeforeClass; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import static org.assertj.core.api.Assertions.assertThat; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import com.github.liblevenshtein.collection.dictionary.factory.DawgFactory; import static com.github.liblevenshtein.assertion.SetAssertions.assertThat;
@BeforeClass public void setUp() throws IOException { try (final BufferedReader reader = new BufferedReader( new InputStreamReader( getClass().getResourceAsStream("/wordsEn.txt"), StandardCharsets.UTF_8))) { final List<String> termsList = new ArrayList<>(); String term; while ((term = reader.readLine()) != null) { termsList.add(term); } Collections.sort(termsList); this.terms = termsList; this.dawgFactory = new DawgFactory(); this.emptyDawg = dawgFactory.build(new ArrayList<>(0)); this.fullDawg = dawgFactory.build(termsList); } } @DataProvider(name = "terms") public Iterator<Object[]> terms() { return new TermIterator(terms.iterator()); } @Test(dataProvider = "terms") public void emptyDawgAcceptsNothing(final String term) {
// Path: src/main/java/com/github/liblevenshtein/collection/dictionary/factory/DawgFactory.java // @Slf4j // public class DawgFactory implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Returns a new DAWG. // * @param terms Terms to insert into the DAWG // * @return A new DAWG, containing the terms. // */ // public Dawg build(@NonNull final Collection<String> terms) { // return build(terms, false); // } // // /** // * Returns a new DAWG. // * @param terms Terms to insert into the DAWG // * @param isSorted Whether terms has been sorted // * @return A new DAWG, containing the terms. // */ // public Dawg build( // @NonNull final Collection<String> terms, // final boolean isSorted) { // // if (terms instanceof SortedDawg) { // return (SortedDawg) terms; // } // // if (!isSorted) { // if (!(terms instanceof List)) { // return build(new ArrayList<String>(terms), false); // } // // Collections.sort((List<String>) terms); // } // // return new SortedDawg(terms); // } // // /** // * Returns the final function of the dictionary. // * @param dictionary Dawg whose final function should be returned // * @return The final function of the dictionary // */ // public IFinalFunction<DawgNode> finalFunction(@NonNull final Dawg dictionary) { // return dictionary; // } // // /** // * Returns the transition function of the dictionary. // * @param dictionary Dawg whose transition function should be returned // * @return The transition function of the dictionary // */ // public ITransitionFunction<DawgNode> transitionFunction(@NonNull final Dawg dictionary) { // return dictionary; // } // } // // Path: src/test/java/com/github/liblevenshtein/assertion/SetAssertions.java // public static <Type> SetAssertions<Type> assertThat(final Set<Type> actual) { // return new SetAssertions<Type>(actual); // } // Path: src/test/java/com/github/liblevenshtein/collection/dictionary/DawgTest.java import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import com.google.common.base.Joiner; import org.testng.annotations.BeforeClass; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import static org.assertj.core.api.Assertions.assertThat; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import com.github.liblevenshtein.collection.dictionary.factory.DawgFactory; import static com.github.liblevenshtein.assertion.SetAssertions.assertThat; @BeforeClass public void setUp() throws IOException { try (final BufferedReader reader = new BufferedReader( new InputStreamReader( getClass().getResourceAsStream("/wordsEn.txt"), StandardCharsets.UTF_8))) { final List<String> termsList = new ArrayList<>(); String term; while ((term = reader.readLine()) != null) { termsList.add(term); } Collections.sort(termsList); this.terms = termsList; this.dawgFactory = new DawgFactory(); this.emptyDawg = dawgFactory.build(new ArrayList<>(0)); this.fullDawg = dawgFactory.build(termsList); } } @DataProvider(name = "terms") public Iterator<Object[]> terms() { return new TermIterator(terms.iterator()); } @Test(dataProvider = "terms") public void emptyDawgAcceptsNothing(final String term) {
assertThat(emptyDawg).doesNotContain(term);
universal-automata/liblevenshtein-java
src/test/java/com/github/liblevenshtein/transducer/UnsubsumeFunctionTest.java
// Path: src/main/java/com/github/liblevenshtein/transducer/factory/PositionFactory.java // @NoArgsConstructor // public class PositionFactory implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Builds a dummy position. // * @return Dummy position. // */ // public Position build() { // return new Position(-1, -1); // } // // /** // * Builds a position vector for the standard, Levenshtein algorihtm. // * @param termIndex Current index of the spelling candidate. // * @param numErrors Number of accumulated errors at index {@code termIndex}. // * @return New position vector having index {@code termIndex} and error // * {@code numErrors}. // */ // public Position build(final int termIndex, final int numErrors) { // return new Position(termIndex, numErrors); // } // // /** // * Builds a position vector for the transposition and merge-and-split, // * Levenshtein algorihtms. // * @param termIndex Current index of the spelling candidate. // * @param numErrors Number of accumulated errors at index {@code termIndex}. // * @param isSpecial Either {@code 1} or {@code 0}, depending on whether the // * position is a special case (numErrors.g. a transposition position). // * @return New position vector having index {@code termIndex}, error // * {@code numErrors}, and special marker {@code isSpecial}. // */ // public Position build(final int termIndex, final int numErrors, final boolean isSpecial) { // if (isSpecial) { // return new SpecialPosition(termIndex, numErrors); // } // // return new Position(termIndex, numErrors); // } // } // // Path: src/main/java/com/github/liblevenshtein/transducer/factory/StateFactory.java // public class StateFactory implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Builds a new, Levenshtein state with the given position vectors. // * @param positions Array of position vectors to link into the state. // * @return New state having the position vectors. // */ // public State build(final Position... positions) { // final State state = new State(); // // Position prev = null; // for (final Position curr : positions) { // state.insertAfter(prev, curr); // prev = curr; // } // // return state; // } // }
import org.testng.annotations.BeforeTest; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import static org.assertj.core.api.Assertions.assertThat; import com.github.liblevenshtein.transducer.factory.PositionFactory; import com.github.liblevenshtein.transducer.factory.StateFactory;
package com.github.liblevenshtein.transducer; public class UnsubsumeFunctionTest { private static final int QUERY_LENGTH = 20;
// Path: src/main/java/com/github/liblevenshtein/transducer/factory/PositionFactory.java // @NoArgsConstructor // public class PositionFactory implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Builds a dummy position. // * @return Dummy position. // */ // public Position build() { // return new Position(-1, -1); // } // // /** // * Builds a position vector for the standard, Levenshtein algorihtm. // * @param termIndex Current index of the spelling candidate. // * @param numErrors Number of accumulated errors at index {@code termIndex}. // * @return New position vector having index {@code termIndex} and error // * {@code numErrors}. // */ // public Position build(final int termIndex, final int numErrors) { // return new Position(termIndex, numErrors); // } // // /** // * Builds a position vector for the transposition and merge-and-split, // * Levenshtein algorihtms. // * @param termIndex Current index of the spelling candidate. // * @param numErrors Number of accumulated errors at index {@code termIndex}. // * @param isSpecial Either {@code 1} or {@code 0}, depending on whether the // * position is a special case (numErrors.g. a transposition position). // * @return New position vector having index {@code termIndex}, error // * {@code numErrors}, and special marker {@code isSpecial}. // */ // public Position build(final int termIndex, final int numErrors, final boolean isSpecial) { // if (isSpecial) { // return new SpecialPosition(termIndex, numErrors); // } // // return new Position(termIndex, numErrors); // } // } // // Path: src/main/java/com/github/liblevenshtein/transducer/factory/StateFactory.java // public class StateFactory implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Builds a new, Levenshtein state with the given position vectors. // * @param positions Array of position vectors to link into the state. // * @return New state having the position vectors. // */ // public State build(final Position... positions) { // final State state = new State(); // // Position prev = null; // for (final Position curr : positions) { // state.insertAfter(prev, curr); // prev = curr; // } // // return state; // } // } // Path: src/test/java/com/github/liblevenshtein/transducer/UnsubsumeFunctionTest.java import org.testng.annotations.BeforeTest; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import static org.assertj.core.api.Assertions.assertThat; import com.github.liblevenshtein.transducer.factory.PositionFactory; import com.github.liblevenshtein.transducer.factory.StateFactory; package com.github.liblevenshtein.transducer; public class UnsubsumeFunctionTest { private static final int QUERY_LENGTH = 20;
private final StateFactory stateFactory = new StateFactory();
universal-automata/liblevenshtein-java
src/test/java/com/github/liblevenshtein/transducer/UnsubsumeFunctionTest.java
// Path: src/main/java/com/github/liblevenshtein/transducer/factory/PositionFactory.java // @NoArgsConstructor // public class PositionFactory implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Builds a dummy position. // * @return Dummy position. // */ // public Position build() { // return new Position(-1, -1); // } // // /** // * Builds a position vector for the standard, Levenshtein algorihtm. // * @param termIndex Current index of the spelling candidate. // * @param numErrors Number of accumulated errors at index {@code termIndex}. // * @return New position vector having index {@code termIndex} and error // * {@code numErrors}. // */ // public Position build(final int termIndex, final int numErrors) { // return new Position(termIndex, numErrors); // } // // /** // * Builds a position vector for the transposition and merge-and-split, // * Levenshtein algorihtms. // * @param termIndex Current index of the spelling candidate. // * @param numErrors Number of accumulated errors at index {@code termIndex}. // * @param isSpecial Either {@code 1} or {@code 0}, depending on whether the // * position is a special case (numErrors.g. a transposition position). // * @return New position vector having index {@code termIndex}, error // * {@code numErrors}, and special marker {@code isSpecial}. // */ // public Position build(final int termIndex, final int numErrors, final boolean isSpecial) { // if (isSpecial) { // return new SpecialPosition(termIndex, numErrors); // } // // return new Position(termIndex, numErrors); // } // } // // Path: src/main/java/com/github/liblevenshtein/transducer/factory/StateFactory.java // public class StateFactory implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Builds a new, Levenshtein state with the given position vectors. // * @param positions Array of position vectors to link into the state. // * @return New state having the position vectors. // */ // public State build(final Position... positions) { // final State state = new State(); // // Position prev = null; // for (final Position curr : positions) { // state.insertAfter(prev, curr); // prev = curr; // } // // return state; // } // }
import org.testng.annotations.BeforeTest; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import static org.assertj.core.api.Assertions.assertThat; import com.github.liblevenshtein.transducer.factory.PositionFactory; import com.github.liblevenshtein.transducer.factory.StateFactory;
package com.github.liblevenshtein.transducer; public class UnsubsumeFunctionTest { private static final int QUERY_LENGTH = 20; private final StateFactory stateFactory = new StateFactory();
// Path: src/main/java/com/github/liblevenshtein/transducer/factory/PositionFactory.java // @NoArgsConstructor // public class PositionFactory implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Builds a dummy position. // * @return Dummy position. // */ // public Position build() { // return new Position(-1, -1); // } // // /** // * Builds a position vector for the standard, Levenshtein algorihtm. // * @param termIndex Current index of the spelling candidate. // * @param numErrors Number of accumulated errors at index {@code termIndex}. // * @return New position vector having index {@code termIndex} and error // * {@code numErrors}. // */ // public Position build(final int termIndex, final int numErrors) { // return new Position(termIndex, numErrors); // } // // /** // * Builds a position vector for the transposition and merge-and-split, // * Levenshtein algorihtms. // * @param termIndex Current index of the spelling candidate. // * @param numErrors Number of accumulated errors at index {@code termIndex}. // * @param isSpecial Either {@code 1} or {@code 0}, depending on whether the // * position is a special case (numErrors.g. a transposition position). // * @return New position vector having index {@code termIndex}, error // * {@code numErrors}, and special marker {@code isSpecial}. // */ // public Position build(final int termIndex, final int numErrors, final boolean isSpecial) { // if (isSpecial) { // return new SpecialPosition(termIndex, numErrors); // } // // return new Position(termIndex, numErrors); // } // } // // Path: src/main/java/com/github/liblevenshtein/transducer/factory/StateFactory.java // public class StateFactory implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Builds a new, Levenshtein state with the given position vectors. // * @param positions Array of position vectors to link into the state. // * @return New state having the position vectors. // */ // public State build(final Position... positions) { // final State state = new State(); // // Position prev = null; // for (final Position curr : positions) { // state.insertAfter(prev, curr); // prev = curr; // } // // return state; // } // } // Path: src/test/java/com/github/liblevenshtein/transducer/UnsubsumeFunctionTest.java import org.testng.annotations.BeforeTest; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import static org.assertj.core.api.Assertions.assertThat; import com.github.liblevenshtein.transducer.factory.PositionFactory; import com.github.liblevenshtein.transducer.factory.StateFactory; package com.github.liblevenshtein.transducer; public class UnsubsumeFunctionTest { private static final int QUERY_LENGTH = 20; private final StateFactory stateFactory = new StateFactory();
private final PositionFactory positionFactory = new PositionFactory();
universal-automata/liblevenshtein-java
src/test/java/com/github/liblevenshtein/transducer/StateTest.java
// Path: src/test/java/com/github/liblevenshtein/assertion/StateAssertions.java // public static StateAssertions assertThat(final State actual) { // return new StateAssertions(actual); // }
import java.util.Comparator; import org.testng.annotations.Test; import static com.github.liblevenshtein.assertion.StateAssertions.assertThat;
package com.github.liblevenshtein.transducer; public class StateTest { @Test public void testInsertionAndIterationOperations() { final Position p00 = new Position(0, 0); final Position p01 = new Position(0, 1); final Position p10 = new Position(1, 0); final Position p11 = new Position(1, 1); final Comparator<Position> comparator = new StandardPositionComparator(); final State state = new State();
// Path: src/test/java/com/github/liblevenshtein/assertion/StateAssertions.java // public static StateAssertions assertThat(final State actual) { // return new StateAssertions(actual); // } // Path: src/test/java/com/github/liblevenshtein/transducer/StateTest.java import java.util.Comparator; import org.testng.annotations.Test; import static com.github.liblevenshtein.assertion.StateAssertions.assertThat; package com.github.liblevenshtein.transducer; public class StateTest { @Test public void testInsertionAndIterationOperations() { final Position p00 = new Position(0, 0); final Position p01 = new Position(0, 1); final Position p10 = new Position(1, 0); final Position p11 = new Position(1, 1); final Comparator<Position> comparator = new StandardPositionComparator(); final State state = new State();
assertThat(state)
universal-automata/liblevenshtein-java
src/main/java/com/github/liblevenshtein/transducer/factory/CandidateFactory.java
// Path: src/main/java/com/github/liblevenshtein/transducer/Candidate.java // @Value // public class Candidate implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Candidate term from the dictionary automaton. // * @return Candidate term from the dictionary automaton. // */ // private final String term; // // /** // * Distance between the candidate term and the query term. // * @return Distance between the candidate term and the query term. // */ // private final int distance; // }
import java.io.Serializable; import lombok.AccessLevel; import lombok.NoArgsConstructor; import com.github.liblevenshtein.transducer.Candidate;
package com.github.liblevenshtein.transducer.factory; /** * Builds spelling candidates of the requested type, optionally including the * distance of the candidate from the query term. * @author Dylon Edwards * @param <CandidateType> Kind of spelling candidate built by this factory. * @since 2.1.2 */ @NoArgsConstructor(access = AccessLevel.PROTECTED) public abstract class CandidateFactory<CandidateType> implements Serializable { private static final long serialVersionUID = 1L; /** * Builds a new spelling candidate from the dictionary term and its * Levenshtein distance from the query term. * @param term Candidate term from the dictionary. * @param distance Levenshtein distance of the dictionary term from the query * term. * @return A new spelling candidate, optionally with the distance included. */ public abstract CandidateType build(String term, int distance); /** * Builds instances of {@link Candidate}, with the dictionary term and its * Levenshtein distance from the query term. * @author Dylon Edwards * @since 2.1.2 */
// Path: src/main/java/com/github/liblevenshtein/transducer/Candidate.java // @Value // public class Candidate implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Candidate term from the dictionary automaton. // * @return Candidate term from the dictionary automaton. // */ // private final String term; // // /** // * Distance between the candidate term and the query term. // * @return Distance between the candidate term and the query term. // */ // private final int distance; // } // Path: src/main/java/com/github/liblevenshtein/transducer/factory/CandidateFactory.java import java.io.Serializable; import lombok.AccessLevel; import lombok.NoArgsConstructor; import com.github.liblevenshtein.transducer.Candidate; package com.github.liblevenshtein.transducer.factory; /** * Builds spelling candidates of the requested type, optionally including the * distance of the candidate from the query term. * @author Dylon Edwards * @param <CandidateType> Kind of spelling candidate built by this factory. * @since 2.1.2 */ @NoArgsConstructor(access = AccessLevel.PROTECTED) public abstract class CandidateFactory<CandidateType> implements Serializable { private static final long serialVersionUID = 1L; /** * Builds a new spelling candidate from the dictionary term and its * Levenshtein distance from the query term. * @param term Candidate term from the dictionary. * @param distance Levenshtein distance of the dictionary term from the query * term. * @return A new spelling candidate, optionally with the distance included. */ public abstract CandidateType build(String term, int distance); /** * Builds instances of {@link Candidate}, with the dictionary term and its * Levenshtein distance from the query term. * @author Dylon Edwards * @since 2.1.2 */
public static class WithDistance extends CandidateFactory<Candidate> {
universal-automata/liblevenshtein-java
src/main/java/com/github/liblevenshtein/transducer/StateTransitionFunction.java
// Path: src/main/java/com/github/liblevenshtein/transducer/factory/PositionTransitionFactory.java // @Setter // @NoArgsConstructor(access = AccessLevel.PROTECTED) // public abstract class PositionTransitionFactory implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Builds Levenshtein states. // */ // protected StateFactory stateFactory; // // /** // * Builds Levenshtein positions. // */ // protected PositionFactory positionFactory; // // /** // * Builds a new position-transition function. // * @return New position-transition function. // */ // public abstract PositionTransitionFunction build(); // // /** // * Builds position-transition functions for standard, Levenshtein states. // * @author Dylon Edwards // * @since 2.1.0 // */ // public static class ForStandardPositions extends PositionTransitionFactory { // // private static final long serialVersionUID = 1L; // // /** // * {@inheritDoc} // */ // @Override // public PositionTransitionFunction build() { // return new StandardPositionTransitionFunction() // .stateFactory(stateFactory) // .positionFactory(positionFactory); // } // } // // /** // * Builds position-transition functions for transposition, Levenshtein states. // * @author Dylon Edwards // * @since 2.1.0 // */ // public static class ForTranspositionPositions extends PositionTransitionFactory { // // private static final long serialVersionUID = 1L; // // /** // * {@inheritDoc} // */ // @Override // public PositionTransitionFunction build() { // return new TranspositionPositionTransitionFunction() // .stateFactory(stateFactory) // .positionFactory(positionFactory); // } // } // // /** // * Builds position-transition functions for merge-and-split, Levenshtein states. // * @author Dylon Edwards // * @since 2.1.0 // */ // public static class ForMergeAndSplitPositions extends PositionTransitionFactory { // // private static final long serialVersionUID = 1L; // // /** // * {@inheritDoc} // */ // @Override // public PositionTransitionFunction build() { // return new MergeAndSplitPositionTransitionFunction() // .stateFactory(stateFactory) // .positionFactory(positionFactory); // } // } // } // // Path: src/main/java/com/github/liblevenshtein/transducer/factory/StateFactory.java // public class StateFactory implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Builds a new, Levenshtein state with the given position vectors. // * @param positions Array of position vectors to link into the state. // * @return New state having the position vectors. // */ // public State build(final Position... positions) { // final State state = new State(); // // Position prev = null; // for (final Position curr : positions) { // state.insertAfter(prev, curr); // prev = curr; // } // // return state; // } // }
import java.io.Serializable; import java.util.Comparator; import lombok.Setter; import com.github.liblevenshtein.transducer.factory.PositionTransitionFactory; import com.github.liblevenshtein.transducer.factory.StateFactory;
package com.github.liblevenshtein.transducer; /** * Transitions one state to another, given a set of inputs. This function * doesn't need to know about the Levenshtein algorithm, as the * algorithm-specific components are injected via setters. * @author Dylon Edwards * @since 2.1.0 */ @Setter public class StateTransitionFunction implements Serializable { private static final long serialVersionUID = 1L; /** * Sorts {@link State} elements in an unsubsumption-friendly fashion. */ private Comparator<Position> comparator; /** * Builds and recycles {@link State} instances. */
// Path: src/main/java/com/github/liblevenshtein/transducer/factory/PositionTransitionFactory.java // @Setter // @NoArgsConstructor(access = AccessLevel.PROTECTED) // public abstract class PositionTransitionFactory implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Builds Levenshtein states. // */ // protected StateFactory stateFactory; // // /** // * Builds Levenshtein positions. // */ // protected PositionFactory positionFactory; // // /** // * Builds a new position-transition function. // * @return New position-transition function. // */ // public abstract PositionTransitionFunction build(); // // /** // * Builds position-transition functions for standard, Levenshtein states. // * @author Dylon Edwards // * @since 2.1.0 // */ // public static class ForStandardPositions extends PositionTransitionFactory { // // private static final long serialVersionUID = 1L; // // /** // * {@inheritDoc} // */ // @Override // public PositionTransitionFunction build() { // return new StandardPositionTransitionFunction() // .stateFactory(stateFactory) // .positionFactory(positionFactory); // } // } // // /** // * Builds position-transition functions for transposition, Levenshtein states. // * @author Dylon Edwards // * @since 2.1.0 // */ // public static class ForTranspositionPositions extends PositionTransitionFactory { // // private static final long serialVersionUID = 1L; // // /** // * {@inheritDoc} // */ // @Override // public PositionTransitionFunction build() { // return new TranspositionPositionTransitionFunction() // .stateFactory(stateFactory) // .positionFactory(positionFactory); // } // } // // /** // * Builds position-transition functions for merge-and-split, Levenshtein states. // * @author Dylon Edwards // * @since 2.1.0 // */ // public static class ForMergeAndSplitPositions extends PositionTransitionFactory { // // private static final long serialVersionUID = 1L; // // /** // * {@inheritDoc} // */ // @Override // public PositionTransitionFunction build() { // return new MergeAndSplitPositionTransitionFunction() // .stateFactory(stateFactory) // .positionFactory(positionFactory); // } // } // } // // Path: src/main/java/com/github/liblevenshtein/transducer/factory/StateFactory.java // public class StateFactory implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Builds a new, Levenshtein state with the given position vectors. // * @param positions Array of position vectors to link into the state. // * @return New state having the position vectors. // */ // public State build(final Position... positions) { // final State state = new State(); // // Position prev = null; // for (final Position curr : positions) { // state.insertAfter(prev, curr); // prev = curr; // } // // return state; // } // } // Path: src/main/java/com/github/liblevenshtein/transducer/StateTransitionFunction.java import java.io.Serializable; import java.util.Comparator; import lombok.Setter; import com.github.liblevenshtein.transducer.factory.PositionTransitionFactory; import com.github.liblevenshtein.transducer.factory.StateFactory; package com.github.liblevenshtein.transducer; /** * Transitions one state to another, given a set of inputs. This function * doesn't need to know about the Levenshtein algorithm, as the * algorithm-specific components are injected via setters. * @author Dylon Edwards * @since 2.1.0 */ @Setter public class StateTransitionFunction implements Serializable { private static final long serialVersionUID = 1L; /** * Sorts {@link State} elements in an unsubsumption-friendly fashion. */ private Comparator<Position> comparator; /** * Builds and recycles {@link State} instances. */
private StateFactory stateFactory;
universal-automata/liblevenshtein-java
src/main/java/com/github/liblevenshtein/transducer/StateTransitionFunction.java
// Path: src/main/java/com/github/liblevenshtein/transducer/factory/PositionTransitionFactory.java // @Setter // @NoArgsConstructor(access = AccessLevel.PROTECTED) // public abstract class PositionTransitionFactory implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Builds Levenshtein states. // */ // protected StateFactory stateFactory; // // /** // * Builds Levenshtein positions. // */ // protected PositionFactory positionFactory; // // /** // * Builds a new position-transition function. // * @return New position-transition function. // */ // public abstract PositionTransitionFunction build(); // // /** // * Builds position-transition functions for standard, Levenshtein states. // * @author Dylon Edwards // * @since 2.1.0 // */ // public static class ForStandardPositions extends PositionTransitionFactory { // // private static final long serialVersionUID = 1L; // // /** // * {@inheritDoc} // */ // @Override // public PositionTransitionFunction build() { // return new StandardPositionTransitionFunction() // .stateFactory(stateFactory) // .positionFactory(positionFactory); // } // } // // /** // * Builds position-transition functions for transposition, Levenshtein states. // * @author Dylon Edwards // * @since 2.1.0 // */ // public static class ForTranspositionPositions extends PositionTransitionFactory { // // private static final long serialVersionUID = 1L; // // /** // * {@inheritDoc} // */ // @Override // public PositionTransitionFunction build() { // return new TranspositionPositionTransitionFunction() // .stateFactory(stateFactory) // .positionFactory(positionFactory); // } // } // // /** // * Builds position-transition functions for merge-and-split, Levenshtein states. // * @author Dylon Edwards // * @since 2.1.0 // */ // public static class ForMergeAndSplitPositions extends PositionTransitionFactory { // // private static final long serialVersionUID = 1L; // // /** // * {@inheritDoc} // */ // @Override // public PositionTransitionFunction build() { // return new MergeAndSplitPositionTransitionFunction() // .stateFactory(stateFactory) // .positionFactory(positionFactory); // } // } // } // // Path: src/main/java/com/github/liblevenshtein/transducer/factory/StateFactory.java // public class StateFactory implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Builds a new, Levenshtein state with the given position vectors. // * @param positions Array of position vectors to link into the state. // * @return New state having the position vectors. // */ // public State build(final Position... positions) { // final State state = new State(); // // Position prev = null; // for (final Position curr : positions) { // state.insertAfter(prev, curr); // prev = curr; // } // // return state; // } // }
import java.io.Serializable; import java.util.Comparator; import lombok.Setter; import com.github.liblevenshtein.transducer.factory.PositionTransitionFactory; import com.github.liblevenshtein.transducer.factory.StateFactory;
package com.github.liblevenshtein.transducer; /** * Transitions one state to another, given a set of inputs. This function * doesn't need to know about the Levenshtein algorithm, as the * algorithm-specific components are injected via setters. * @author Dylon Edwards * @since 2.1.0 */ @Setter public class StateTransitionFunction implements Serializable { private static final long serialVersionUID = 1L; /** * Sorts {@link State} elements in an unsubsumption-friendly fashion. */ private Comparator<Position> comparator; /** * Builds and recycles {@link State} instances. */ private StateFactory stateFactory; /** * Builds position vector, transition functions according to the Levenshtein * algorithm. */
// Path: src/main/java/com/github/liblevenshtein/transducer/factory/PositionTransitionFactory.java // @Setter // @NoArgsConstructor(access = AccessLevel.PROTECTED) // public abstract class PositionTransitionFactory implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Builds Levenshtein states. // */ // protected StateFactory stateFactory; // // /** // * Builds Levenshtein positions. // */ // protected PositionFactory positionFactory; // // /** // * Builds a new position-transition function. // * @return New position-transition function. // */ // public abstract PositionTransitionFunction build(); // // /** // * Builds position-transition functions for standard, Levenshtein states. // * @author Dylon Edwards // * @since 2.1.0 // */ // public static class ForStandardPositions extends PositionTransitionFactory { // // private static final long serialVersionUID = 1L; // // /** // * {@inheritDoc} // */ // @Override // public PositionTransitionFunction build() { // return new StandardPositionTransitionFunction() // .stateFactory(stateFactory) // .positionFactory(positionFactory); // } // } // // /** // * Builds position-transition functions for transposition, Levenshtein states. // * @author Dylon Edwards // * @since 2.1.0 // */ // public static class ForTranspositionPositions extends PositionTransitionFactory { // // private static final long serialVersionUID = 1L; // // /** // * {@inheritDoc} // */ // @Override // public PositionTransitionFunction build() { // return new TranspositionPositionTransitionFunction() // .stateFactory(stateFactory) // .positionFactory(positionFactory); // } // } // // /** // * Builds position-transition functions for merge-and-split, Levenshtein states. // * @author Dylon Edwards // * @since 2.1.0 // */ // public static class ForMergeAndSplitPositions extends PositionTransitionFactory { // // private static final long serialVersionUID = 1L; // // /** // * {@inheritDoc} // */ // @Override // public PositionTransitionFunction build() { // return new MergeAndSplitPositionTransitionFunction() // .stateFactory(stateFactory) // .positionFactory(positionFactory); // } // } // } // // Path: src/main/java/com/github/liblevenshtein/transducer/factory/StateFactory.java // public class StateFactory implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Builds a new, Levenshtein state with the given position vectors. // * @param positions Array of position vectors to link into the state. // * @return New state having the position vectors. // */ // public State build(final Position... positions) { // final State state = new State(); // // Position prev = null; // for (final Position curr : positions) { // state.insertAfter(prev, curr); // prev = curr; // } // // return state; // } // } // Path: src/main/java/com/github/liblevenshtein/transducer/StateTransitionFunction.java import java.io.Serializable; import java.util.Comparator; import lombok.Setter; import com.github.liblevenshtein.transducer.factory.PositionTransitionFactory; import com.github.liblevenshtein.transducer.factory.StateFactory; package com.github.liblevenshtein.transducer; /** * Transitions one state to another, given a set of inputs. This function * doesn't need to know about the Levenshtein algorithm, as the * algorithm-specific components are injected via setters. * @author Dylon Edwards * @since 2.1.0 */ @Setter public class StateTransitionFunction implements Serializable { private static final long serialVersionUID = 1L; /** * Sorts {@link State} elements in an unsubsumption-friendly fashion. */ private Comparator<Position> comparator; /** * Builds and recycles {@link State} instances. */ private StateFactory stateFactory; /** * Builds position vector, transition functions according to the Levenshtein * algorithm. */
private PositionTransitionFactory transitionFactory;
universal-automata/liblevenshtein-java
src/main/java/com/github/liblevenshtein/distance/MemoizedStandard.java
// Path: src/main/java/com/github/liblevenshtein/collection/SymmetricImmutablePair.java // @Value // public class SymmetricImmutablePair<Type extends Comparable<Type>> // implements Comparable<SymmetricImmutablePair<Type>>, Serializable { // // private static final long serialVersionUID = 1L; // // /** // * First element of this pair. // */ // private final Type first; // // /** // * Second element of this pair. // */ // private final Type second; // // /** // * Returned from {@link #hashCode()}. // */ // private final int hashCode; // // /** // * Constructs a new symmetric, immutable pair on the given parameters. The // * hashCode is determined upon construction, so the assumption is made that // * first and second are immutable or will not be mutated. If they or any of // * their hashable components are mutated post-construction, the hashCode will // * be incorrect and the behavior of instances of this pair in such structures // * as hash maps will be undefined (e.g. this pair may seem to "disappear" from // * the hash map, even though it's still there). // * @param first First element of this pair // * @param second Second element of this pair // */ // public SymmetricImmutablePair( // @NonNull final Type first, // @NonNull final Type second) { // // if (first.compareTo(second) < 0) { // this.first = first; // this.second = second; // } // else { // this.first = second; // this.second = first; // } // // this.hashCode = new HashCodeBuilder(541, 7873) // .append(this.first) // .append(this.second) // .toHashCode(); // } // // /** // * {@inheritDoc} // */ // @Override // public int compareTo(final SymmetricImmutablePair<Type> other) { // final int c = first.compareTo(other.first()); // if (0 == c) { // return second.compareTo(other.second()); // } // return c; // } // // /** // * {@inheritDoc} // */ // @Override // public boolean equals(final Object o) { // if (!(o instanceof SymmetricImmutablePair)) { // return false; // } // // @SuppressWarnings("unchecked") // final SymmetricImmutablePair<Type> other = (SymmetricImmutablePair<Type>) o; // return 0 == compareTo(other); // } // // /** // * {@inheritDoc} // */ // @Override // public int hashCode() { // return hashCode; // } // }
import lombok.val; import com.github.liblevenshtein.collection.SymmetricImmutablePair;
package com.github.liblevenshtein.distance; /** * Memoizes the distance between two terms, where the distance is calculated * using the standard Levenshtein distance, including the elementary operations * of insertion, deletion and substitution. * @author Dylon Edwards * @since 2.1.0 */ public class MemoizedStandard extends AbstractMemoized { private static final long serialVersionUID = 1L; /** * {@inheritDoc} */ @Override @SuppressWarnings("checkstyle:finalparameters") public int memoizedDistance(String v, String w) {
// Path: src/main/java/com/github/liblevenshtein/collection/SymmetricImmutablePair.java // @Value // public class SymmetricImmutablePair<Type extends Comparable<Type>> // implements Comparable<SymmetricImmutablePair<Type>>, Serializable { // // private static final long serialVersionUID = 1L; // // /** // * First element of this pair. // */ // private final Type first; // // /** // * Second element of this pair. // */ // private final Type second; // // /** // * Returned from {@link #hashCode()}. // */ // private final int hashCode; // // /** // * Constructs a new symmetric, immutable pair on the given parameters. The // * hashCode is determined upon construction, so the assumption is made that // * first and second are immutable or will not be mutated. If they or any of // * their hashable components are mutated post-construction, the hashCode will // * be incorrect and the behavior of instances of this pair in such structures // * as hash maps will be undefined (e.g. this pair may seem to "disappear" from // * the hash map, even though it's still there). // * @param first First element of this pair // * @param second Second element of this pair // */ // public SymmetricImmutablePair( // @NonNull final Type first, // @NonNull final Type second) { // // if (first.compareTo(second) < 0) { // this.first = first; // this.second = second; // } // else { // this.first = second; // this.second = first; // } // // this.hashCode = new HashCodeBuilder(541, 7873) // .append(this.first) // .append(this.second) // .toHashCode(); // } // // /** // * {@inheritDoc} // */ // @Override // public int compareTo(final SymmetricImmutablePair<Type> other) { // final int c = first.compareTo(other.first()); // if (0 == c) { // return second.compareTo(other.second()); // } // return c; // } // // /** // * {@inheritDoc} // */ // @Override // public boolean equals(final Object o) { // if (!(o instanceof SymmetricImmutablePair)) { // return false; // } // // @SuppressWarnings("unchecked") // final SymmetricImmutablePair<Type> other = (SymmetricImmutablePair<Type>) o; // return 0 == compareTo(other); // } // // /** // * {@inheritDoc} // */ // @Override // public int hashCode() { // return hashCode; // } // } // Path: src/main/java/com/github/liblevenshtein/distance/MemoizedStandard.java import lombok.val; import com.github.liblevenshtein.collection.SymmetricImmutablePair; package com.github.liblevenshtein.distance; /** * Memoizes the distance between two terms, where the distance is calculated * using the standard Levenshtein distance, including the elementary operations * of insertion, deletion and substitution. * @author Dylon Edwards * @since 2.1.0 */ public class MemoizedStandard extends AbstractMemoized { private static final long serialVersionUID = 1L; /** * {@inheritDoc} */ @Override @SuppressWarnings("checkstyle:finalparameters") public int memoizedDistance(String v, String w) {
val key = new SymmetricImmutablePair<String>(v, w);
universal-automata/liblevenshtein-java
src/test/java/com/github/liblevenshtein/transducer/SpecialPositionComparatorTest.java
// Path: src/test/java/com/github/liblevenshtein/assertion/ComparatorAssertions.java // public static <Type> ComparatorAssertions<Type> assertThat( // final Comparator<Type> actual) { // return new ComparatorAssertions<>(actual); // }
import org.testng.annotations.Test; import static com.github.liblevenshtein.assertion.ComparatorAssertions.assertThat;
package com.github.liblevenshtein.transducer; public class SpecialPositionComparatorTest { private final SpecialPositionComparator comparator = new SpecialPositionComparator(); @Test public void testCompare() {
// Path: src/test/java/com/github/liblevenshtein/assertion/ComparatorAssertions.java // public static <Type> ComparatorAssertions<Type> assertThat( // final Comparator<Type> actual) { // return new ComparatorAssertions<>(actual); // } // Path: src/test/java/com/github/liblevenshtein/transducer/SpecialPositionComparatorTest.java import org.testng.annotations.Test; import static com.github.liblevenshtein.assertion.ComparatorAssertions.assertThat; package com.github.liblevenshtein.transducer; public class SpecialPositionComparatorTest { private final SpecialPositionComparator comparator = new SpecialPositionComparator(); @Test public void testCompare() {
assertThat(comparator)
universal-automata/liblevenshtein-java
src/test/java/com/github/liblevenshtein/assertion/SubsumesFunctionAssertionsTest.java
// Path: src/main/java/com/github/liblevenshtein/transducer/Position.java // @Data // @RequiredArgsConstructor // public class Position implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Reference to the next node in this linked-list. The next node may be null // */ // private Position next = null; // // /** // * Index of the dictionary term represented by this coordinate. // */ // private final int termIndex; // // /** // * Number of accumulated errors at this coordinate. // */ // private final int numErrors; // // /** // * Whether this position should be treated specially, such as whether it // * represents a tranposition, merge, or split. // * @return Whether this position should be treated specially. // */ // public boolean isSpecial() { // return false; // } // } // // Path: src/main/java/com/github/liblevenshtein/transducer/SubsumesFunction.java // public abstract class SubsumesFunction implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Determines whether {@code lhs} subsumes {@code rhs}. // * @param lhs {@link Position} doing the subsumption. // * @param rhs {@link Position} being subsumed. // * @param n Length of the query term. // * @return {@code lhs} subsuem {@code rhs}. // */ // public abstract boolean at(Position lhs, Position rhs, int n); // // /** // * Routines for determining whether a standard position subsumes another. // * @author Dylon Edwards // * @since 2.1.0 // */ // public static class ForStandardAlgorithm extends SubsumesFunction { // // private static final long serialVersionUID = 1L; // // /** // * {@inheritDoc} // */ // @Override // public boolean at(final Position lhs, final Position rhs, final int n) { // final int i = lhs.termIndex(); // final int e = lhs.numErrors(); // final int j = rhs.termIndex(); // final int f = rhs.numErrors(); // return (i < j ? j - i : i - j) <= (f - e); // } // } // // /** // * Routines for determining whether a transposition position subsumes another. // * @author Dylon Edwards // * @since 2.1.0 // */ // public static class ForTransposition extends SubsumesFunction { // // private static final long serialVersionUID = 1L; // // /** // * {@inheritDoc} // */ // @Override // public boolean at(final Position lhs, final Position rhs, final int n) { // final int i = lhs.termIndex(); // final int e = lhs.numErrors(); // final boolean s = lhs.isSpecial(); // final int j = rhs.termIndex(); // final int f = rhs.numErrors(); // final boolean t = rhs.isSpecial(); // // if (s) { // if (t) { // return i == j; // } // // return f == n && i == j; // } // // if (t) { // // We have two cases: // // // // Case 1: (j < i) => (j - i) = - (i - j) // // => |j - (i - 1)| = |j - i + 1| // // = |-(i - j) + 1| // // = |-(i - j - 1)| // // = i - j - 1 // // // // Case 1 holds, because i and j are integers, and j < i implies i is at // // least 1 unit greater than j, further implying that i - j - 1 is // // non-negative. // // // // Case 2: (j >= i) => |j - (i - 1)| = |j - i + 1| = j - i + 1 // // // // Case 2 holds for the same reason case 1 does, in that j - i >= 0, and // // adding 1 to the difference will only strengthen its non-negativity. // // // //return Math.abs(j - (i - 1)) <= (f - e); // return (j < i ? i - j - 1 : j - i + 1) <= (f - e); // } // // return (i < j ? j - i : i - j) <= (f - e); // } // } // // /** // * Routines for determining whether a merge-and-split position subsumes another. // * @author Dylon Edwards // * @since 2.1.0 // */ // public static class ForMergeAndSplit extends SubsumesFunction { // // private static final long serialVersionUID = 1L; // // /** // * {@inheritDoc} // */ // @Override // public boolean at(final Position lhs, final Position rhs, final int n) { // final int i = lhs.termIndex(); // final int e = lhs.numErrors(); // final boolean s = lhs.isSpecial(); // final int j = rhs.termIndex(); // final int f = rhs.numErrors(); // final boolean t = rhs.isSpecial(); // // if (s && !t) { // return false; // } // // return (i < j ? j - i : i - j) <= (f - e); // } // } // } // // Path: src/test/java/com/github/liblevenshtein/assertion/SubsumesFunctionAssertions.java // public static SubsumesFunctionAssertions assertThat( // final SubsumesFunction actual) { // return new SubsumesFunctionAssertions(actual); // }
import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import com.github.liblevenshtein.transducer.Position; import com.github.liblevenshtein.transducer.SubsumesFunction; import static com.github.liblevenshtein.assertion.SubsumesFunctionAssertions.assertThat;
package com.github.liblevenshtein.assertion; public class SubsumesFunctionAssertionsTest { private static final int TERM_LENGTH = 4;
// Path: src/main/java/com/github/liblevenshtein/transducer/Position.java // @Data // @RequiredArgsConstructor // public class Position implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Reference to the next node in this linked-list. The next node may be null // */ // private Position next = null; // // /** // * Index of the dictionary term represented by this coordinate. // */ // private final int termIndex; // // /** // * Number of accumulated errors at this coordinate. // */ // private final int numErrors; // // /** // * Whether this position should be treated specially, such as whether it // * represents a tranposition, merge, or split. // * @return Whether this position should be treated specially. // */ // public boolean isSpecial() { // return false; // } // } // // Path: src/main/java/com/github/liblevenshtein/transducer/SubsumesFunction.java // public abstract class SubsumesFunction implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Determines whether {@code lhs} subsumes {@code rhs}. // * @param lhs {@link Position} doing the subsumption. // * @param rhs {@link Position} being subsumed. // * @param n Length of the query term. // * @return {@code lhs} subsuem {@code rhs}. // */ // public abstract boolean at(Position lhs, Position rhs, int n); // // /** // * Routines for determining whether a standard position subsumes another. // * @author Dylon Edwards // * @since 2.1.0 // */ // public static class ForStandardAlgorithm extends SubsumesFunction { // // private static final long serialVersionUID = 1L; // // /** // * {@inheritDoc} // */ // @Override // public boolean at(final Position lhs, final Position rhs, final int n) { // final int i = lhs.termIndex(); // final int e = lhs.numErrors(); // final int j = rhs.termIndex(); // final int f = rhs.numErrors(); // return (i < j ? j - i : i - j) <= (f - e); // } // } // // /** // * Routines for determining whether a transposition position subsumes another. // * @author Dylon Edwards // * @since 2.1.0 // */ // public static class ForTransposition extends SubsumesFunction { // // private static final long serialVersionUID = 1L; // // /** // * {@inheritDoc} // */ // @Override // public boolean at(final Position lhs, final Position rhs, final int n) { // final int i = lhs.termIndex(); // final int e = lhs.numErrors(); // final boolean s = lhs.isSpecial(); // final int j = rhs.termIndex(); // final int f = rhs.numErrors(); // final boolean t = rhs.isSpecial(); // // if (s) { // if (t) { // return i == j; // } // // return f == n && i == j; // } // // if (t) { // // We have two cases: // // // // Case 1: (j < i) => (j - i) = - (i - j) // // => |j - (i - 1)| = |j - i + 1| // // = |-(i - j) + 1| // // = |-(i - j - 1)| // // = i - j - 1 // // // // Case 1 holds, because i and j are integers, and j < i implies i is at // // least 1 unit greater than j, further implying that i - j - 1 is // // non-negative. // // // // Case 2: (j >= i) => |j - (i - 1)| = |j - i + 1| = j - i + 1 // // // // Case 2 holds for the same reason case 1 does, in that j - i >= 0, and // // adding 1 to the difference will only strengthen its non-negativity. // // // //return Math.abs(j - (i - 1)) <= (f - e); // return (j < i ? i - j - 1 : j - i + 1) <= (f - e); // } // // return (i < j ? j - i : i - j) <= (f - e); // } // } // // /** // * Routines for determining whether a merge-and-split position subsumes another. // * @author Dylon Edwards // * @since 2.1.0 // */ // public static class ForMergeAndSplit extends SubsumesFunction { // // private static final long serialVersionUID = 1L; // // /** // * {@inheritDoc} // */ // @Override // public boolean at(final Position lhs, final Position rhs, final int n) { // final int i = lhs.termIndex(); // final int e = lhs.numErrors(); // final boolean s = lhs.isSpecial(); // final int j = rhs.termIndex(); // final int f = rhs.numErrors(); // final boolean t = rhs.isSpecial(); // // if (s && !t) { // return false; // } // // return (i < j ? j - i : i - j) <= (f - e); // } // } // } // // Path: src/test/java/com/github/liblevenshtein/assertion/SubsumesFunctionAssertions.java // public static SubsumesFunctionAssertions assertThat( // final SubsumesFunction actual) { // return new SubsumesFunctionAssertions(actual); // } // Path: src/test/java/com/github/liblevenshtein/assertion/SubsumesFunctionAssertionsTest.java import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import com.github.liblevenshtein.transducer.Position; import com.github.liblevenshtein.transducer.SubsumesFunction; import static com.github.liblevenshtein.assertion.SubsumesFunctionAssertions.assertThat; package com.github.liblevenshtein.assertion; public class SubsumesFunctionAssertionsTest { private static final int TERM_LENGTH = 4;
private final ThreadLocal<SubsumesFunction> standardSubsumes = new ThreadLocal<>();
universal-automata/liblevenshtein-java
src/test/java/com/github/liblevenshtein/assertion/SubsumesFunctionAssertionsTest.java
// Path: src/main/java/com/github/liblevenshtein/transducer/Position.java // @Data // @RequiredArgsConstructor // public class Position implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Reference to the next node in this linked-list. The next node may be null // */ // private Position next = null; // // /** // * Index of the dictionary term represented by this coordinate. // */ // private final int termIndex; // // /** // * Number of accumulated errors at this coordinate. // */ // private final int numErrors; // // /** // * Whether this position should be treated specially, such as whether it // * represents a tranposition, merge, or split. // * @return Whether this position should be treated specially. // */ // public boolean isSpecial() { // return false; // } // } // // Path: src/main/java/com/github/liblevenshtein/transducer/SubsumesFunction.java // public abstract class SubsumesFunction implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Determines whether {@code lhs} subsumes {@code rhs}. // * @param lhs {@link Position} doing the subsumption. // * @param rhs {@link Position} being subsumed. // * @param n Length of the query term. // * @return {@code lhs} subsuem {@code rhs}. // */ // public abstract boolean at(Position lhs, Position rhs, int n); // // /** // * Routines for determining whether a standard position subsumes another. // * @author Dylon Edwards // * @since 2.1.0 // */ // public static class ForStandardAlgorithm extends SubsumesFunction { // // private static final long serialVersionUID = 1L; // // /** // * {@inheritDoc} // */ // @Override // public boolean at(final Position lhs, final Position rhs, final int n) { // final int i = lhs.termIndex(); // final int e = lhs.numErrors(); // final int j = rhs.termIndex(); // final int f = rhs.numErrors(); // return (i < j ? j - i : i - j) <= (f - e); // } // } // // /** // * Routines for determining whether a transposition position subsumes another. // * @author Dylon Edwards // * @since 2.1.0 // */ // public static class ForTransposition extends SubsumesFunction { // // private static final long serialVersionUID = 1L; // // /** // * {@inheritDoc} // */ // @Override // public boolean at(final Position lhs, final Position rhs, final int n) { // final int i = lhs.termIndex(); // final int e = lhs.numErrors(); // final boolean s = lhs.isSpecial(); // final int j = rhs.termIndex(); // final int f = rhs.numErrors(); // final boolean t = rhs.isSpecial(); // // if (s) { // if (t) { // return i == j; // } // // return f == n && i == j; // } // // if (t) { // // We have two cases: // // // // Case 1: (j < i) => (j - i) = - (i - j) // // => |j - (i - 1)| = |j - i + 1| // // = |-(i - j) + 1| // // = |-(i - j - 1)| // // = i - j - 1 // // // // Case 1 holds, because i and j are integers, and j < i implies i is at // // least 1 unit greater than j, further implying that i - j - 1 is // // non-negative. // // // // Case 2: (j >= i) => |j - (i - 1)| = |j - i + 1| = j - i + 1 // // // // Case 2 holds for the same reason case 1 does, in that j - i >= 0, and // // adding 1 to the difference will only strengthen its non-negativity. // // // //return Math.abs(j - (i - 1)) <= (f - e); // return (j < i ? i - j - 1 : j - i + 1) <= (f - e); // } // // return (i < j ? j - i : i - j) <= (f - e); // } // } // // /** // * Routines for determining whether a merge-and-split position subsumes another. // * @author Dylon Edwards // * @since 2.1.0 // */ // public static class ForMergeAndSplit extends SubsumesFunction { // // private static final long serialVersionUID = 1L; // // /** // * {@inheritDoc} // */ // @Override // public boolean at(final Position lhs, final Position rhs, final int n) { // final int i = lhs.termIndex(); // final int e = lhs.numErrors(); // final boolean s = lhs.isSpecial(); // final int j = rhs.termIndex(); // final int f = rhs.numErrors(); // final boolean t = rhs.isSpecial(); // // if (s && !t) { // return false; // } // // return (i < j ? j - i : i - j) <= (f - e); // } // } // } // // Path: src/test/java/com/github/liblevenshtein/assertion/SubsumesFunctionAssertions.java // public static SubsumesFunctionAssertions assertThat( // final SubsumesFunction actual) { // return new SubsumesFunctionAssertions(actual); // }
import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import com.github.liblevenshtein.transducer.Position; import com.github.liblevenshtein.transducer.SubsumesFunction; import static com.github.liblevenshtein.assertion.SubsumesFunctionAssertions.assertThat;
package com.github.liblevenshtein.assertion; public class SubsumesFunctionAssertionsTest { private static final int TERM_LENGTH = 4; private final ThreadLocal<SubsumesFunction> standardSubsumes = new ThreadLocal<>(); private final ThreadLocal<SubsumesFunction> specialSubsumes = new ThreadLocal<>();
// Path: src/main/java/com/github/liblevenshtein/transducer/Position.java // @Data // @RequiredArgsConstructor // public class Position implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Reference to the next node in this linked-list. The next node may be null // */ // private Position next = null; // // /** // * Index of the dictionary term represented by this coordinate. // */ // private final int termIndex; // // /** // * Number of accumulated errors at this coordinate. // */ // private final int numErrors; // // /** // * Whether this position should be treated specially, such as whether it // * represents a tranposition, merge, or split. // * @return Whether this position should be treated specially. // */ // public boolean isSpecial() { // return false; // } // } // // Path: src/main/java/com/github/liblevenshtein/transducer/SubsumesFunction.java // public abstract class SubsumesFunction implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Determines whether {@code lhs} subsumes {@code rhs}. // * @param lhs {@link Position} doing the subsumption. // * @param rhs {@link Position} being subsumed. // * @param n Length of the query term. // * @return {@code lhs} subsuem {@code rhs}. // */ // public abstract boolean at(Position lhs, Position rhs, int n); // // /** // * Routines for determining whether a standard position subsumes another. // * @author Dylon Edwards // * @since 2.1.0 // */ // public static class ForStandardAlgorithm extends SubsumesFunction { // // private static final long serialVersionUID = 1L; // // /** // * {@inheritDoc} // */ // @Override // public boolean at(final Position lhs, final Position rhs, final int n) { // final int i = lhs.termIndex(); // final int e = lhs.numErrors(); // final int j = rhs.termIndex(); // final int f = rhs.numErrors(); // return (i < j ? j - i : i - j) <= (f - e); // } // } // // /** // * Routines for determining whether a transposition position subsumes another. // * @author Dylon Edwards // * @since 2.1.0 // */ // public static class ForTransposition extends SubsumesFunction { // // private static final long serialVersionUID = 1L; // // /** // * {@inheritDoc} // */ // @Override // public boolean at(final Position lhs, final Position rhs, final int n) { // final int i = lhs.termIndex(); // final int e = lhs.numErrors(); // final boolean s = lhs.isSpecial(); // final int j = rhs.termIndex(); // final int f = rhs.numErrors(); // final boolean t = rhs.isSpecial(); // // if (s) { // if (t) { // return i == j; // } // // return f == n && i == j; // } // // if (t) { // // We have two cases: // // // // Case 1: (j < i) => (j - i) = - (i - j) // // => |j - (i - 1)| = |j - i + 1| // // = |-(i - j) + 1| // // = |-(i - j - 1)| // // = i - j - 1 // // // // Case 1 holds, because i and j are integers, and j < i implies i is at // // least 1 unit greater than j, further implying that i - j - 1 is // // non-negative. // // // // Case 2: (j >= i) => |j - (i - 1)| = |j - i + 1| = j - i + 1 // // // // Case 2 holds for the same reason case 1 does, in that j - i >= 0, and // // adding 1 to the difference will only strengthen its non-negativity. // // // //return Math.abs(j - (i - 1)) <= (f - e); // return (j < i ? i - j - 1 : j - i + 1) <= (f - e); // } // // return (i < j ? j - i : i - j) <= (f - e); // } // } // // /** // * Routines for determining whether a merge-and-split position subsumes another. // * @author Dylon Edwards // * @since 2.1.0 // */ // public static class ForMergeAndSplit extends SubsumesFunction { // // private static final long serialVersionUID = 1L; // // /** // * {@inheritDoc} // */ // @Override // public boolean at(final Position lhs, final Position rhs, final int n) { // final int i = lhs.termIndex(); // final int e = lhs.numErrors(); // final boolean s = lhs.isSpecial(); // final int j = rhs.termIndex(); // final int f = rhs.numErrors(); // final boolean t = rhs.isSpecial(); // // if (s && !t) { // return false; // } // // return (i < j ? j - i : i - j) <= (f - e); // } // } // } // // Path: src/test/java/com/github/liblevenshtein/assertion/SubsumesFunctionAssertions.java // public static SubsumesFunctionAssertions assertThat( // final SubsumesFunction actual) { // return new SubsumesFunctionAssertions(actual); // } // Path: src/test/java/com/github/liblevenshtein/assertion/SubsumesFunctionAssertionsTest.java import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import com.github.liblevenshtein.transducer.Position; import com.github.liblevenshtein.transducer.SubsumesFunction; import static com.github.liblevenshtein.assertion.SubsumesFunctionAssertions.assertThat; package com.github.liblevenshtein.assertion; public class SubsumesFunctionAssertionsTest { private static final int TERM_LENGTH = 4; private final ThreadLocal<SubsumesFunction> standardSubsumes = new ThreadLocal<>(); private final ThreadLocal<SubsumesFunction> specialSubsumes = new ThreadLocal<>();
private final ThreadLocal<Position> lhs = new ThreadLocal<>();
universal-automata/liblevenshtein-java
src/test/java/com/github/liblevenshtein/transducer/SubsumesFunctionTest.java
// Path: src/main/java/com/github/liblevenshtein/transducer/factory/PositionFactory.java // @NoArgsConstructor // public class PositionFactory implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Builds a dummy position. // * @return Dummy position. // */ // public Position build() { // return new Position(-1, -1); // } // // /** // * Builds a position vector for the standard, Levenshtein algorihtm. // * @param termIndex Current index of the spelling candidate. // * @param numErrors Number of accumulated errors at index {@code termIndex}. // * @return New position vector having index {@code termIndex} and error // * {@code numErrors}. // */ // public Position build(final int termIndex, final int numErrors) { // return new Position(termIndex, numErrors); // } // // /** // * Builds a position vector for the transposition and merge-and-split, // * Levenshtein algorihtms. // * @param termIndex Current index of the spelling candidate. // * @param numErrors Number of accumulated errors at index {@code termIndex}. // * @param isSpecial Either {@code 1} or {@code 0}, depending on whether the // * position is a special case (numErrors.g. a transposition position). // * @return New position vector having index {@code termIndex}, error // * {@code numErrors}, and special marker {@code isSpecial}. // */ // public Position build(final int termIndex, final int numErrors, final boolean isSpecial) { // if (isSpecial) { // return new SpecialPosition(termIndex, numErrors); // } // // return new Position(termIndex, numErrors); // } // } // // Path: src/test/java/com/github/liblevenshtein/assertion/SubsumesFunctionAssertions.java // public static SubsumesFunctionAssertions assertThat( // final SubsumesFunction actual) { // return new SubsumesFunctionAssertions(actual); // }
import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import com.github.liblevenshtein.transducer.factory.PositionFactory; import static com.github.liblevenshtein.assertion.SubsumesFunctionAssertions.assertThat;
{1, 1, false, 1, 2, false, 4, true}, {3, 1, false, 0, 2, true, 4, false}, {1, 1, false, 0, 2, true, 4, true}, {3, 3, true, 3, 3, false, 4, false}, {4, 4, true, 4, 4, false, 4, true}, {1, 1, true, 2, 1, true, 4, false}, {1, 1, true, 1, 1, true, 4, true}, }; } @DataProvider(name = "forMergeAndSplit") public Object[][] forMergeAndSplit() { return new Object[][] { {1, 1, false, 1, 0, false, 4, false}, {1, 1, false, 1, 1, false, 4, true}, {1, 1, false, 1, 0, true, 4, false}, {1, 1, false, 1, 1, true, 4, true}, {1, 1, true, 1, 0, false, 4, false}, {1, 1, true, 1, 1, false, 4, false}, {1, 1, true, 1, 0, true, 4, false}, {1, 1, true, 1, 1, true, 4, true}, }; } @Test(dataProvider = "forStandardAlgorithm") public void testForStandardAlgorithm( final int i, final int e, final int j, final int f, final int n, final boolean shouldSubsume) {
// Path: src/main/java/com/github/liblevenshtein/transducer/factory/PositionFactory.java // @NoArgsConstructor // public class PositionFactory implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Builds a dummy position. // * @return Dummy position. // */ // public Position build() { // return new Position(-1, -1); // } // // /** // * Builds a position vector for the standard, Levenshtein algorihtm. // * @param termIndex Current index of the spelling candidate. // * @param numErrors Number of accumulated errors at index {@code termIndex}. // * @return New position vector having index {@code termIndex} and error // * {@code numErrors}. // */ // public Position build(final int termIndex, final int numErrors) { // return new Position(termIndex, numErrors); // } // // /** // * Builds a position vector for the transposition and merge-and-split, // * Levenshtein algorihtms. // * @param termIndex Current index of the spelling candidate. // * @param numErrors Number of accumulated errors at index {@code termIndex}. // * @param isSpecial Either {@code 1} or {@code 0}, depending on whether the // * position is a special case (numErrors.g. a transposition position). // * @return New position vector having index {@code termIndex}, error // * {@code numErrors}, and special marker {@code isSpecial}. // */ // public Position build(final int termIndex, final int numErrors, final boolean isSpecial) { // if (isSpecial) { // return new SpecialPosition(termIndex, numErrors); // } // // return new Position(termIndex, numErrors); // } // } // // Path: src/test/java/com/github/liblevenshtein/assertion/SubsumesFunctionAssertions.java // public static SubsumesFunctionAssertions assertThat( // final SubsumesFunction actual) { // return new SubsumesFunctionAssertions(actual); // } // Path: src/test/java/com/github/liblevenshtein/transducer/SubsumesFunctionTest.java import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import com.github.liblevenshtein.transducer.factory.PositionFactory; import static com.github.liblevenshtein.assertion.SubsumesFunctionAssertions.assertThat; {1, 1, false, 1, 2, false, 4, true}, {3, 1, false, 0, 2, true, 4, false}, {1, 1, false, 0, 2, true, 4, true}, {3, 3, true, 3, 3, false, 4, false}, {4, 4, true, 4, 4, false, 4, true}, {1, 1, true, 2, 1, true, 4, false}, {1, 1, true, 1, 1, true, 4, true}, }; } @DataProvider(name = "forMergeAndSplit") public Object[][] forMergeAndSplit() { return new Object[][] { {1, 1, false, 1, 0, false, 4, false}, {1, 1, false, 1, 1, false, 4, true}, {1, 1, false, 1, 0, true, 4, false}, {1, 1, false, 1, 1, true, 4, true}, {1, 1, true, 1, 0, false, 4, false}, {1, 1, true, 1, 1, false, 4, false}, {1, 1, true, 1, 0, true, 4, false}, {1, 1, true, 1, 1, true, 4, true}, }; } @Test(dataProvider = "forStandardAlgorithm") public void testForStandardAlgorithm( final int i, final int e, final int j, final int f, final int n, final boolean shouldSubsume) {
assertThat(standardSubsumes)
universal-automata/liblevenshtein-java
src/test/java/com/github/liblevenshtein/transducer/StandardPositionTransitionFunctionTest.java
// Path: src/main/java/com/github/liblevenshtein/transducer/factory/PositionFactory.java // @NoArgsConstructor // public class PositionFactory implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Builds a dummy position. // * @return Dummy position. // */ // public Position build() { // return new Position(-1, -1); // } // // /** // * Builds a position vector for the standard, Levenshtein algorihtm. // * @param termIndex Current index of the spelling candidate. // * @param numErrors Number of accumulated errors at index {@code termIndex}. // * @return New position vector having index {@code termIndex} and error // * {@code numErrors}. // */ // public Position build(final int termIndex, final int numErrors) { // return new Position(termIndex, numErrors); // } // // /** // * Builds a position vector for the transposition and merge-and-split, // * Levenshtein algorihtms. // * @param termIndex Current index of the spelling candidate. // * @param numErrors Number of accumulated errors at index {@code termIndex}. // * @param isSpecial Either {@code 1} or {@code 0}, depending on whether the // * position is a special case (numErrors.g. a transposition position). // * @return New position vector having index {@code termIndex}, error // * {@code numErrors}, and special marker {@code isSpecial}. // */ // public Position build(final int termIndex, final int numErrors, final boolean isSpecial) { // if (isSpecial) { // return new SpecialPosition(termIndex, numErrors); // } // // return new Position(termIndex, numErrors); // } // } // // Path: src/main/java/com/github/liblevenshtein/transducer/factory/StateFactory.java // public class StateFactory implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Builds a new, Levenshtein state with the given position vectors. // * @param positions Array of position vectors to link into the state. // * @return New state having the position vectors. // */ // public State build(final Position... positions) { // final State state = new State(); // // Position prev = null; // for (final Position curr : positions) { // state.insertAfter(prev, curr); // prev = curr; // } // // return state; // } // } // // Path: src/test/java/com/github/liblevenshtein/assertion/StandardPositionTransitionFunctionAssertions.java // public static StandardPositionTransitionFunctionAssertions assertThat( // final StandardPositionTransitionFunction actual) { // return new StandardPositionTransitionFunctionAssertions(actual); // }
import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import com.github.liblevenshtein.transducer.factory.PositionFactory; import com.github.liblevenshtein.transducer.factory.StateFactory; import static com.github.liblevenshtein.assertion.StandardPositionTransitionFunctionAssertions.assertThat;
package com.github.liblevenshtein.transducer; public class StandardPositionTransitionFunctionTest { private static final int N = 2; // max number of errors private static final int W = 4; // length of characteristic vector
// Path: src/main/java/com/github/liblevenshtein/transducer/factory/PositionFactory.java // @NoArgsConstructor // public class PositionFactory implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Builds a dummy position. // * @return Dummy position. // */ // public Position build() { // return new Position(-1, -1); // } // // /** // * Builds a position vector for the standard, Levenshtein algorihtm. // * @param termIndex Current index of the spelling candidate. // * @param numErrors Number of accumulated errors at index {@code termIndex}. // * @return New position vector having index {@code termIndex} and error // * {@code numErrors}. // */ // public Position build(final int termIndex, final int numErrors) { // return new Position(termIndex, numErrors); // } // // /** // * Builds a position vector for the transposition and merge-and-split, // * Levenshtein algorihtms. // * @param termIndex Current index of the spelling candidate. // * @param numErrors Number of accumulated errors at index {@code termIndex}. // * @param isSpecial Either {@code 1} or {@code 0}, depending on whether the // * position is a special case (numErrors.g. a transposition position). // * @return New position vector having index {@code termIndex}, error // * {@code numErrors}, and special marker {@code isSpecial}. // */ // public Position build(final int termIndex, final int numErrors, final boolean isSpecial) { // if (isSpecial) { // return new SpecialPosition(termIndex, numErrors); // } // // return new Position(termIndex, numErrors); // } // } // // Path: src/main/java/com/github/liblevenshtein/transducer/factory/StateFactory.java // public class StateFactory implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Builds a new, Levenshtein state with the given position vectors. // * @param positions Array of position vectors to link into the state. // * @return New state having the position vectors. // */ // public State build(final Position... positions) { // final State state = new State(); // // Position prev = null; // for (final Position curr : positions) { // state.insertAfter(prev, curr); // prev = curr; // } // // return state; // } // } // // Path: src/test/java/com/github/liblevenshtein/assertion/StandardPositionTransitionFunctionAssertions.java // public static StandardPositionTransitionFunctionAssertions assertThat( // final StandardPositionTransitionFunction actual) { // return new StandardPositionTransitionFunctionAssertions(actual); // } // Path: src/test/java/com/github/liblevenshtein/transducer/StandardPositionTransitionFunctionTest.java import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import com.github.liblevenshtein.transducer.factory.PositionFactory; import com.github.liblevenshtein.transducer.factory.StateFactory; import static com.github.liblevenshtein.assertion.StandardPositionTransitionFunctionAssertions.assertThat; package com.github.liblevenshtein.transducer; public class StandardPositionTransitionFunctionTest { private static final int N = 2; // max number of errors private static final int W = 4; // length of characteristic vector
private final StateFactory stateFactory = new StateFactory();
universal-automata/liblevenshtein-java
src/test/java/com/github/liblevenshtein/transducer/StandardPositionTransitionFunctionTest.java
// Path: src/main/java/com/github/liblevenshtein/transducer/factory/PositionFactory.java // @NoArgsConstructor // public class PositionFactory implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Builds a dummy position. // * @return Dummy position. // */ // public Position build() { // return new Position(-1, -1); // } // // /** // * Builds a position vector for the standard, Levenshtein algorihtm. // * @param termIndex Current index of the spelling candidate. // * @param numErrors Number of accumulated errors at index {@code termIndex}. // * @return New position vector having index {@code termIndex} and error // * {@code numErrors}. // */ // public Position build(final int termIndex, final int numErrors) { // return new Position(termIndex, numErrors); // } // // /** // * Builds a position vector for the transposition and merge-and-split, // * Levenshtein algorihtms. // * @param termIndex Current index of the spelling candidate. // * @param numErrors Number of accumulated errors at index {@code termIndex}. // * @param isSpecial Either {@code 1} or {@code 0}, depending on whether the // * position is a special case (numErrors.g. a transposition position). // * @return New position vector having index {@code termIndex}, error // * {@code numErrors}, and special marker {@code isSpecial}. // */ // public Position build(final int termIndex, final int numErrors, final boolean isSpecial) { // if (isSpecial) { // return new SpecialPosition(termIndex, numErrors); // } // // return new Position(termIndex, numErrors); // } // } // // Path: src/main/java/com/github/liblevenshtein/transducer/factory/StateFactory.java // public class StateFactory implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Builds a new, Levenshtein state with the given position vectors. // * @param positions Array of position vectors to link into the state. // * @return New state having the position vectors. // */ // public State build(final Position... positions) { // final State state = new State(); // // Position prev = null; // for (final Position curr : positions) { // state.insertAfter(prev, curr); // prev = curr; // } // // return state; // } // } // // Path: src/test/java/com/github/liblevenshtein/assertion/StandardPositionTransitionFunctionAssertions.java // public static StandardPositionTransitionFunctionAssertions assertThat( // final StandardPositionTransitionFunction actual) { // return new StandardPositionTransitionFunctionAssertions(actual); // }
import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import com.github.liblevenshtein.transducer.factory.PositionFactory; import com.github.liblevenshtein.transducer.factory.StateFactory; import static com.github.liblevenshtein.assertion.StandardPositionTransitionFunctionAssertions.assertThat;
package com.github.liblevenshtein.transducer; public class StandardPositionTransitionFunctionTest { private static final int N = 2; // max number of errors private static final int W = 4; // length of characteristic vector private final StateFactory stateFactory = new StateFactory();
// Path: src/main/java/com/github/liblevenshtein/transducer/factory/PositionFactory.java // @NoArgsConstructor // public class PositionFactory implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Builds a dummy position. // * @return Dummy position. // */ // public Position build() { // return new Position(-1, -1); // } // // /** // * Builds a position vector for the standard, Levenshtein algorihtm. // * @param termIndex Current index of the spelling candidate. // * @param numErrors Number of accumulated errors at index {@code termIndex}. // * @return New position vector having index {@code termIndex} and error // * {@code numErrors}. // */ // public Position build(final int termIndex, final int numErrors) { // return new Position(termIndex, numErrors); // } // // /** // * Builds a position vector for the transposition and merge-and-split, // * Levenshtein algorihtms. // * @param termIndex Current index of the spelling candidate. // * @param numErrors Number of accumulated errors at index {@code termIndex}. // * @param isSpecial Either {@code 1} or {@code 0}, depending on whether the // * position is a special case (numErrors.g. a transposition position). // * @return New position vector having index {@code termIndex}, error // * {@code numErrors}, and special marker {@code isSpecial}. // */ // public Position build(final int termIndex, final int numErrors, final boolean isSpecial) { // if (isSpecial) { // return new SpecialPosition(termIndex, numErrors); // } // // return new Position(termIndex, numErrors); // } // } // // Path: src/main/java/com/github/liblevenshtein/transducer/factory/StateFactory.java // public class StateFactory implements Serializable { // // private static final long serialVersionUID = 1L; // // /** // * Builds a new, Levenshtein state with the given position vectors. // * @param positions Array of position vectors to link into the state. // * @return New state having the position vectors. // */ // public State build(final Position... positions) { // final State state = new State(); // // Position prev = null; // for (final Position curr : positions) { // state.insertAfter(prev, curr); // prev = curr; // } // // return state; // } // } // // Path: src/test/java/com/github/liblevenshtein/assertion/StandardPositionTransitionFunctionAssertions.java // public static StandardPositionTransitionFunctionAssertions assertThat( // final StandardPositionTransitionFunction actual) { // return new StandardPositionTransitionFunctionAssertions(actual); // } // Path: src/test/java/com/github/liblevenshtein/transducer/StandardPositionTransitionFunctionTest.java import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import com.github.liblevenshtein.transducer.factory.PositionFactory; import com.github.liblevenshtein.transducer.factory.StateFactory; import static com.github.liblevenshtein.assertion.StandardPositionTransitionFunctionAssertions.assertThat; package com.github.liblevenshtein.transducer; public class StandardPositionTransitionFunctionTest { private static final int N = 2; // max number of errors private static final int W = 4; // length of characteristic vector private final StateFactory stateFactory = new StateFactory();
private final PositionFactory positionFactory = new PositionFactory();