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
52North/Supervisor
json/src/main/java/org/n52/supervisor/checks/json/EnviroCarRunnerFactory.java
// Path: core/src/main/java/org/n52/supervisor/api/Check.java // @XmlRootElement // public abstract class Check { // // private String identifier; // // private String notificationEmail; // // protected String type = "GenericCheck"; // // /* // * injects only work on objects created by Guice. // * this is most likely not the case for Checkers. // */ // // @Inject // // @Named(SupervisorProperties.DEFAULT_CHECK_INTERVAL) // private long intervalSeconds; // // public Check() { // // required for jaxb // } // // public Check(String identifier) { // super(); // this.identifier = identifier; // } // // public Check(String notificationEmail, long intervalSeconds) { // this(); // this.notificationEmail = notificationEmail; // this.intervalSeconds = intervalSeconds; // } // // public Check(String identifier, String notificationEmail, long intervalSeconds) { // this(identifier); // this.notificationEmail = notificationEmail; // this.intervalSeconds = intervalSeconds; // } // // public String getIdentifier() { // return identifier; // } // // public long getIntervalSeconds() { // return intervalSeconds; // } // // public String getNotificationEmail() { // return notificationEmail; // } // // public String getType() { // return type; // } // // public void setIdentifier(String identifier) { // this.identifier = identifier; // } // // public void setIntervalSeconds(long intervalMillis) { // this.intervalSeconds = intervalMillis; // } // // public void setNotificationEmail(String notificationEmail) { // this.notificationEmail = notificationEmail; // } // // public void setType(String type) { // this.type = type; // } // // } // // Path: core/src/main/java/org/n52/supervisor/api/CheckRunner.java // public interface CheckRunner { // // final IdentifierGenerator ID_GENERATOR = new ShortAlphanumericIdentifierGenerator(); // // public void addResult(CheckResult r); // // public boolean check(); // // public Check getCheck(); // // public Collection<CheckResult> getResults(); // // public Collection<CheckResult> getAndClearResults(); // // public void notifyFailure(); // // public void notifySuccess(); // // public void setCheck(Check check) throws UnsupportedCheckException; // // /** // * @param rd // * is required so that the runner can announce its results // */ // public void setResultDatabase(ResultDatabase rd); // // } // // Path: core/src/main/java/org/n52/supervisor/checks/RunnerFactory.java // public interface RunnerFactory { // // CheckRunner resolveRunner(Check check); // // }
import org.n52.supervisor.api.Check; import org.n52.supervisor.api.CheckRunner; import org.n52.supervisor.checks.RunnerFactory;
/** * Copyright (C) 2013 - 2014 52°North Initiative for Geospatial Open Source Software GmbH * * 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.n52.supervisor.checks.json; public class EnviroCarRunnerFactory implements RunnerFactory { @Override
// Path: core/src/main/java/org/n52/supervisor/api/Check.java // @XmlRootElement // public abstract class Check { // // private String identifier; // // private String notificationEmail; // // protected String type = "GenericCheck"; // // /* // * injects only work on objects created by Guice. // * this is most likely not the case for Checkers. // */ // // @Inject // // @Named(SupervisorProperties.DEFAULT_CHECK_INTERVAL) // private long intervalSeconds; // // public Check() { // // required for jaxb // } // // public Check(String identifier) { // super(); // this.identifier = identifier; // } // // public Check(String notificationEmail, long intervalSeconds) { // this(); // this.notificationEmail = notificationEmail; // this.intervalSeconds = intervalSeconds; // } // // public Check(String identifier, String notificationEmail, long intervalSeconds) { // this(identifier); // this.notificationEmail = notificationEmail; // this.intervalSeconds = intervalSeconds; // } // // public String getIdentifier() { // return identifier; // } // // public long getIntervalSeconds() { // return intervalSeconds; // } // // public String getNotificationEmail() { // return notificationEmail; // } // // public String getType() { // return type; // } // // public void setIdentifier(String identifier) { // this.identifier = identifier; // } // // public void setIntervalSeconds(long intervalMillis) { // this.intervalSeconds = intervalMillis; // } // // public void setNotificationEmail(String notificationEmail) { // this.notificationEmail = notificationEmail; // } // // public void setType(String type) { // this.type = type; // } // // } // // Path: core/src/main/java/org/n52/supervisor/api/CheckRunner.java // public interface CheckRunner { // // final IdentifierGenerator ID_GENERATOR = new ShortAlphanumericIdentifierGenerator(); // // public void addResult(CheckResult r); // // public boolean check(); // // public Check getCheck(); // // public Collection<CheckResult> getResults(); // // public Collection<CheckResult> getAndClearResults(); // // public void notifyFailure(); // // public void notifySuccess(); // // public void setCheck(Check check) throws UnsupportedCheckException; // // /** // * @param rd // * is required so that the runner can announce its results // */ // public void setResultDatabase(ResultDatabase rd); // // } // // Path: core/src/main/java/org/n52/supervisor/checks/RunnerFactory.java // public interface RunnerFactory { // // CheckRunner resolveRunner(Check check); // // } // Path: json/src/main/java/org/n52/supervisor/checks/json/EnviroCarRunnerFactory.java import org.n52.supervisor.api.Check; import org.n52.supervisor.api.CheckRunner; import org.n52.supervisor.checks.RunnerFactory; /** * Copyright (C) 2013 - 2014 52°North Initiative for Geospatial Open Source Software GmbH * * 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.n52.supervisor.checks.json; public class EnviroCarRunnerFactory implements RunnerFactory { @Override
public CheckRunner resolveRunner(Check check) {
52North/Supervisor
json/src/main/java/org/n52/supervisor/checks/json/EnviroCarModule.java
// Path: core/src/main/java/org/n52/supervisor/checks/RunnerFactory.java // public interface RunnerFactory { // // CheckRunner resolveRunner(Check check); // // }
import org.n52.supervisor.checks.RunnerFactory; import com.google.inject.AbstractModule; import com.google.inject.multibindings.Multibinder;
/** * Copyright (C) 2013 - 2014 52°North Initiative for Geospatial Open Source Software GmbH * * 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.n52.supervisor.checks.json; public class EnviroCarModule extends AbstractModule { @Override protected void configure() {
// Path: core/src/main/java/org/n52/supervisor/checks/RunnerFactory.java // public interface RunnerFactory { // // CheckRunner resolveRunner(Check check); // // } // Path: json/src/main/java/org/n52/supervisor/checks/json/EnviroCarModule.java import org.n52.supervisor.checks.RunnerFactory; import com.google.inject.AbstractModule; import com.google.inject.multibindings.Multibinder; /** * Copyright (C) 2013 - 2014 52°North Initiative for Geospatial Open Source Software GmbH * * 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.n52.supervisor.checks.json; public class EnviroCarModule extends AbstractModule { @Override protected void configure() {
Multibinder<RunnerFactory> binder = Multibinder.newSetBinder(binder(),
52North/Supervisor
ows/src/main/java/org/n52/supervisor/checks/ows/OWSRunnerFactory.java
// Path: core/src/main/java/org/n52/supervisor/api/Check.java // @XmlRootElement // public abstract class Check { // // private String identifier; // // private String notificationEmail; // // protected String type = "GenericCheck"; // // /* // * injects only work on objects created by Guice. // * this is most likely not the case for Checkers. // */ // // @Inject // // @Named(SupervisorProperties.DEFAULT_CHECK_INTERVAL) // private long intervalSeconds; // // public Check() { // // required for jaxb // } // // public Check(String identifier) { // super(); // this.identifier = identifier; // } // // public Check(String notificationEmail, long intervalSeconds) { // this(); // this.notificationEmail = notificationEmail; // this.intervalSeconds = intervalSeconds; // } // // public Check(String identifier, String notificationEmail, long intervalSeconds) { // this(identifier); // this.notificationEmail = notificationEmail; // this.intervalSeconds = intervalSeconds; // } // // public String getIdentifier() { // return identifier; // } // // public long getIntervalSeconds() { // return intervalSeconds; // } // // public String getNotificationEmail() { // return notificationEmail; // } // // public String getType() { // return type; // } // // public void setIdentifier(String identifier) { // this.identifier = identifier; // } // // public void setIntervalSeconds(long intervalMillis) { // this.intervalSeconds = intervalMillis; // } // // public void setNotificationEmail(String notificationEmail) { // this.notificationEmail = notificationEmail; // } // // public void setType(String type) { // this.type = type; // } // // } // // Path: core/src/main/java/org/n52/supervisor/api/CheckRunner.java // public interface CheckRunner { // // final IdentifierGenerator ID_GENERATOR = new ShortAlphanumericIdentifierGenerator(); // // public void addResult(CheckResult r); // // public boolean check(); // // public Check getCheck(); // // public Collection<CheckResult> getResults(); // // public Collection<CheckResult> getAndClearResults(); // // public void notifyFailure(); // // public void notifySuccess(); // // public void setCheck(Check check) throws UnsupportedCheckException; // // /** // * @param rd // * is required so that the runner can announce its results // */ // public void setResultDatabase(ResultDatabase rd); // // } // // Path: core/src/main/java/org/n52/supervisor/checks/RunnerFactory.java // public interface RunnerFactory { // // CheckRunner resolveRunner(Check check); // // }
import org.n52.supervisor.api.Check; import org.n52.supervisor.api.CheckRunner; import org.n52.supervisor.checks.RunnerFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
/** * Copyright (C) 2013 - 2014 52°North Initiative for Geospatial Open Source Software GmbH * * 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.n52.supervisor.checks.ows; public class OWSRunnerFactory implements RunnerFactory { private static final Logger log = LoggerFactory .getLogger(OWSRunnerFactory.class); @Override
// Path: core/src/main/java/org/n52/supervisor/api/Check.java // @XmlRootElement // public abstract class Check { // // private String identifier; // // private String notificationEmail; // // protected String type = "GenericCheck"; // // /* // * injects only work on objects created by Guice. // * this is most likely not the case for Checkers. // */ // // @Inject // // @Named(SupervisorProperties.DEFAULT_CHECK_INTERVAL) // private long intervalSeconds; // // public Check() { // // required for jaxb // } // // public Check(String identifier) { // super(); // this.identifier = identifier; // } // // public Check(String notificationEmail, long intervalSeconds) { // this(); // this.notificationEmail = notificationEmail; // this.intervalSeconds = intervalSeconds; // } // // public Check(String identifier, String notificationEmail, long intervalSeconds) { // this(identifier); // this.notificationEmail = notificationEmail; // this.intervalSeconds = intervalSeconds; // } // // public String getIdentifier() { // return identifier; // } // // public long getIntervalSeconds() { // return intervalSeconds; // } // // public String getNotificationEmail() { // return notificationEmail; // } // // public String getType() { // return type; // } // // public void setIdentifier(String identifier) { // this.identifier = identifier; // } // // public void setIntervalSeconds(long intervalMillis) { // this.intervalSeconds = intervalMillis; // } // // public void setNotificationEmail(String notificationEmail) { // this.notificationEmail = notificationEmail; // } // // public void setType(String type) { // this.type = type; // } // // } // // Path: core/src/main/java/org/n52/supervisor/api/CheckRunner.java // public interface CheckRunner { // // final IdentifierGenerator ID_GENERATOR = new ShortAlphanumericIdentifierGenerator(); // // public void addResult(CheckResult r); // // public boolean check(); // // public Check getCheck(); // // public Collection<CheckResult> getResults(); // // public Collection<CheckResult> getAndClearResults(); // // public void notifyFailure(); // // public void notifySuccess(); // // public void setCheck(Check check) throws UnsupportedCheckException; // // /** // * @param rd // * is required so that the runner can announce its results // */ // public void setResultDatabase(ResultDatabase rd); // // } // // Path: core/src/main/java/org/n52/supervisor/checks/RunnerFactory.java // public interface RunnerFactory { // // CheckRunner resolveRunner(Check check); // // } // Path: ows/src/main/java/org/n52/supervisor/checks/ows/OWSRunnerFactory.java import org.n52.supervisor.api.Check; import org.n52.supervisor.api.CheckRunner; import org.n52.supervisor.checks.RunnerFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Copyright (C) 2013 - 2014 52°North Initiative for Geospatial Open Source Software GmbH * * 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.n52.supervisor.checks.ows; public class OWSRunnerFactory implements RunnerFactory { private static final Logger log = LoggerFactory .getLogger(OWSRunnerFactory.class); @Override
public CheckRunner resolveRunner(Check check) {
52North/Supervisor
ows/src/main/java/org/n52/supervisor/checks/ows/OWSRunnerFactory.java
// Path: core/src/main/java/org/n52/supervisor/api/Check.java // @XmlRootElement // public abstract class Check { // // private String identifier; // // private String notificationEmail; // // protected String type = "GenericCheck"; // // /* // * injects only work on objects created by Guice. // * this is most likely not the case for Checkers. // */ // // @Inject // // @Named(SupervisorProperties.DEFAULT_CHECK_INTERVAL) // private long intervalSeconds; // // public Check() { // // required for jaxb // } // // public Check(String identifier) { // super(); // this.identifier = identifier; // } // // public Check(String notificationEmail, long intervalSeconds) { // this(); // this.notificationEmail = notificationEmail; // this.intervalSeconds = intervalSeconds; // } // // public Check(String identifier, String notificationEmail, long intervalSeconds) { // this(identifier); // this.notificationEmail = notificationEmail; // this.intervalSeconds = intervalSeconds; // } // // public String getIdentifier() { // return identifier; // } // // public long getIntervalSeconds() { // return intervalSeconds; // } // // public String getNotificationEmail() { // return notificationEmail; // } // // public String getType() { // return type; // } // // public void setIdentifier(String identifier) { // this.identifier = identifier; // } // // public void setIntervalSeconds(long intervalMillis) { // this.intervalSeconds = intervalMillis; // } // // public void setNotificationEmail(String notificationEmail) { // this.notificationEmail = notificationEmail; // } // // public void setType(String type) { // this.type = type; // } // // } // // Path: core/src/main/java/org/n52/supervisor/api/CheckRunner.java // public interface CheckRunner { // // final IdentifierGenerator ID_GENERATOR = new ShortAlphanumericIdentifierGenerator(); // // public void addResult(CheckResult r); // // public boolean check(); // // public Check getCheck(); // // public Collection<CheckResult> getResults(); // // public Collection<CheckResult> getAndClearResults(); // // public void notifyFailure(); // // public void notifySuccess(); // // public void setCheck(Check check) throws UnsupportedCheckException; // // /** // * @param rd // * is required so that the runner can announce its results // */ // public void setResultDatabase(ResultDatabase rd); // // } // // Path: core/src/main/java/org/n52/supervisor/checks/RunnerFactory.java // public interface RunnerFactory { // // CheckRunner resolveRunner(Check check); // // }
import org.n52.supervisor.api.Check; import org.n52.supervisor.api.CheckRunner; import org.n52.supervisor.checks.RunnerFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
/** * Copyright (C) 2013 - 2014 52°North Initiative for Geospatial Open Source Software GmbH * * 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.n52.supervisor.checks.ows; public class OWSRunnerFactory implements RunnerFactory { private static final Logger log = LoggerFactory .getLogger(OWSRunnerFactory.class); @Override
// Path: core/src/main/java/org/n52/supervisor/api/Check.java // @XmlRootElement // public abstract class Check { // // private String identifier; // // private String notificationEmail; // // protected String type = "GenericCheck"; // // /* // * injects only work on objects created by Guice. // * this is most likely not the case for Checkers. // */ // // @Inject // // @Named(SupervisorProperties.DEFAULT_CHECK_INTERVAL) // private long intervalSeconds; // // public Check() { // // required for jaxb // } // // public Check(String identifier) { // super(); // this.identifier = identifier; // } // // public Check(String notificationEmail, long intervalSeconds) { // this(); // this.notificationEmail = notificationEmail; // this.intervalSeconds = intervalSeconds; // } // // public Check(String identifier, String notificationEmail, long intervalSeconds) { // this(identifier); // this.notificationEmail = notificationEmail; // this.intervalSeconds = intervalSeconds; // } // // public String getIdentifier() { // return identifier; // } // // public long getIntervalSeconds() { // return intervalSeconds; // } // // public String getNotificationEmail() { // return notificationEmail; // } // // public String getType() { // return type; // } // // public void setIdentifier(String identifier) { // this.identifier = identifier; // } // // public void setIntervalSeconds(long intervalMillis) { // this.intervalSeconds = intervalMillis; // } // // public void setNotificationEmail(String notificationEmail) { // this.notificationEmail = notificationEmail; // } // // public void setType(String type) { // this.type = type; // } // // } // // Path: core/src/main/java/org/n52/supervisor/api/CheckRunner.java // public interface CheckRunner { // // final IdentifierGenerator ID_GENERATOR = new ShortAlphanumericIdentifierGenerator(); // // public void addResult(CheckResult r); // // public boolean check(); // // public Check getCheck(); // // public Collection<CheckResult> getResults(); // // public Collection<CheckResult> getAndClearResults(); // // public void notifyFailure(); // // public void notifySuccess(); // // public void setCheck(Check check) throws UnsupportedCheckException; // // /** // * @param rd // * is required so that the runner can announce its results // */ // public void setResultDatabase(ResultDatabase rd); // // } // // Path: core/src/main/java/org/n52/supervisor/checks/RunnerFactory.java // public interface RunnerFactory { // // CheckRunner resolveRunner(Check check); // // } // Path: ows/src/main/java/org/n52/supervisor/checks/ows/OWSRunnerFactory.java import org.n52.supervisor.api.Check; import org.n52.supervisor.api.CheckRunner; import org.n52.supervisor.checks.RunnerFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Copyright (C) 2013 - 2014 52°North Initiative for Geospatial Open Source Software GmbH * * 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.n52.supervisor.checks.ows; public class OWSRunnerFactory implements RunnerFactory { private static final Logger log = LoggerFactory .getLogger(OWSRunnerFactory.class); @Override
public CheckRunner resolveRunner(Check check) {
52North/Supervisor
core/src/main/java/org/n52/supervisor/tasks/ThreadPoolTaskExecutor.java
// Path: core/src/main/java/org/n52/supervisor/api/CheckRunner.java // public interface CheckRunner { // // final IdentifierGenerator ID_GENERATOR = new ShortAlphanumericIdentifierGenerator(); // // public void addResult(CheckResult r); // // public boolean check(); // // public Check getCheck(); // // public Collection<CheckResult> getResults(); // // public Collection<CheckResult> getAndClearResults(); // // public void notifyFailure(); // // public void notifySuccess(); // // public void setCheck(Check check) throws UnsupportedCheckException; // // /** // * @param rd // * is required so that the runner can announce its results // */ // public void setResultDatabase(ResultDatabase rd); // // } // // Path: core/src/main/java/org/n52/supervisor/api/CheckTask.java // public interface CheckTask { // // public Collection<CheckResult> checkIt(CheckRunner c); // // } // // Path: core/src/main/java/org/n52/supervisor/api/CheckTaskFactory.java // public interface CheckTaskFactory { // // CheckTask create(CheckRunner checker); // // }
import com.google.inject.Inject; import com.google.inject.Singleton; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Date; import java.util.Properties; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; import org.n52.supervisor.api.CheckRunner; import org.n52.supervisor.api.CheckTask; import org.n52.supervisor.api.CheckTaskFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
/** * Copyright (C) 2013 - 2014 52°North Initiative for Geospatial Open Source Software GmbH * * 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.n52.supervisor.tasks; /** * * This class can be used to execute {@link TimerTask} instances. It runs as a servlet and can be accessed by * other servlets for task scheduling and cancelling. The actual service method for GET and POST requests are * not implemented. It also provides methods to access the appropriate instances of * {@link ICatalogStatusHandler} and {@link ICatalogFactory} for tasks that run within this servlet. * * @author Daniel Nüst (daniel.nuest@uni-muenster.de) * */ @Singleton public class ThreadPoolTaskExecutor implements TaskExecutor { private static final String CHECK_THREAD_COUNT = "CHECK_THREAD_COUNT"; private ScheduledThreadPoolExecutor executor; private static Logger log = LoggerFactory.getLogger(ThreadPoolTaskExecutor.class); private static final String SEND_EMAILS = "supervisor.tasks.email.send"; private Properties props; /** * List that holds all repeated task during run-time. */ private ArrayList<TaskElement> tasks = new ArrayList<ThreadPoolTaskExecutor.TaskElement>(); private String configFile = "/supervisor.properties";
// Path: core/src/main/java/org/n52/supervisor/api/CheckRunner.java // public interface CheckRunner { // // final IdentifierGenerator ID_GENERATOR = new ShortAlphanumericIdentifierGenerator(); // // public void addResult(CheckResult r); // // public boolean check(); // // public Check getCheck(); // // public Collection<CheckResult> getResults(); // // public Collection<CheckResult> getAndClearResults(); // // public void notifyFailure(); // // public void notifySuccess(); // // public void setCheck(Check check) throws UnsupportedCheckException; // // /** // * @param rd // * is required so that the runner can announce its results // */ // public void setResultDatabase(ResultDatabase rd); // // } // // Path: core/src/main/java/org/n52/supervisor/api/CheckTask.java // public interface CheckTask { // // public Collection<CheckResult> checkIt(CheckRunner c); // // } // // Path: core/src/main/java/org/n52/supervisor/api/CheckTaskFactory.java // public interface CheckTaskFactory { // // CheckTask create(CheckRunner checker); // // } // Path: core/src/main/java/org/n52/supervisor/tasks/ThreadPoolTaskExecutor.java import com.google.inject.Inject; import com.google.inject.Singleton; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Date; import java.util.Properties; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; import org.n52.supervisor.api.CheckRunner; import org.n52.supervisor.api.CheckTask; import org.n52.supervisor.api.CheckTaskFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Copyright (C) 2013 - 2014 52°North Initiative for Geospatial Open Source Software GmbH * * 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.n52.supervisor.tasks; /** * * This class can be used to execute {@link TimerTask} instances. It runs as a servlet and can be accessed by * other servlets for task scheduling and cancelling. The actual service method for GET and POST requests are * not implemented. It also provides methods to access the appropriate instances of * {@link ICatalogStatusHandler} and {@link ICatalogFactory} for tasks that run within this servlet. * * @author Daniel Nüst (daniel.nuest@uni-muenster.de) * */ @Singleton public class ThreadPoolTaskExecutor implements TaskExecutor { private static final String CHECK_THREAD_COUNT = "CHECK_THREAD_COUNT"; private ScheduledThreadPoolExecutor executor; private static Logger log = LoggerFactory.getLogger(ThreadPoolTaskExecutor.class); private static final String SEND_EMAILS = "supervisor.tasks.email.send"; private Properties props; /** * List that holds all repeated task during run-time. */ private ArrayList<TaskElement> tasks = new ArrayList<ThreadPoolTaskExecutor.TaskElement>(); private String configFile = "/supervisor.properties";
private CheckTaskFactory taskFactory;
52North/Supervisor
core/src/main/java/org/n52/supervisor/tasks/ThreadPoolTaskExecutor.java
// Path: core/src/main/java/org/n52/supervisor/api/CheckRunner.java // public interface CheckRunner { // // final IdentifierGenerator ID_GENERATOR = new ShortAlphanumericIdentifierGenerator(); // // public void addResult(CheckResult r); // // public boolean check(); // // public Check getCheck(); // // public Collection<CheckResult> getResults(); // // public Collection<CheckResult> getAndClearResults(); // // public void notifyFailure(); // // public void notifySuccess(); // // public void setCheck(Check check) throws UnsupportedCheckException; // // /** // * @param rd // * is required so that the runner can announce its results // */ // public void setResultDatabase(ResultDatabase rd); // // } // // Path: core/src/main/java/org/n52/supervisor/api/CheckTask.java // public interface CheckTask { // // public Collection<CheckResult> checkIt(CheckRunner c); // // } // // Path: core/src/main/java/org/n52/supervisor/api/CheckTaskFactory.java // public interface CheckTaskFactory { // // CheckTask create(CheckRunner checker); // // }
import com.google.inject.Inject; import com.google.inject.Singleton; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Date; import java.util.Properties; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; import org.n52.supervisor.api.CheckRunner; import org.n52.supervisor.api.CheckTask; import org.n52.supervisor.api.CheckTaskFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
boolean sendEmails = Boolean.parseBoolean(props.getProperty(SEND_EMAILS)); if (sendEmails) { /* * disabled for the moment, does not work as expected */ // add task for email notifications, with out without admin email // String adminEmail = this.props.getProperty(EMAIL_ADMIN_EMAIL); // // long emailSendInterval = Long.valueOf(this.props.getProperty(EMAIL_SEND_PERIOD_MINDS)); // if ( !adminEmail.contains("@ADMIN_EMAIL@")) { // log.info("Found admin email address for send email task."); // SendEmailTask set = new SendEmailTask(adminEmail, this.rd); // submit(EMAIL_SENDER_TASK_ID, set, emailSendInterval, emailSendInterval); // } } else log.debug("Not sending emails, not starting email tasks."); log.info(" ***** Timer initiated successfully! ***** "); } private Properties loadProperties(InputStream is) throws IOException { Properties properties = new Properties(); properties.load(is); return properties; }
// Path: core/src/main/java/org/n52/supervisor/api/CheckRunner.java // public interface CheckRunner { // // final IdentifierGenerator ID_GENERATOR = new ShortAlphanumericIdentifierGenerator(); // // public void addResult(CheckResult r); // // public boolean check(); // // public Check getCheck(); // // public Collection<CheckResult> getResults(); // // public Collection<CheckResult> getAndClearResults(); // // public void notifyFailure(); // // public void notifySuccess(); // // public void setCheck(Check check) throws UnsupportedCheckException; // // /** // * @param rd // * is required so that the runner can announce its results // */ // public void setResultDatabase(ResultDatabase rd); // // } // // Path: core/src/main/java/org/n52/supervisor/api/CheckTask.java // public interface CheckTask { // // public Collection<CheckResult> checkIt(CheckRunner c); // // } // // Path: core/src/main/java/org/n52/supervisor/api/CheckTaskFactory.java // public interface CheckTaskFactory { // // CheckTask create(CheckRunner checker); // // } // Path: core/src/main/java/org/n52/supervisor/tasks/ThreadPoolTaskExecutor.java import com.google.inject.Inject; import com.google.inject.Singleton; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Date; import java.util.Properties; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; import org.n52.supervisor.api.CheckRunner; import org.n52.supervisor.api.CheckTask; import org.n52.supervisor.api.CheckTaskFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; boolean sendEmails = Boolean.parseBoolean(props.getProperty(SEND_EMAILS)); if (sendEmails) { /* * disabled for the moment, does not work as expected */ // add task for email notifications, with out without admin email // String adminEmail = this.props.getProperty(EMAIL_ADMIN_EMAIL); // // long emailSendInterval = Long.valueOf(this.props.getProperty(EMAIL_SEND_PERIOD_MINDS)); // if ( !adminEmail.contains("@ADMIN_EMAIL@")) { // log.info("Found admin email address for send email task."); // SendEmailTask set = new SendEmailTask(adminEmail, this.rd); // submit(EMAIL_SENDER_TASK_ID, set, emailSendInterval, emailSendInterval); // } } else log.debug("Not sending emails, not starting email tasks."); log.info(" ***** Timer initiated successfully! ***** "); } private Properties loadProperties(InputStream is) throws IOException { Properties properties = new Properties(); properties.load(is); return properties; }
public void submit(String identifier, CheckRunner cr, long delay) throws TaskExecutorException {
52North/Supervisor
core/src/main/java/org/n52/supervisor/tasks/ThreadPoolTaskExecutor.java
// Path: core/src/main/java/org/n52/supervisor/api/CheckRunner.java // public interface CheckRunner { // // final IdentifierGenerator ID_GENERATOR = new ShortAlphanumericIdentifierGenerator(); // // public void addResult(CheckResult r); // // public boolean check(); // // public Check getCheck(); // // public Collection<CheckResult> getResults(); // // public Collection<CheckResult> getAndClearResults(); // // public void notifyFailure(); // // public void notifySuccess(); // // public void setCheck(Check check) throws UnsupportedCheckException; // // /** // * @param rd // * is required so that the runner can announce its results // */ // public void setResultDatabase(ResultDatabase rd); // // } // // Path: core/src/main/java/org/n52/supervisor/api/CheckTask.java // public interface CheckTask { // // public Collection<CheckResult> checkIt(CheckRunner c); // // } // // Path: core/src/main/java/org/n52/supervisor/api/CheckTaskFactory.java // public interface CheckTaskFactory { // // CheckTask create(CheckRunner checker); // // }
import com.google.inject.Inject; import com.google.inject.Singleton; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Date; import java.util.Properties; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; import org.n52.supervisor.api.CheckRunner; import org.n52.supervisor.api.CheckTask; import org.n52.supervisor.api.CheckTaskFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
// log.info("Found admin email address for send email task."); // SendEmailTask set = new SendEmailTask(adminEmail, this.rd); // submit(EMAIL_SENDER_TASK_ID, set, emailSendInterval, emailSendInterval); // } } else log.debug("Not sending emails, not starting email tasks."); log.info(" ***** Timer initiated successfully! ***** "); } private Properties loadProperties(InputStream is) throws IOException { Properties properties = new Properties(); properties.load(is); return properties; } public void submit(String identifier, CheckRunner cr, long delay) throws TaskExecutorException { TimerTask task = createTimerTask(cr); executor.schedule(task, delay, TimeUnit.MILLISECONDS); if (log.isDebugEnabled()) { log.debug("Submitted: " + task + " with delay = " + delay); } this.tasks.add(new TaskElement(identifier, task, delay, 0l)); } private TimerTask createTimerTask(CheckRunner cr) throws TaskExecutorException {
// Path: core/src/main/java/org/n52/supervisor/api/CheckRunner.java // public interface CheckRunner { // // final IdentifierGenerator ID_GENERATOR = new ShortAlphanumericIdentifierGenerator(); // // public void addResult(CheckResult r); // // public boolean check(); // // public Check getCheck(); // // public Collection<CheckResult> getResults(); // // public Collection<CheckResult> getAndClearResults(); // // public void notifyFailure(); // // public void notifySuccess(); // // public void setCheck(Check check) throws UnsupportedCheckException; // // /** // * @param rd // * is required so that the runner can announce its results // */ // public void setResultDatabase(ResultDatabase rd); // // } // // Path: core/src/main/java/org/n52/supervisor/api/CheckTask.java // public interface CheckTask { // // public Collection<CheckResult> checkIt(CheckRunner c); // // } // // Path: core/src/main/java/org/n52/supervisor/api/CheckTaskFactory.java // public interface CheckTaskFactory { // // CheckTask create(CheckRunner checker); // // } // Path: core/src/main/java/org/n52/supervisor/tasks/ThreadPoolTaskExecutor.java import com.google.inject.Inject; import com.google.inject.Singleton; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Date; import java.util.Properties; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; import org.n52.supervisor.api.CheckRunner; import org.n52.supervisor.api.CheckTask; import org.n52.supervisor.api.CheckTaskFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; // log.info("Found admin email address for send email task."); // SendEmailTask set = new SendEmailTask(adminEmail, this.rd); // submit(EMAIL_SENDER_TASK_ID, set, emailSendInterval, emailSendInterval); // } } else log.debug("Not sending emails, not starting email tasks."); log.info(" ***** Timer initiated successfully! ***** "); } private Properties loadProperties(InputStream is) throws IOException { Properties properties = new Properties(); properties.load(is); return properties; } public void submit(String identifier, CheckRunner cr, long delay) throws TaskExecutorException { TimerTask task = createTimerTask(cr); executor.schedule(task, delay, TimeUnit.MILLISECONDS); if (log.isDebugEnabled()) { log.debug("Submitted: " + task + " with delay = " + delay); } this.tasks.add(new TaskElement(identifier, task, delay, 0l)); } private TimerTask createTimerTask(CheckRunner cr) throws TaskExecutorException {
CheckTask t = this.taskFactory.create(cr);
52North/Supervisor
json/src/main/java/org/n52/supervisor/checks/json/EnviroCarAggregationChecker.java
// Path: core/src/main/java/org/n52/supervisor/checks/AbstractServiceCheckRunner.java // public abstract class AbstractServiceCheckRunner implements CheckRunner { // // protected static final DateFormat ISO8601LocalFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:SS.SSS"); // // private static Logger log = LoggerFactory.getLogger(AbstractServiceCheckRunner.class); // // protected Client client = new Client(); // // private final List<CheckResult> results = new ArrayList<CheckResult>(); // // protected ServiceCheck check; // // private ResultDatabase rd; // // public AbstractServiceCheckRunner(final ServiceCheck check) { // this.check = check; // } // // @Override // public synchronized void addResult(final CheckResult result) { // results.add(result); // log.debug("Result added: " + result); // } // // public synchronized void clearResults() { // log.debug("Clearing {} results",results.size()); // results.clear(); // } // // protected ServiceCheckResult createNegativeResult(final String text) { // ResultType type = CheckResult.ResultType.NEGATIVE; // final ServiceCheckResult result = createResult(text, type); // return result; // } // // // protected ServiceCheckResult createPositiveResult(final String text) { // ResultType type = CheckResult.ResultType.POSITIVE; // final ServiceCheckResult result = createResult(text, type); // return result; // } // // protected ServiceCheckResult createResult(final String text, ResultType type) { // final ServiceCheckResult result = new ServiceCheckResult( // ID_GENERATOR.generate(), // check.getIdentifier(), // text, // new Date(), // type, // check.getServiceIdentifier()); // return result; // } // // @Override // public Check getCheck() { // return check; // } // // @Override // public synchronized Collection<CheckResult> getResults() { // return results; // } // // @Override // public synchronized Collection<CheckResult> getAndClearResults() { // List<CheckResult> copy = new ArrayList<CheckResult>(this.results); // results.clear(); // return copy; // } // // @Override // public void notifyFailure() { // log.info("Check FAILED: {}", this); // // if (check.getNotificationEmail() == null) { // log.error("Can not notify via email, is null!"); // } else { // final Collection<CheckResult> failures = new ArrayList<CheckResult>(); // // synchronized (this) { // for (final CheckResult r : results) { // if (r.getType().equals(CheckResult.ResultType.NEGATIVE)) { // failures.add(r); // } // } // } // // final Notification n = new EmailNotification(check, failures); // submitNotification(n); // } // } // // @Override // public void notifySuccess() { // log.info("Check SUCCESSFUL: {}", this); // } // // protected boolean saveAndReturnNegativeResult(final String text) { // final ServiceCheckResult r = createNegativeResult(text); // addResult(r); // return false; // } // // @Override // public void setCheck(final Check c) throws UnsupportedCheckException { // if (c instanceof ServiceCheck) { // final ServiceCheck sc = (ServiceCheck) c; // check = sc; // } else { // throw new UnsupportedCheckException(); // } // } // // @Override // public void setResultDatabase(final ResultDatabase rd) { // this.rd = rd; // } // // public void submitNotification(Notification n) { // SendEmailTask set = new SendEmailTask( // SupervisorProperties.instance().getAdminEmail(), rd); // set.addNotification(n); // set.execute(); // } // // public List<CheckResult> getLatestDatabaseResults() { // return rd.getLatestResults(); // } // // }
import org.n52.supervisor.checks.AbstractServiceCheckRunner; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.xml.bind.annotation.XmlRootElement; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.codehaus.jackson.map.ObjectMapper;
/** * Copyright (C) 2013 - 2014 52°North Initiative for Geospatial Open Source Software GmbH * * 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.n52.supervisor.checks.json; @XmlRootElement public class EnviroCarAggregationChecker extends BaseEnviroCarChecker { private static final Logger logger = LoggerFactory.getLogger(EnviroCarAggregationChecker.class); private String apiTrackUrl; private String aggregationTrackUrl; public static void main(String[] args) { String u1 = "https://envirocar.org/api/stable/tracks?limit=250&page=0"; String u2 = "http://ags.dev.52north.org:8080/point-aggregation/aggregatedTracks"; EnviroCarAggregationChecker checker = new EnviroCarAggregationChecker(u1, u2, null); boolean result = checker.new Runner().check(); } public EnviroCarAggregationChecker() { super(null); } public EnviroCarAggregationChecker(String apiTrackUrl, String aggregationTrackUrl, String email) { super(email); this.apiTrackUrl = apiTrackUrl; this.aggregationTrackUrl = aggregationTrackUrl; }
// Path: core/src/main/java/org/n52/supervisor/checks/AbstractServiceCheckRunner.java // public abstract class AbstractServiceCheckRunner implements CheckRunner { // // protected static final DateFormat ISO8601LocalFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:SS.SSS"); // // private static Logger log = LoggerFactory.getLogger(AbstractServiceCheckRunner.class); // // protected Client client = new Client(); // // private final List<CheckResult> results = new ArrayList<CheckResult>(); // // protected ServiceCheck check; // // private ResultDatabase rd; // // public AbstractServiceCheckRunner(final ServiceCheck check) { // this.check = check; // } // // @Override // public synchronized void addResult(final CheckResult result) { // results.add(result); // log.debug("Result added: " + result); // } // // public synchronized void clearResults() { // log.debug("Clearing {} results",results.size()); // results.clear(); // } // // protected ServiceCheckResult createNegativeResult(final String text) { // ResultType type = CheckResult.ResultType.NEGATIVE; // final ServiceCheckResult result = createResult(text, type); // return result; // } // // // protected ServiceCheckResult createPositiveResult(final String text) { // ResultType type = CheckResult.ResultType.POSITIVE; // final ServiceCheckResult result = createResult(text, type); // return result; // } // // protected ServiceCheckResult createResult(final String text, ResultType type) { // final ServiceCheckResult result = new ServiceCheckResult( // ID_GENERATOR.generate(), // check.getIdentifier(), // text, // new Date(), // type, // check.getServiceIdentifier()); // return result; // } // // @Override // public Check getCheck() { // return check; // } // // @Override // public synchronized Collection<CheckResult> getResults() { // return results; // } // // @Override // public synchronized Collection<CheckResult> getAndClearResults() { // List<CheckResult> copy = new ArrayList<CheckResult>(this.results); // results.clear(); // return copy; // } // // @Override // public void notifyFailure() { // log.info("Check FAILED: {}", this); // // if (check.getNotificationEmail() == null) { // log.error("Can not notify via email, is null!"); // } else { // final Collection<CheckResult> failures = new ArrayList<CheckResult>(); // // synchronized (this) { // for (final CheckResult r : results) { // if (r.getType().equals(CheckResult.ResultType.NEGATIVE)) { // failures.add(r); // } // } // } // // final Notification n = new EmailNotification(check, failures); // submitNotification(n); // } // } // // @Override // public void notifySuccess() { // log.info("Check SUCCESSFUL: {}", this); // } // // protected boolean saveAndReturnNegativeResult(final String text) { // final ServiceCheckResult r = createNegativeResult(text); // addResult(r); // return false; // } // // @Override // public void setCheck(final Check c) throws UnsupportedCheckException { // if (c instanceof ServiceCheck) { // final ServiceCheck sc = (ServiceCheck) c; // check = sc; // } else { // throw new UnsupportedCheckException(); // } // } // // @Override // public void setResultDatabase(final ResultDatabase rd) { // this.rd = rd; // } // // public void submitNotification(Notification n) { // SendEmailTask set = new SendEmailTask( // SupervisorProperties.instance().getAdminEmail(), rd); // set.addNotification(n); // set.execute(); // } // // public List<CheckResult> getLatestDatabaseResults() { // return rd.getLatestResults(); // } // // } // Path: json/src/main/java/org/n52/supervisor/checks/json/EnviroCarAggregationChecker.java import org.n52.supervisor.checks.AbstractServiceCheckRunner; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.xml.bind.annotation.XmlRootElement; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.codehaus.jackson.map.ObjectMapper; /** * Copyright (C) 2013 - 2014 52°North Initiative for Geospatial Open Source Software GmbH * * 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.n52.supervisor.checks.json; @XmlRootElement public class EnviroCarAggregationChecker extends BaseEnviroCarChecker { private static final Logger logger = LoggerFactory.getLogger(EnviroCarAggregationChecker.class); private String apiTrackUrl; private String aggregationTrackUrl; public static void main(String[] args) { String u1 = "https://envirocar.org/api/stable/tracks?limit=250&page=0"; String u2 = "http://ags.dev.52north.org:8080/point-aggregation/aggregatedTracks"; EnviroCarAggregationChecker checker = new EnviroCarAggregationChecker(u1, u2, null); boolean result = checker.new Runner().check(); } public EnviroCarAggregationChecker() { super(null); } public EnviroCarAggregationChecker(String apiTrackUrl, String aggregationTrackUrl, String email) { super(email); this.apiTrackUrl = apiTrackUrl; this.aggregationTrackUrl = aggregationTrackUrl; }
public class Runner extends AbstractServiceCheckRunner {
52North/Supervisor
core/src/main/java/org/n52/supervisor/db/CheckDatabase.java
// Path: core/src/main/java/org/n52/supervisor/api/Check.java // @XmlRootElement // public abstract class Check { // // private String identifier; // // private String notificationEmail; // // protected String type = "GenericCheck"; // // /* // * injects only work on objects created by Guice. // * this is most likely not the case for Checkers. // */ // // @Inject // // @Named(SupervisorProperties.DEFAULT_CHECK_INTERVAL) // private long intervalSeconds; // // public Check() { // // required for jaxb // } // // public Check(String identifier) { // super(); // this.identifier = identifier; // } // // public Check(String notificationEmail, long intervalSeconds) { // this(); // this.notificationEmail = notificationEmail; // this.intervalSeconds = intervalSeconds; // } // // public Check(String identifier, String notificationEmail, long intervalSeconds) { // this(identifier); // this.notificationEmail = notificationEmail; // this.intervalSeconds = intervalSeconds; // } // // public String getIdentifier() { // return identifier; // } // // public long getIntervalSeconds() { // return intervalSeconds; // } // // public String getNotificationEmail() { // return notificationEmail; // } // // public String getType() { // return type; // } // // public void setIdentifier(String identifier) { // this.identifier = identifier; // } // // public void setIntervalSeconds(long intervalMillis) { // this.intervalSeconds = intervalMillis; // } // // public void setNotificationEmail(String notificationEmail) { // this.notificationEmail = notificationEmail; // } // // public void setType(String type) { // this.type = type; // } // // }
import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.n52.supervisor.api.Check; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.inject.Singleton;
/** * Copyright (C) 2013 - 2014 52°North Initiative for Geospatial Open Source Software GmbH * * 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.n52.supervisor.db; /** * * @author Daniel * */ @Singleton public class CheckDatabase { private static Logger log = LoggerFactory.getLogger(CheckDatabase.class);
// Path: core/src/main/java/org/n52/supervisor/api/Check.java // @XmlRootElement // public abstract class Check { // // private String identifier; // // private String notificationEmail; // // protected String type = "GenericCheck"; // // /* // * injects only work on objects created by Guice. // * this is most likely not the case for Checkers. // */ // // @Inject // // @Named(SupervisorProperties.DEFAULT_CHECK_INTERVAL) // private long intervalSeconds; // // public Check() { // // required for jaxb // } // // public Check(String identifier) { // super(); // this.identifier = identifier; // } // // public Check(String notificationEmail, long intervalSeconds) { // this(); // this.notificationEmail = notificationEmail; // this.intervalSeconds = intervalSeconds; // } // // public Check(String identifier, String notificationEmail, long intervalSeconds) { // this(identifier); // this.notificationEmail = notificationEmail; // this.intervalSeconds = intervalSeconds; // } // // public String getIdentifier() { // return identifier; // } // // public long getIntervalSeconds() { // return intervalSeconds; // } // // public String getNotificationEmail() { // return notificationEmail; // } // // public String getType() { // return type; // } // // public void setIdentifier(String identifier) { // this.identifier = identifier; // } // // public void setIntervalSeconds(long intervalMillis) { // this.intervalSeconds = intervalMillis; // } // // public void setNotificationEmail(String notificationEmail) { // this.notificationEmail = notificationEmail; // } // // public void setType(String type) { // this.type = type; // } // // } // Path: core/src/main/java/org/n52/supervisor/db/CheckDatabase.java import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.n52.supervisor.api.Check; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.inject.Singleton; /** * Copyright (C) 2013 - 2014 52°North Initiative for Geospatial Open Source Software GmbH * * 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.n52.supervisor.db; /** * * @author Daniel * */ @Singleton public class CheckDatabase { private static Logger log = LoggerFactory.getLogger(CheckDatabase.class);
private ArrayList<Check> internalDatabase = new ArrayList<Check>();
52North/Supervisor
ows/src/main/java/org/n52/supervisor/checks/ows/OWSModule.java
// Path: core/src/main/java/org/n52/supervisor/checks/RunnerFactory.java // public interface RunnerFactory { // // CheckRunner resolveRunner(Check check); // // }
import org.n52.supervisor.checks.RunnerFactory; import com.google.inject.AbstractModule; import com.google.inject.multibindings.Multibinder;
/** * Copyright (C) 2013 - 2014 52°North Initiative for Geospatial Open Source Software GmbH * * 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.n52.supervisor.checks.ows; public class OWSModule extends AbstractModule { @Override protected void configure() {
// Path: core/src/main/java/org/n52/supervisor/checks/RunnerFactory.java // public interface RunnerFactory { // // CheckRunner resolveRunner(Check check); // // } // Path: ows/src/main/java/org/n52/supervisor/checks/ows/OWSModule.java import org.n52.supervisor.checks.RunnerFactory; import com.google.inject.AbstractModule; import com.google.inject.multibindings.Multibinder; /** * Copyright (C) 2013 - 2014 52°North Initiative for Geospatial Open Source Software GmbH * * 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.n52.supervisor.checks.ows; public class OWSModule extends AbstractModule { @Override protected void configure() {
Multibinder<RunnerFactory> binder = Multibinder.newSetBinder(binder(),
52North/Supervisor
core/src/main/java/org/n52/supervisor/ConfigModule.java
// Path: core/src/main/java/org/n52/supervisor/checks/BasicRunnerFactory.java // public class BasicRunnerFactory implements RunnerFactory { // // @Inject // private ResultDatabase rd; // // @Override // public CheckRunner resolveRunner(Check check) { // CheckRunner r = null; // // if (check instanceof HeapCheck) { // final HeapCheck hc = (HeapCheck) check; // r = new HeapCheckRunner(hc); // } // else if (check instanceof SelfCheck) { // final SelfCheck sc = (SelfCheck) check; // r = new SelfCheckRunner(sc); // } // // if (r != null) { // r.setResultDatabase(rd); // } // // return r; // } // // } // // Path: core/src/main/java/org/n52/supervisor/checks/RunnerFactory.java // public interface RunnerFactory { // // CheckRunner resolveRunner(Check check); // // }
import com.google.inject.multibindings.Multibinder; import com.google.inject.name.Names; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Properties; import org.n52.supervisor.checks.BasicRunnerFactory; import org.n52.supervisor.checks.RunnerFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.inject.AbstractModule;
final String msg = "SuperVisor properties not found."; log.error(msg, e); throw new RuntimeException(msg,e); } catch (final IOException e) { final String msg = "SuperVisor properties not readable."; log.error(msg, e); throw new RuntimeException(msg,e); } // try storing properties in user.home final File folder = new File(USER_HOME_PATH); if (!folder.exists() && !folder.mkdir()) { log.warn("SuperVisor properties could not be saved. No writing permissions at '{}'.", folder); return properties; } final File file = new File(USER_HOME_PATH + name); log.info("Save properties at '{}'.", file.getAbsolutePath()); try { //save properties final OutputStream os = new FileOutputStream(file); properties.store(os, null); } catch (final IOException e) { log.error("SuperVisor properties could not be saved.", e); } return properties; } @Override protected void configure() { final Properties appProps = loadProperties("app.properties"); Names.bindProperties(binder(), appProps);
// Path: core/src/main/java/org/n52/supervisor/checks/BasicRunnerFactory.java // public class BasicRunnerFactory implements RunnerFactory { // // @Inject // private ResultDatabase rd; // // @Override // public CheckRunner resolveRunner(Check check) { // CheckRunner r = null; // // if (check instanceof HeapCheck) { // final HeapCheck hc = (HeapCheck) check; // r = new HeapCheckRunner(hc); // } // else if (check instanceof SelfCheck) { // final SelfCheck sc = (SelfCheck) check; // r = new SelfCheckRunner(sc); // } // // if (r != null) { // r.setResultDatabase(rd); // } // // return r; // } // // } // // Path: core/src/main/java/org/n52/supervisor/checks/RunnerFactory.java // public interface RunnerFactory { // // CheckRunner resolveRunner(Check check); // // } // Path: core/src/main/java/org/n52/supervisor/ConfigModule.java import com.google.inject.multibindings.Multibinder; import com.google.inject.name.Names; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Properties; import org.n52.supervisor.checks.BasicRunnerFactory; import org.n52.supervisor.checks.RunnerFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.inject.AbstractModule; final String msg = "SuperVisor properties not found."; log.error(msg, e); throw new RuntimeException(msg,e); } catch (final IOException e) { final String msg = "SuperVisor properties not readable."; log.error(msg, e); throw new RuntimeException(msg,e); } // try storing properties in user.home final File folder = new File(USER_HOME_PATH); if (!folder.exists() && !folder.mkdir()) { log.warn("SuperVisor properties could not be saved. No writing permissions at '{}'.", folder); return properties; } final File file = new File(USER_HOME_PATH + name); log.info("Save properties at '{}'.", file.getAbsolutePath()); try { //save properties final OutputStream os = new FileOutputStream(file); properties.store(os, null); } catch (final IOException e) { log.error("SuperVisor properties could not be saved.", e); } return properties; } @Override protected void configure() { final Properties appProps = loadProperties("app.properties"); Names.bindProperties(binder(), appProps);
Multibinder<RunnerFactory> binder = Multibinder.newSetBinder(binder(),
52North/Supervisor
core/src/main/java/org/n52/supervisor/ConfigModule.java
// Path: core/src/main/java/org/n52/supervisor/checks/BasicRunnerFactory.java // public class BasicRunnerFactory implements RunnerFactory { // // @Inject // private ResultDatabase rd; // // @Override // public CheckRunner resolveRunner(Check check) { // CheckRunner r = null; // // if (check instanceof HeapCheck) { // final HeapCheck hc = (HeapCheck) check; // r = new HeapCheckRunner(hc); // } // else if (check instanceof SelfCheck) { // final SelfCheck sc = (SelfCheck) check; // r = new SelfCheckRunner(sc); // } // // if (r != null) { // r.setResultDatabase(rd); // } // // return r; // } // // } // // Path: core/src/main/java/org/n52/supervisor/checks/RunnerFactory.java // public interface RunnerFactory { // // CheckRunner resolveRunner(Check check); // // }
import com.google.inject.multibindings.Multibinder; import com.google.inject.name.Names; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Properties; import org.n52.supervisor.checks.BasicRunnerFactory; import org.n52.supervisor.checks.RunnerFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.inject.AbstractModule;
throw new RuntimeException(msg,e); } catch (final IOException e) { final String msg = "SuperVisor properties not readable."; log.error(msg, e); throw new RuntimeException(msg,e); } // try storing properties in user.home final File folder = new File(USER_HOME_PATH); if (!folder.exists() && !folder.mkdir()) { log.warn("SuperVisor properties could not be saved. No writing permissions at '{}'.", folder); return properties; } final File file = new File(USER_HOME_PATH + name); log.info("Save properties at '{}'.", file.getAbsolutePath()); try { //save properties final OutputStream os = new FileOutputStream(file); properties.store(os, null); } catch (final IOException e) { log.error("SuperVisor properties could not be saved.", e); } return properties; } @Override protected void configure() { final Properties appProps = loadProperties("app.properties"); Names.bindProperties(binder(), appProps); Multibinder<RunnerFactory> binder = Multibinder.newSetBinder(binder(), RunnerFactory.class);
// Path: core/src/main/java/org/n52/supervisor/checks/BasicRunnerFactory.java // public class BasicRunnerFactory implements RunnerFactory { // // @Inject // private ResultDatabase rd; // // @Override // public CheckRunner resolveRunner(Check check) { // CheckRunner r = null; // // if (check instanceof HeapCheck) { // final HeapCheck hc = (HeapCheck) check; // r = new HeapCheckRunner(hc); // } // else if (check instanceof SelfCheck) { // final SelfCheck sc = (SelfCheck) check; // r = new SelfCheckRunner(sc); // } // // if (r != null) { // r.setResultDatabase(rd); // } // // return r; // } // // } // // Path: core/src/main/java/org/n52/supervisor/checks/RunnerFactory.java // public interface RunnerFactory { // // CheckRunner resolveRunner(Check check); // // } // Path: core/src/main/java/org/n52/supervisor/ConfigModule.java import com.google.inject.multibindings.Multibinder; import com.google.inject.name.Names; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Properties; import org.n52.supervisor.checks.BasicRunnerFactory; import org.n52.supervisor.checks.RunnerFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.inject.AbstractModule; throw new RuntimeException(msg,e); } catch (final IOException e) { final String msg = "SuperVisor properties not readable."; log.error(msg, e); throw new RuntimeException(msg,e); } // try storing properties in user.home final File folder = new File(USER_HOME_PATH); if (!folder.exists() && !folder.mkdir()) { log.warn("SuperVisor properties could not be saved. No writing permissions at '{}'.", folder); return properties; } final File file = new File(USER_HOME_PATH + name); log.info("Save properties at '{}'.", file.getAbsolutePath()); try { //save properties final OutputStream os = new FileOutputStream(file); properties.store(os, null); } catch (final IOException e) { log.error("SuperVisor properties could not be saved.", e); } return properties; } @Override protected void configure() { final Properties appProps = loadProperties("app.properties"); Names.bindProperties(binder(), appProps); Multibinder<RunnerFactory> binder = Multibinder.newSetBinder(binder(), RunnerFactory.class);
binder.addBinding().to(BasicRunnerFactory.class);
52North/Supervisor
core/src/main/java/org/n52/supervisor/db/ResultDatabase.java
// Path: core/src/main/java/org/n52/supervisor/api/CheckResult.java // @XmlRootElement // public abstract class CheckResult { // // public static enum ResultType { // NEGATIVE, NEUTRAL, POSITIVE // } // // private String checkIdentifier; // // /** // * Do NOT use any HTML code here because the source code will be rendered! // */ // private String result; // // private Date checkTime; // // private ResultType type; // // private String identifier; // // public CheckResult() { // // required for jaxb // } // // public CheckResult(final String identifier) { // super(); // this.identifier = identifier; // } // // public CheckResult(final String identifier, final String checkIdentifier, final String result, final Date timeOfCheck, final ResultType type) { // super(); // this.identifier = identifier; // this.checkIdentifier = checkIdentifier; // this.result = result; // checkTime = timeOfCheck; // this.type = type; // } // // public String getCheckIdentifier() { // return checkIdentifier; // } // // public String getResult() { // return result; // } // // public Date getCheckTime() { // return checkTime; // } // // public ResultType getType() { // return type; // } // // public String getIdentifier() { // return identifier; // } // // public void setIdentifier(final String identifier) { // this.identifier = identifier; // } // // public void setCheckIdentifier(final String checkIdentifier) { // this.checkIdentifier = checkIdentifier; // } // // public void setResult(final String result) { // this.result = result; // } // // public void setCheckTime(final Date checkTime) { // this.checkTime = checkTime; // } // // public void setType(final ResultType type) { // this.type = type; // } // // @Override // public String toString() { // final StringBuilder builder = new StringBuilder(); // builder.append("CheckResult ["); // if (checkIdentifier != null) { // builder.append("checkIdentifier="); // builder.append(checkIdentifier); // builder.append(", "); // } // if (result != null) { // builder.append("result="); // builder.append(result); // builder.append(", "); // } // if (checkTime != null) { // builder.append("checkTime="); // builder.append(checkTime); // builder.append(", "); // } // if (type != null) { // builder.append("type="); // builder.append(type); // } // builder.append("]"); // return builder.toString(); // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((checkIdentifier == null) ? 0 : checkIdentifier.hashCode()); // result = prime * result + ((this.result == null) ? 0 : this.result.hashCode()); // result = prime * result + ((checkTime == null) ? 0 : checkTime.hashCode()); // result = prime * result + ((type == null) ? 0 : type.hashCode()); // return result; // } // // @Override // public boolean equals(final Object obj) { // if (this == obj) { // return true; // } // if (obj == null) { // return false; // } // if (!(obj instanceof CheckResult)) { // return false; // } // final CheckResult other = (CheckResult) obj; // if (checkIdentifier == null) { // if (other.checkIdentifier != null) { // return false; // } // } else if (!checkIdentifier.equals(other.checkIdentifier)) { // return false; // } // if (result == null) { // if (other.result != null) { // return false; // } // } else if (!result.equals(other.result)) { // return false; // } // if (checkTime == null) { // if (other.checkTime != null) { // return false; // } // } else if (!checkTime.equals(other.checkTime)) { // return false; // } // if (type != other.type) { // return false; // } // return true; // } // // }
import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Queue; import org.n52.supervisor.api.CheckResult; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.collect.EvictingQueue; import com.google.inject.Inject; import com.google.inject.Singleton; import com.google.inject.name.Named;
/** * Copyright (C) 2013 - 2014 52°North Initiative for Geospatial Open Source Software GmbH * * 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.n52.supervisor.db; /** * * @author Daniel * */ @Singleton public class ResultDatabase {
// Path: core/src/main/java/org/n52/supervisor/api/CheckResult.java // @XmlRootElement // public abstract class CheckResult { // // public static enum ResultType { // NEGATIVE, NEUTRAL, POSITIVE // } // // private String checkIdentifier; // // /** // * Do NOT use any HTML code here because the source code will be rendered! // */ // private String result; // // private Date checkTime; // // private ResultType type; // // private String identifier; // // public CheckResult() { // // required for jaxb // } // // public CheckResult(final String identifier) { // super(); // this.identifier = identifier; // } // // public CheckResult(final String identifier, final String checkIdentifier, final String result, final Date timeOfCheck, final ResultType type) { // super(); // this.identifier = identifier; // this.checkIdentifier = checkIdentifier; // this.result = result; // checkTime = timeOfCheck; // this.type = type; // } // // public String getCheckIdentifier() { // return checkIdentifier; // } // // public String getResult() { // return result; // } // // public Date getCheckTime() { // return checkTime; // } // // public ResultType getType() { // return type; // } // // public String getIdentifier() { // return identifier; // } // // public void setIdentifier(final String identifier) { // this.identifier = identifier; // } // // public void setCheckIdentifier(final String checkIdentifier) { // this.checkIdentifier = checkIdentifier; // } // // public void setResult(final String result) { // this.result = result; // } // // public void setCheckTime(final Date checkTime) { // this.checkTime = checkTime; // } // // public void setType(final ResultType type) { // this.type = type; // } // // @Override // public String toString() { // final StringBuilder builder = new StringBuilder(); // builder.append("CheckResult ["); // if (checkIdentifier != null) { // builder.append("checkIdentifier="); // builder.append(checkIdentifier); // builder.append(", "); // } // if (result != null) { // builder.append("result="); // builder.append(result); // builder.append(", "); // } // if (checkTime != null) { // builder.append("checkTime="); // builder.append(checkTime); // builder.append(", "); // } // if (type != null) { // builder.append("type="); // builder.append(type); // } // builder.append("]"); // return builder.toString(); // } // // @Override // public int hashCode() { // final int prime = 31; // int result = 1; // result = prime * result + ((checkIdentifier == null) ? 0 : checkIdentifier.hashCode()); // result = prime * result + ((this.result == null) ? 0 : this.result.hashCode()); // result = prime * result + ((checkTime == null) ? 0 : checkTime.hashCode()); // result = prime * result + ((type == null) ? 0 : type.hashCode()); // return result; // } // // @Override // public boolean equals(final Object obj) { // if (this == obj) { // return true; // } // if (obj == null) { // return false; // } // if (!(obj instanceof CheckResult)) { // return false; // } // final CheckResult other = (CheckResult) obj; // if (checkIdentifier == null) { // if (other.checkIdentifier != null) { // return false; // } // } else if (!checkIdentifier.equals(other.checkIdentifier)) { // return false; // } // if (result == null) { // if (other.result != null) { // return false; // } // } else if (!result.equals(other.result)) { // return false; // } // if (checkTime == null) { // if (other.checkTime != null) { // return false; // } // } else if (!checkTime.equals(other.checkTime)) { // return false; // } // if (type != other.type) { // return false; // } // return true; // } // // } // Path: core/src/main/java/org/n52/supervisor/db/ResultDatabase.java import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Queue; import org.n52.supervisor.api.CheckResult; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.collect.EvictingQueue; import com.google.inject.Inject; import com.google.inject.Singleton; import com.google.inject.name.Named; /** * Copyright (C) 2013 - 2014 52°North Initiative for Geospatial Open Source Software GmbH * * 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.n52.supervisor.db; /** * * @author Daniel * */ @Singleton public class ResultDatabase {
public static final CheckResult NO_CHECK_RESULT_WITH_GIVEN_ID = new CheckResult() {};
52North/Supervisor
core/src/main/java/org/n52/supervisor/api/CheckRunner.java
// Path: core/src/main/java/org/n52/supervisor/db/ResultDatabase.java // @Singleton // public class ResultDatabase { // // public static final CheckResult NO_CHECK_RESULT_WITH_GIVEN_ID = new CheckResult() {}; // // private Queue<CheckResult> latestResults; // // private static Logger log = LoggerFactory.getLogger(ResultDatabase.class); // // private final int maxStoredResults; // // @Inject // public ResultDatabase(@Named("supervisor.checks.maxStoredResults") final // int maxStoredResults) { // this.maxStoredResults = maxStoredResults; // latestResults = EvictingQueue.create(this.maxStoredResults); // log.info("NEW {}", this); // } // // public void appendResult(final CheckResult result) { // if (!latestResults.contains(result)) { // latestResults.add(result); // } // } // // public void appendResults(final Collection<CheckResult> results) { // // if (latestResults.size() >= 100) { // FIXME make append non static so that config parameter can be // // // used: this.maxStoredResults // // log.debug("Too many results. Got " + results.size() + " new and " + latestResults.size() + // // " existing."); // // for (int i = 0; i < Math.min(results.size(), latestResults.size()); i++) { // // // remove the first element so many times that the new results // // // fit. // // latestResults.remove(); // // } // // } // // latestResults.addAll(results); // } // // public void clearResults() { // log.debug("Clearing all results: {}", Arrays.deepToString(latestResults.toArray())); // latestResults.clear(); // } // // public void close() { // latestResults.clear(); // latestResults = null; // } // // public List<CheckResult> getLatestResults() { // return new ArrayList<CheckResult>(latestResults); // } // // public int getMaxStoredResults() { // return maxStoredResults; // } // // /** // * @param id the identifier of a {@link CheckResult}. // * @return The {@link CheckResult} with the given id or {@link ResultDatabase#NO_CHECK_RESULT_WITH_GIVEN_ID}. // */ // public CheckResult getResult(final String id){ // for (final CheckResult checkResult : latestResults) { // if (checkResult.getIdentifier().equals(id)) { // return checkResult; // } // } // return NO_CHECK_RESULT_WITH_GIVEN_ID; // } // // @Override // public String toString() { // final StringBuilder builder = new StringBuilder(); // builder.append("ResultDatabase [maxStoredResults="); // builder.append(maxStoredResults); // builder.append("]"); // return builder.toString(); // } // // public boolean isEmpty() { // return latestResults.isEmpty(); // } // // } // // Path: core/src/main/java/org/n52/supervisor/id/IdentifierGenerator.java // public interface IdentifierGenerator { // // public abstract String generate(); // // public abstract Collection<String> generate(int count); // // } // // Path: core/src/main/java/org/n52/supervisor/id/ShortAlphanumericIdentifierGenerator.java // public class ShortAlphanumericIdentifierGenerator implements IdentifierGenerator { // // private static Logger log = LoggerFactory.getLogger(ShortAlphanumericIdentifierGenerator.class); // // public static final int ID_LENGTH = 10; // // public ShortAlphanumericIdentifierGenerator() { // log.debug("NEW {}", this); // } // // @Override // public String generate() { // return RandomStringUtils.randomAlphanumeric(ID_LENGTH).toLowerCase(); // } // // @Override // public Collection<String> generate(int count) { // ArrayList<String> ids = new ArrayList<>(); // for (int i = 0; i < count; i++) { // ids.add(generate()); // } // return ids; // } // // }
import java.util.Collection; import org.n52.supervisor.db.ResultDatabase; import org.n52.supervisor.id.IdentifierGenerator; import org.n52.supervisor.id.ShortAlphanumericIdentifierGenerator;
/** * Copyright (C) 2013 - 2014 52°North Initiative for Geospatial Open Source Software GmbH * * 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.n52.supervisor.api; /** * @author Daniel Nüst * */ public interface CheckRunner { final IdentifierGenerator ID_GENERATOR = new ShortAlphanumericIdentifierGenerator(); public void addResult(CheckResult r); public boolean check(); public Check getCheck(); public Collection<CheckResult> getResults(); public Collection<CheckResult> getAndClearResults(); public void notifyFailure(); public void notifySuccess(); public void setCheck(Check check) throws UnsupportedCheckException; /** * @param rd * is required so that the runner can announce its results */
// Path: core/src/main/java/org/n52/supervisor/db/ResultDatabase.java // @Singleton // public class ResultDatabase { // // public static final CheckResult NO_CHECK_RESULT_WITH_GIVEN_ID = new CheckResult() {}; // // private Queue<CheckResult> latestResults; // // private static Logger log = LoggerFactory.getLogger(ResultDatabase.class); // // private final int maxStoredResults; // // @Inject // public ResultDatabase(@Named("supervisor.checks.maxStoredResults") final // int maxStoredResults) { // this.maxStoredResults = maxStoredResults; // latestResults = EvictingQueue.create(this.maxStoredResults); // log.info("NEW {}", this); // } // // public void appendResult(final CheckResult result) { // if (!latestResults.contains(result)) { // latestResults.add(result); // } // } // // public void appendResults(final Collection<CheckResult> results) { // // if (latestResults.size() >= 100) { // FIXME make append non static so that config parameter can be // // // used: this.maxStoredResults // // log.debug("Too many results. Got " + results.size() + " new and " + latestResults.size() + // // " existing."); // // for (int i = 0; i < Math.min(results.size(), latestResults.size()); i++) { // // // remove the first element so many times that the new results // // // fit. // // latestResults.remove(); // // } // // } // // latestResults.addAll(results); // } // // public void clearResults() { // log.debug("Clearing all results: {}", Arrays.deepToString(latestResults.toArray())); // latestResults.clear(); // } // // public void close() { // latestResults.clear(); // latestResults = null; // } // // public List<CheckResult> getLatestResults() { // return new ArrayList<CheckResult>(latestResults); // } // // public int getMaxStoredResults() { // return maxStoredResults; // } // // /** // * @param id the identifier of a {@link CheckResult}. // * @return The {@link CheckResult} with the given id or {@link ResultDatabase#NO_CHECK_RESULT_WITH_GIVEN_ID}. // */ // public CheckResult getResult(final String id){ // for (final CheckResult checkResult : latestResults) { // if (checkResult.getIdentifier().equals(id)) { // return checkResult; // } // } // return NO_CHECK_RESULT_WITH_GIVEN_ID; // } // // @Override // public String toString() { // final StringBuilder builder = new StringBuilder(); // builder.append("ResultDatabase [maxStoredResults="); // builder.append(maxStoredResults); // builder.append("]"); // return builder.toString(); // } // // public boolean isEmpty() { // return latestResults.isEmpty(); // } // // } // // Path: core/src/main/java/org/n52/supervisor/id/IdentifierGenerator.java // public interface IdentifierGenerator { // // public abstract String generate(); // // public abstract Collection<String> generate(int count); // // } // // Path: core/src/main/java/org/n52/supervisor/id/ShortAlphanumericIdentifierGenerator.java // public class ShortAlphanumericIdentifierGenerator implements IdentifierGenerator { // // private static Logger log = LoggerFactory.getLogger(ShortAlphanumericIdentifierGenerator.class); // // public static final int ID_LENGTH = 10; // // public ShortAlphanumericIdentifierGenerator() { // log.debug("NEW {}", this); // } // // @Override // public String generate() { // return RandomStringUtils.randomAlphanumeric(ID_LENGTH).toLowerCase(); // } // // @Override // public Collection<String> generate(int count) { // ArrayList<String> ids = new ArrayList<>(); // for (int i = 0; i < count; i++) { // ids.add(generate()); // } // return ids; // } // // } // Path: core/src/main/java/org/n52/supervisor/api/CheckRunner.java import java.util.Collection; import org.n52.supervisor.db.ResultDatabase; import org.n52.supervisor.id.IdentifierGenerator; import org.n52.supervisor.id.ShortAlphanumericIdentifierGenerator; /** * Copyright (C) 2013 - 2014 52°North Initiative for Geospatial Open Source Software GmbH * * 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.n52.supervisor.api; /** * @author Daniel Nüst * */ public interface CheckRunner { final IdentifierGenerator ID_GENERATOR = new ShortAlphanumericIdentifierGenerator(); public void addResult(CheckResult r); public boolean check(); public Check getCheck(); public Collection<CheckResult> getResults(); public Collection<CheckResult> getAndClearResults(); public void notifyFailure(); public void notifySuccess(); public void setCheck(Check check) throws UnsupportedCheckException; /** * @param rd * is required so that the runner can announce its results */
public void setResultDatabase(ResultDatabase rd);
52North/Supervisor
core/src/test/java/org/n52/supervisor/Identifiers.java
// Path: core/src/main/java/org/n52/supervisor/id/IdentifierGenerator.java // public interface IdentifierGenerator { // // public abstract String generate(); // // public abstract Collection<String> generate(int count); // // } // // Path: core/src/main/java/org/n52/supervisor/id/ShortAlphanumericIdentifierGenerator.java // public class ShortAlphanumericIdentifierGenerator implements IdentifierGenerator { // // private static Logger log = LoggerFactory.getLogger(ShortAlphanumericIdentifierGenerator.class); // // public static final int ID_LENGTH = 10; // // public ShortAlphanumericIdentifierGenerator() { // log.debug("NEW {}", this); // } // // @Override // public String generate() { // return RandomStringUtils.randomAlphanumeric(ID_LENGTH).toLowerCase(); // } // // @Override // public Collection<String> generate(int count) { // ArrayList<String> ids = new ArrayList<>(); // for (int i = 0; i < count; i++) { // ids.add(generate()); // } // return ids; // } // // }
import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.not; import static org.hamcrest.Matchers.hasSize; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import java.util.Arrays; import java.util.Collection; import org.apache.commons.lang3.StringUtils; import org.junit.Test; import org.n52.supervisor.id.IdentifierGenerator; import org.n52.supervisor.id.ShortAlphanumericIdentifierGenerator;
/** * Copyright (C) 2013 - 2014 52°North Initiative for Geospatial Open Source Software GmbH * * 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.n52.supervisor; public class Identifiers { @Test public void identifiersAreGenerated() {
// Path: core/src/main/java/org/n52/supervisor/id/IdentifierGenerator.java // public interface IdentifierGenerator { // // public abstract String generate(); // // public abstract Collection<String> generate(int count); // // } // // Path: core/src/main/java/org/n52/supervisor/id/ShortAlphanumericIdentifierGenerator.java // public class ShortAlphanumericIdentifierGenerator implements IdentifierGenerator { // // private static Logger log = LoggerFactory.getLogger(ShortAlphanumericIdentifierGenerator.class); // // public static final int ID_LENGTH = 10; // // public ShortAlphanumericIdentifierGenerator() { // log.debug("NEW {}", this); // } // // @Override // public String generate() { // return RandomStringUtils.randomAlphanumeric(ID_LENGTH).toLowerCase(); // } // // @Override // public Collection<String> generate(int count) { // ArrayList<String> ids = new ArrayList<>(); // for (int i = 0; i < count; i++) { // ids.add(generate()); // } // return ids; // } // // } // Path: core/src/test/java/org/n52/supervisor/Identifiers.java import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.not; import static org.hamcrest.Matchers.hasSize; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import java.util.Arrays; import java.util.Collection; import org.apache.commons.lang3.StringUtils; import org.junit.Test; import org.n52.supervisor.id.IdentifierGenerator; import org.n52.supervisor.id.ShortAlphanumericIdentifierGenerator; /** * Copyright (C) 2013 - 2014 52°North Initiative for Geospatial Open Source Software GmbH * * 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.n52.supervisor; public class Identifiers { @Test public void identifiersAreGenerated() {
IdentifierGenerator gen = new ShortAlphanumericIdentifierGenerator();
52North/Supervisor
core/src/test/java/org/n52/supervisor/Identifiers.java
// Path: core/src/main/java/org/n52/supervisor/id/IdentifierGenerator.java // public interface IdentifierGenerator { // // public abstract String generate(); // // public abstract Collection<String> generate(int count); // // } // // Path: core/src/main/java/org/n52/supervisor/id/ShortAlphanumericIdentifierGenerator.java // public class ShortAlphanumericIdentifierGenerator implements IdentifierGenerator { // // private static Logger log = LoggerFactory.getLogger(ShortAlphanumericIdentifierGenerator.class); // // public static final int ID_LENGTH = 10; // // public ShortAlphanumericIdentifierGenerator() { // log.debug("NEW {}", this); // } // // @Override // public String generate() { // return RandomStringUtils.randomAlphanumeric(ID_LENGTH).toLowerCase(); // } // // @Override // public Collection<String> generate(int count) { // ArrayList<String> ids = new ArrayList<>(); // for (int i = 0; i < count; i++) { // ids.add(generate()); // } // return ids; // } // // }
import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.not; import static org.hamcrest.Matchers.hasSize; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import java.util.Arrays; import java.util.Collection; import org.apache.commons.lang3.StringUtils; import org.junit.Test; import org.n52.supervisor.id.IdentifierGenerator; import org.n52.supervisor.id.ShortAlphanumericIdentifierGenerator;
/** * Copyright (C) 2013 - 2014 52°North Initiative for Geospatial Open Source Software GmbH * * 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.n52.supervisor; public class Identifiers { @Test public void identifiersAreGenerated() {
// Path: core/src/main/java/org/n52/supervisor/id/IdentifierGenerator.java // public interface IdentifierGenerator { // // public abstract String generate(); // // public abstract Collection<String> generate(int count); // // } // // Path: core/src/main/java/org/n52/supervisor/id/ShortAlphanumericIdentifierGenerator.java // public class ShortAlphanumericIdentifierGenerator implements IdentifierGenerator { // // private static Logger log = LoggerFactory.getLogger(ShortAlphanumericIdentifierGenerator.class); // // public static final int ID_LENGTH = 10; // // public ShortAlphanumericIdentifierGenerator() { // log.debug("NEW {}", this); // } // // @Override // public String generate() { // return RandomStringUtils.randomAlphanumeric(ID_LENGTH).toLowerCase(); // } // // @Override // public Collection<String> generate(int count) { // ArrayList<String> ids = new ArrayList<>(); // for (int i = 0; i < count; i++) { // ids.add(generate()); // } // return ids; // } // // } // Path: core/src/test/java/org/n52/supervisor/Identifiers.java import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.not; import static org.hamcrest.Matchers.hasSize; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import java.util.Arrays; import java.util.Collection; import org.apache.commons.lang3.StringUtils; import org.junit.Test; import org.n52.supervisor.id.IdentifierGenerator; import org.n52.supervisor.id.ShortAlphanumericIdentifierGenerator; /** * Copyright (C) 2013 - 2014 52°North Initiative for Geospatial Open Source Software GmbH * * 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.n52.supervisor; public class Identifiers { @Test public void identifiersAreGenerated() {
IdentifierGenerator gen = new ShortAlphanumericIdentifierGenerator();
52North/Supervisor
core/src/main/java/org/n52/supervisor/GuiceServletConfig.java
// Path: core/src/main/java/org/n52/supervisor/db/StorageModule.java // public class StorageModule extends AbstractModule { // // private static Logger log = LoggerFactory.getLogger(StorageModule.class); // // @Override // public void configure() { // bind(CheckDatabase.class); // bind(ResultDatabase.class); // // log.info("Configured {}", this); // } // // } // // Path: core/src/main/java/org/n52/supervisor/id/IdentificationModule.java // public class IdentificationModule extends AbstractModule { // // @Override // protected void configure() { // bind(IdentifierGenerator.class).to(ShortAlphanumericIdentifierGenerator.class); // } // // } // // Path: core/src/main/java/org/n52/supervisor/tasks/TaskModule.java // public class TaskModule extends AbstractModule { // // private static Logger log = LoggerFactory.getLogger(TaskModule.class); // // @Override // protected void configure() { // bind(TaskExecutor.class).to(QuartzTaskExecutor.class); // bind(Scheduler.class).to(JobSchedulerImpl.class); // // install(new FactoryModuleBuilder().implement(CheckTask.class, CheckTaskImpl.class).build(CheckTaskFactory.class)); // // log.info("Configured {}", this); // // } // // }
import com.google.inject.AbstractModule; import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.servlet.GuiceServletContextListener; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.ServiceLoader; import java.util.concurrent.Executors; import javax.servlet.ServletContextEvent; import org.n52.supervisor.db.StorageModule; import org.n52.supervisor.id.IdentificationModule; import org.n52.supervisor.tasks.TaskModule; import org.nnsoft.guice.lifegycle.DisposeModule; import org.nnsoft.guice.lifegycle.Disposer; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
/** * Copyright (C) 2013 - 2014 52°North Initiative for Geospatial Open Source Software GmbH * * 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.n52.supervisor; /** * http://code.google.com/p/google-guice/wiki/ServletModule */ public class GuiceServletConfig extends GuiceServletContextListener { private static final Logger logger = LoggerFactory.getLogger(GuiceServletConfig.class); private class InitThread extends Thread { private Injector i; public InitThread(Injector i) { this.i = i; } @Override public void run() { SupervisorInit instance = this.i.getInstance(SupervisorInit.class); System.out.println(instance); } } private Injector injector; @Override public void contextDestroyed(ServletContextEvent servletContextEvent) { super.contextDestroyed(servletContextEvent); injector.getInstance(Disposer.class).dispose(); } @Override protected Injector getInjector() { List<AbstractModule> modules = new ArrayList<>(); modules.add(new SupervisorProperties.Module());
// Path: core/src/main/java/org/n52/supervisor/db/StorageModule.java // public class StorageModule extends AbstractModule { // // private static Logger log = LoggerFactory.getLogger(StorageModule.class); // // @Override // public void configure() { // bind(CheckDatabase.class); // bind(ResultDatabase.class); // // log.info("Configured {}", this); // } // // } // // Path: core/src/main/java/org/n52/supervisor/id/IdentificationModule.java // public class IdentificationModule extends AbstractModule { // // @Override // protected void configure() { // bind(IdentifierGenerator.class).to(ShortAlphanumericIdentifierGenerator.class); // } // // } // // Path: core/src/main/java/org/n52/supervisor/tasks/TaskModule.java // public class TaskModule extends AbstractModule { // // private static Logger log = LoggerFactory.getLogger(TaskModule.class); // // @Override // protected void configure() { // bind(TaskExecutor.class).to(QuartzTaskExecutor.class); // bind(Scheduler.class).to(JobSchedulerImpl.class); // // install(new FactoryModuleBuilder().implement(CheckTask.class, CheckTaskImpl.class).build(CheckTaskFactory.class)); // // log.info("Configured {}", this); // // } // // } // Path: core/src/main/java/org/n52/supervisor/GuiceServletConfig.java import com.google.inject.AbstractModule; import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.servlet.GuiceServletContextListener; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.ServiceLoader; import java.util.concurrent.Executors; import javax.servlet.ServletContextEvent; import org.n52.supervisor.db.StorageModule; import org.n52.supervisor.id.IdentificationModule; import org.n52.supervisor.tasks.TaskModule; import org.nnsoft.guice.lifegycle.DisposeModule; import org.nnsoft.guice.lifegycle.Disposer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Copyright (C) 2013 - 2014 52°North Initiative for Geospatial Open Source Software GmbH * * 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.n52.supervisor; /** * http://code.google.com/p/google-guice/wiki/ServletModule */ public class GuiceServletConfig extends GuiceServletContextListener { private static final Logger logger = LoggerFactory.getLogger(GuiceServletConfig.class); private class InitThread extends Thread { private Injector i; public InitThread(Injector i) { this.i = i; } @Override public void run() { SupervisorInit instance = this.i.getInstance(SupervisorInit.class); System.out.println(instance); } } private Injector injector; @Override public void contextDestroyed(ServletContextEvent servletContextEvent) { super.contextDestroyed(servletContextEvent); injector.getInstance(Disposer.class).dispose(); } @Override protected Injector getInjector() { List<AbstractModule> modules = new ArrayList<>(); modules.add(new SupervisorProperties.Module());
modules.add(new IdentificationModule());
52North/Supervisor
core/src/main/java/org/n52/supervisor/GuiceServletConfig.java
// Path: core/src/main/java/org/n52/supervisor/db/StorageModule.java // public class StorageModule extends AbstractModule { // // private static Logger log = LoggerFactory.getLogger(StorageModule.class); // // @Override // public void configure() { // bind(CheckDatabase.class); // bind(ResultDatabase.class); // // log.info("Configured {}", this); // } // // } // // Path: core/src/main/java/org/n52/supervisor/id/IdentificationModule.java // public class IdentificationModule extends AbstractModule { // // @Override // protected void configure() { // bind(IdentifierGenerator.class).to(ShortAlphanumericIdentifierGenerator.class); // } // // } // // Path: core/src/main/java/org/n52/supervisor/tasks/TaskModule.java // public class TaskModule extends AbstractModule { // // private static Logger log = LoggerFactory.getLogger(TaskModule.class); // // @Override // protected void configure() { // bind(TaskExecutor.class).to(QuartzTaskExecutor.class); // bind(Scheduler.class).to(JobSchedulerImpl.class); // // install(new FactoryModuleBuilder().implement(CheckTask.class, CheckTaskImpl.class).build(CheckTaskFactory.class)); // // log.info("Configured {}", this); // // } // // }
import com.google.inject.AbstractModule; import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.servlet.GuiceServletContextListener; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.ServiceLoader; import java.util.concurrent.Executors; import javax.servlet.ServletContextEvent; import org.n52.supervisor.db.StorageModule; import org.n52.supervisor.id.IdentificationModule; import org.n52.supervisor.tasks.TaskModule; import org.nnsoft.guice.lifegycle.DisposeModule; import org.nnsoft.guice.lifegycle.Disposer; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
/** * Copyright (C) 2013 - 2014 52°North Initiative for Geospatial Open Source Software GmbH * * 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.n52.supervisor; /** * http://code.google.com/p/google-guice/wiki/ServletModule */ public class GuiceServletConfig extends GuiceServletContextListener { private static final Logger logger = LoggerFactory.getLogger(GuiceServletConfig.class); private class InitThread extends Thread { private Injector i; public InitThread(Injector i) { this.i = i; } @Override public void run() { SupervisorInit instance = this.i.getInstance(SupervisorInit.class); System.out.println(instance); } } private Injector injector; @Override public void contextDestroyed(ServletContextEvent servletContextEvent) { super.contextDestroyed(servletContextEvent); injector.getInstance(Disposer.class).dispose(); } @Override protected Injector getInjector() { List<AbstractModule> modules = new ArrayList<>(); modules.add(new SupervisorProperties.Module()); modules.add(new IdentificationModule()); modules.add(new ConfigModule());
// Path: core/src/main/java/org/n52/supervisor/db/StorageModule.java // public class StorageModule extends AbstractModule { // // private static Logger log = LoggerFactory.getLogger(StorageModule.class); // // @Override // public void configure() { // bind(CheckDatabase.class); // bind(ResultDatabase.class); // // log.info("Configured {}", this); // } // // } // // Path: core/src/main/java/org/n52/supervisor/id/IdentificationModule.java // public class IdentificationModule extends AbstractModule { // // @Override // protected void configure() { // bind(IdentifierGenerator.class).to(ShortAlphanumericIdentifierGenerator.class); // } // // } // // Path: core/src/main/java/org/n52/supervisor/tasks/TaskModule.java // public class TaskModule extends AbstractModule { // // private static Logger log = LoggerFactory.getLogger(TaskModule.class); // // @Override // protected void configure() { // bind(TaskExecutor.class).to(QuartzTaskExecutor.class); // bind(Scheduler.class).to(JobSchedulerImpl.class); // // install(new FactoryModuleBuilder().implement(CheckTask.class, CheckTaskImpl.class).build(CheckTaskFactory.class)); // // log.info("Configured {}", this); // // } // // } // Path: core/src/main/java/org/n52/supervisor/GuiceServletConfig.java import com.google.inject.AbstractModule; import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.servlet.GuiceServletContextListener; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.ServiceLoader; import java.util.concurrent.Executors; import javax.servlet.ServletContextEvent; import org.n52.supervisor.db.StorageModule; import org.n52.supervisor.id.IdentificationModule; import org.n52.supervisor.tasks.TaskModule; import org.nnsoft.guice.lifegycle.DisposeModule; import org.nnsoft.guice.lifegycle.Disposer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Copyright (C) 2013 - 2014 52°North Initiative for Geospatial Open Source Software GmbH * * 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.n52.supervisor; /** * http://code.google.com/p/google-guice/wiki/ServletModule */ public class GuiceServletConfig extends GuiceServletContextListener { private static final Logger logger = LoggerFactory.getLogger(GuiceServletConfig.class); private class InitThread extends Thread { private Injector i; public InitThread(Injector i) { this.i = i; } @Override public void run() { SupervisorInit instance = this.i.getInstance(SupervisorInit.class); System.out.println(instance); } } private Injector injector; @Override public void contextDestroyed(ServletContextEvent servletContextEvent) { super.contextDestroyed(servletContextEvent); injector.getInstance(Disposer.class).dispose(); } @Override protected Injector getInjector() { List<AbstractModule> modules = new ArrayList<>(); modules.add(new SupervisorProperties.Module()); modules.add(new IdentificationModule()); modules.add(new ConfigModule());
modules.add(new StorageModule());
52North/Supervisor
core/src/main/java/org/n52/supervisor/GuiceServletConfig.java
// Path: core/src/main/java/org/n52/supervisor/db/StorageModule.java // public class StorageModule extends AbstractModule { // // private static Logger log = LoggerFactory.getLogger(StorageModule.class); // // @Override // public void configure() { // bind(CheckDatabase.class); // bind(ResultDatabase.class); // // log.info("Configured {}", this); // } // // } // // Path: core/src/main/java/org/n52/supervisor/id/IdentificationModule.java // public class IdentificationModule extends AbstractModule { // // @Override // protected void configure() { // bind(IdentifierGenerator.class).to(ShortAlphanumericIdentifierGenerator.class); // } // // } // // Path: core/src/main/java/org/n52/supervisor/tasks/TaskModule.java // public class TaskModule extends AbstractModule { // // private static Logger log = LoggerFactory.getLogger(TaskModule.class); // // @Override // protected void configure() { // bind(TaskExecutor.class).to(QuartzTaskExecutor.class); // bind(Scheduler.class).to(JobSchedulerImpl.class); // // install(new FactoryModuleBuilder().implement(CheckTask.class, CheckTaskImpl.class).build(CheckTaskFactory.class)); // // log.info("Configured {}", this); // // } // // }
import com.google.inject.AbstractModule; import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.servlet.GuiceServletContextListener; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.ServiceLoader; import java.util.concurrent.Executors; import javax.servlet.ServletContextEvent; import org.n52.supervisor.db.StorageModule; import org.n52.supervisor.id.IdentificationModule; import org.n52.supervisor.tasks.TaskModule; import org.nnsoft.guice.lifegycle.DisposeModule; import org.nnsoft.guice.lifegycle.Disposer; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
/** * Copyright (C) 2013 - 2014 52°North Initiative for Geospatial Open Source Software GmbH * * 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.n52.supervisor; /** * http://code.google.com/p/google-guice/wiki/ServletModule */ public class GuiceServletConfig extends GuiceServletContextListener { private static final Logger logger = LoggerFactory.getLogger(GuiceServletConfig.class); private class InitThread extends Thread { private Injector i; public InitThread(Injector i) { this.i = i; } @Override public void run() { SupervisorInit instance = this.i.getInstance(SupervisorInit.class); System.out.println(instance); } } private Injector injector; @Override public void contextDestroyed(ServletContextEvent servletContextEvent) { super.contextDestroyed(servletContextEvent); injector.getInstance(Disposer.class).dispose(); } @Override protected Injector getInjector() { List<AbstractModule> modules = new ArrayList<>(); modules.add(new SupervisorProperties.Module()); modules.add(new IdentificationModule()); modules.add(new ConfigModule()); modules.add(new StorageModule()); modules.add(new SupervisorModule());
// Path: core/src/main/java/org/n52/supervisor/db/StorageModule.java // public class StorageModule extends AbstractModule { // // private static Logger log = LoggerFactory.getLogger(StorageModule.class); // // @Override // public void configure() { // bind(CheckDatabase.class); // bind(ResultDatabase.class); // // log.info("Configured {}", this); // } // // } // // Path: core/src/main/java/org/n52/supervisor/id/IdentificationModule.java // public class IdentificationModule extends AbstractModule { // // @Override // protected void configure() { // bind(IdentifierGenerator.class).to(ShortAlphanumericIdentifierGenerator.class); // } // // } // // Path: core/src/main/java/org/n52/supervisor/tasks/TaskModule.java // public class TaskModule extends AbstractModule { // // private static Logger log = LoggerFactory.getLogger(TaskModule.class); // // @Override // protected void configure() { // bind(TaskExecutor.class).to(QuartzTaskExecutor.class); // bind(Scheduler.class).to(JobSchedulerImpl.class); // // install(new FactoryModuleBuilder().implement(CheckTask.class, CheckTaskImpl.class).build(CheckTaskFactory.class)); // // log.info("Configured {}", this); // // } // // } // Path: core/src/main/java/org/n52/supervisor/GuiceServletConfig.java import com.google.inject.AbstractModule; import com.google.inject.Guice; import com.google.inject.Injector; import com.google.inject.servlet.GuiceServletContextListener; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.ServiceLoader; import java.util.concurrent.Executors; import javax.servlet.ServletContextEvent; import org.n52.supervisor.db.StorageModule; import org.n52.supervisor.id.IdentificationModule; import org.n52.supervisor.tasks.TaskModule; import org.nnsoft.guice.lifegycle.DisposeModule; import org.nnsoft.guice.lifegycle.Disposer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Copyright (C) 2013 - 2014 52°North Initiative for Geospatial Open Source Software GmbH * * 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.n52.supervisor; /** * http://code.google.com/p/google-guice/wiki/ServletModule */ public class GuiceServletConfig extends GuiceServletContextListener { private static final Logger logger = LoggerFactory.getLogger(GuiceServletConfig.class); private class InitThread extends Thread { private Injector i; public InitThread(Injector i) { this.i = i; } @Override public void run() { SupervisorInit instance = this.i.getInstance(SupervisorInit.class); System.out.println(instance); } } private Injector injector; @Override public void contextDestroyed(ServletContextEvent servletContextEvent) { super.contextDestroyed(servletContextEvent); injector.getInstance(Disposer.class).dispose(); } @Override protected Injector getInjector() { List<AbstractModule> modules = new ArrayList<>(); modules.add(new SupervisorProperties.Module()); modules.add(new IdentificationModule()); modules.add(new ConfigModule()); modules.add(new StorageModule()); modules.add(new SupervisorModule());
modules.add(new TaskModule());
52North/Supervisor
core/src/main/java/org/n52/supervisor/tasks/ManualChecker.java
// Path: core/src/main/java/org/n52/supervisor/api/CheckRunner.java // public interface CheckRunner { // // final IdentifierGenerator ID_GENERATOR = new ShortAlphanumericIdentifierGenerator(); // // public void addResult(CheckResult r); // // public boolean check(); // // public Check getCheck(); // // public Collection<CheckResult> getResults(); // // public Collection<CheckResult> getAndClearResults(); // // public void notifyFailure(); // // public void notifySuccess(); // // public void setCheck(Check check) throws UnsupportedCheckException; // // /** // * @param rd // * is required so that the runner can announce its results // */ // public void setResultDatabase(ResultDatabase rd); // // }
import java.util.Collection; import org.n52.supervisor.api.CheckRunner; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
/** * Copyright (C) 2013 - 2014 52°North Initiative for Geospatial Open Source Software GmbH * * 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.n52.supervisor.tasks; public class ManualChecker extends Thread { private static Logger log = LoggerFactory.getLogger(ManualChecker.class);
// Path: core/src/main/java/org/n52/supervisor/api/CheckRunner.java // public interface CheckRunner { // // final IdentifierGenerator ID_GENERATOR = new ShortAlphanumericIdentifierGenerator(); // // public void addResult(CheckResult r); // // public boolean check(); // // public Check getCheck(); // // public Collection<CheckResult> getResults(); // // public Collection<CheckResult> getAndClearResults(); // // public void notifyFailure(); // // public void notifySuccess(); // // public void setCheck(Check check) throws UnsupportedCheckException; // // /** // * @param rd // * is required so that the runner can announce its results // */ // public void setResultDatabase(ResultDatabase rd); // // } // Path: core/src/main/java/org/n52/supervisor/tasks/ManualChecker.java import java.util.Collection; import org.n52.supervisor.api.CheckRunner; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Copyright (C) 2013 - 2014 52°North Initiative for Geospatial Open Source Software GmbH * * 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.n52.supervisor.tasks; public class ManualChecker extends Thread { private static Logger log = LoggerFactory.getLogger(ManualChecker.class);
private Collection<CheckRunner> checkers;
DistantEye/EP_Utilities
EclipsePhaseLifePath/src/com/github/distanteye/ep_utils/commands/BackupCharCommand.java
// Path: EclipsePhaseLifePath/src/com/github/distanteye/ep_utils/core/CharacterEnvironment.java // public interface CharacterEnvironment { // // EpCharacter getPC(); // SecureRandom getRng(); // UI getUI(); // // /** // * Emulates a dice roll // * @param numSides upper limit of the dice roll, will return number from 1 to numSides, inclusive // * @param rollMessage Prompt/Message relevant to the roll, will display if interactive choice mode triggers // * @param forceRoll If true, is always a true random roll, if false, and if isRolling is false, prompts the user to make an interactive choice // * @return // */ // int rollDice(int numSides, String rollMessage, boolean forceRoll); // // /** // * Resets the CharacterEnvironment to its default state // */ // void reset(); // // void setHasFinished(boolean hasFinished); // // /** // * Flags the effects processing engine to notStop after finishing this current step // */ // void setNoStop(); // // /** // * Flags the effects processing engine that it needs to return control to UI after finishing // * the current step. If setNoStop was called, this will be ignored. // */ // void setEffectsNeedReturn(); // // /** // * Flags the effects processing engine to skip to the specified effects String, overriding // * default behavior when moving to the next step // * @param stepSkipTo Valid command/effects string // */ // void setStepSkipTo(String stepSkipTo); // // /** // * A "quick save" that pushes to an internal String the current character state. // * Can be loaded to character with loadBackup // */ // public void backupCharacter(); // // /** // * Takes the backup from backupCharacter and overwrites Character with it // * Will not work if backupCharacter hasn't been called yet // */ // public void loadBackup(); // // public boolean isAllRandom(); // }
import com.github.distanteye.ep_utils.core.CharacterEnvironment;
package com.github.distanteye.ep_utils.commands; /** * Command of following syntax types: * backupCharacter() * * @author Vigilant * */ public class BackupCharCommand extends Command { /** *Creates a command from the given effects string * @param input Valid input string, this should be the full String with command name and () still */ public BackupCharCommand(String input) { super(input); if (subparts.length != 1) { throw new IllegalArgumentException("Poorly formated effect (wrong number params) " + input); } }
// Path: EclipsePhaseLifePath/src/com/github/distanteye/ep_utils/core/CharacterEnvironment.java // public interface CharacterEnvironment { // // EpCharacter getPC(); // SecureRandom getRng(); // UI getUI(); // // /** // * Emulates a dice roll // * @param numSides upper limit of the dice roll, will return number from 1 to numSides, inclusive // * @param rollMessage Prompt/Message relevant to the roll, will display if interactive choice mode triggers // * @param forceRoll If true, is always a true random roll, if false, and if isRolling is false, prompts the user to make an interactive choice // * @return // */ // int rollDice(int numSides, String rollMessage, boolean forceRoll); // // /** // * Resets the CharacterEnvironment to its default state // */ // void reset(); // // void setHasFinished(boolean hasFinished); // // /** // * Flags the effects processing engine to notStop after finishing this current step // */ // void setNoStop(); // // /** // * Flags the effects processing engine that it needs to return control to UI after finishing // * the current step. If setNoStop was called, this will be ignored. // */ // void setEffectsNeedReturn(); // // /** // * Flags the effects processing engine to skip to the specified effects String, overriding // * default behavior when moving to the next step // * @param stepSkipTo Valid command/effects string // */ // void setStepSkipTo(String stepSkipTo); // // /** // * A "quick save" that pushes to an internal String the current character state. // * Can be loaded to character with loadBackup // */ // public void backupCharacter(); // // /** // * Takes the backup from backupCharacter and overwrites Character with it // * Will not work if backupCharacter hasn't been called yet // */ // public void loadBackup(); // // public boolean isAllRandom(); // } // Path: EclipsePhaseLifePath/src/com/github/distanteye/ep_utils/commands/BackupCharCommand.java import com.github.distanteye.ep_utils.core.CharacterEnvironment; package com.github.distanteye.ep_utils.commands; /** * Command of following syntax types: * backupCharacter() * * @author Vigilant * */ public class BackupCharCommand extends Command { /** *Creates a command from the given effects string * @param input Valid input string, this should be the full String with command name and () still */ public BackupCharCommand(String input) { super(input); if (subparts.length != 1) { throw new IllegalArgumentException("Poorly formated effect (wrong number params) " + input); } }
public String run(CharacterEnvironment env)
DistantEye/EP_Utilities
EclipsePhaseLifePath/src/com/github/distanteye/ep_utils/commands/directives/SimpRollDiceDirective.java
// Path: EclipsePhaseLifePath/src/com/github/distanteye/ep_utils/core/CharacterEnvironment.java // public interface CharacterEnvironment { // // EpCharacter getPC(); // SecureRandom getRng(); // UI getUI(); // // /** // * Emulates a dice roll // * @param numSides upper limit of the dice roll, will return number from 1 to numSides, inclusive // * @param rollMessage Prompt/Message relevant to the roll, will display if interactive choice mode triggers // * @param forceRoll If true, is always a true random roll, if false, and if isRolling is false, prompts the user to make an interactive choice // * @return // */ // int rollDice(int numSides, String rollMessage, boolean forceRoll); // // /** // * Resets the CharacterEnvironment to its default state // */ // void reset(); // // void setHasFinished(boolean hasFinished); // // /** // * Flags the effects processing engine to notStop after finishing this current step // */ // void setNoStop(); // // /** // * Flags the effects processing engine that it needs to return control to UI after finishing // * the current step. If setNoStop was called, this will be ignored. // */ // void setEffectsNeedReturn(); // // /** // * Flags the effects processing engine to skip to the specified effects String, overriding // * default behavior when moving to the next step // * @param stepSkipTo Valid command/effects string // */ // void setStepSkipTo(String stepSkipTo); // // /** // * A "quick save" that pushes to an internal String the current character state. // * Can be loaded to character with loadBackup // */ // public void backupCharacter(); // // /** // * Takes the backup from backupCharacter and overwrites Character with it // * Will not work if backupCharacter hasn't been called yet // */ // public void loadBackup(); // // public boolean isAllRandom(); // }
import com.github.distanteye.ep_utils.core.CharacterEnvironment;
package com.github.distanteye.ep_utils.commands.directives; /** * Directive of syntax: * simpRollDice(<numDice>,<sides>) players cannot choose the result of this (always forceRoll true) * * @author Vigilant * */ public class SimpRollDiceDirective extends Directive { /** *Creates a command from the given effects string * @param input Valid formatted command effect string, this should be the full String with command name and still */ public SimpRollDiceDirective(String input) { super(input); // validation comes during process() subpartsToParams(); } /* (non-Javadoc) * @see com.github.distanteye.ep_utils.commands.directives.Directive#process(com.github.distanteye.ep_utils.containers.EpCharacter) */ @Override
// Path: EclipsePhaseLifePath/src/com/github/distanteye/ep_utils/core/CharacterEnvironment.java // public interface CharacterEnvironment { // // EpCharacter getPC(); // SecureRandom getRng(); // UI getUI(); // // /** // * Emulates a dice roll // * @param numSides upper limit of the dice roll, will return number from 1 to numSides, inclusive // * @param rollMessage Prompt/Message relevant to the roll, will display if interactive choice mode triggers // * @param forceRoll If true, is always a true random roll, if false, and if isRolling is false, prompts the user to make an interactive choice // * @return // */ // int rollDice(int numSides, String rollMessage, boolean forceRoll); // // /** // * Resets the CharacterEnvironment to its default state // */ // void reset(); // // void setHasFinished(boolean hasFinished); // // /** // * Flags the effects processing engine to notStop after finishing this current step // */ // void setNoStop(); // // /** // * Flags the effects processing engine that it needs to return control to UI after finishing // * the current step. If setNoStop was called, this will be ignored. // */ // void setEffectsNeedReturn(); // // /** // * Flags the effects processing engine to skip to the specified effects String, overriding // * default behavior when moving to the next step // * @param stepSkipTo Valid command/effects string // */ // void setStepSkipTo(String stepSkipTo); // // /** // * A "quick save" that pushes to an internal String the current character state. // * Can be loaded to character with loadBackup // */ // public void backupCharacter(); // // /** // * Takes the backup from backupCharacter and overwrites Character with it // * Will not work if backupCharacter hasn't been called yet // */ // public void loadBackup(); // // public boolean isAllRandom(); // } // Path: EclipsePhaseLifePath/src/com/github/distanteye/ep_utils/commands/directives/SimpRollDiceDirective.java import com.github.distanteye.ep_utils.core.CharacterEnvironment; package com.github.distanteye.ep_utils.commands.directives; /** * Directive of syntax: * simpRollDice(<numDice>,<sides>) players cannot choose the result of this (always forceRoll true) * * @author Vigilant * */ public class SimpRollDiceDirective extends Directive { /** *Creates a command from the given effects string * @param input Valid formatted command effect string, this should be the full String with command name and still */ public SimpRollDiceDirective(String input) { super(input); // validation comes during process() subpartsToParams(); } /* (non-Javadoc) * @see com.github.distanteye.ep_utils.commands.directives.Directive#process(com.github.distanteye.ep_utils.containers.EpCharacter) */ @Override
public String process(CharacterEnvironment env) {
DistantEye/EP_Utilities
EclipsePhaseLifePath/src/com/github/distanteye/ep_utils/commands/SetVarCommand.java
// Path: EclipsePhaseLifePath/src/com/github/distanteye/ep_utils/core/CharacterEnvironment.java // public interface CharacterEnvironment { // // EpCharacter getPC(); // SecureRandom getRng(); // UI getUI(); // // /** // * Emulates a dice roll // * @param numSides upper limit of the dice roll, will return number from 1 to numSides, inclusive // * @param rollMessage Prompt/Message relevant to the roll, will display if interactive choice mode triggers // * @param forceRoll If true, is always a true random roll, if false, and if isRolling is false, prompts the user to make an interactive choice // * @return // */ // int rollDice(int numSides, String rollMessage, boolean forceRoll); // // /** // * Resets the CharacterEnvironment to its default state // */ // void reset(); // // void setHasFinished(boolean hasFinished); // // /** // * Flags the effects processing engine to notStop after finishing this current step // */ // void setNoStop(); // // /** // * Flags the effects processing engine that it needs to return control to UI after finishing // * the current step. If setNoStop was called, this will be ignored. // */ // void setEffectsNeedReturn(); // // /** // * Flags the effects processing engine to skip to the specified effects String, overriding // * default behavior when moving to the next step // * @param stepSkipTo Valid command/effects string // */ // void setStepSkipTo(String stepSkipTo); // // /** // * A "quick save" that pushes to an internal String the current character state. // * Can be loaded to character with loadBackup // */ // public void backupCharacter(); // // /** // * Takes the backup from backupCharacter and overwrites Character with it // * Will not work if backupCharacter hasn't been called yet // */ // public void loadBackup(); // // public boolean isAllRandom(); // }
import com.github.distanteye.ep_utils.core.CharacterEnvironment;
package com.github.distanteye.ep_utils.commands; /** * Command of following syntax types: * setVar(<name>,<value>) * * @author Vigilant * */ public class SetVarCommand extends Command { /** *Creates a command from the given effects string * @param input Valid input string, this should be the full String with command name and () still */ public SetVarCommand(String input) { super(input); if (subparts.length != 3 ) { throw new IllegalArgumentException("Poorly formated effect (wrong number params) " + input); } else if (!( subparts[1].length() > 0 && subparts[2].length() > 0)) { throw new IllegalArgumentException("Poorly formated effect (params blank) " + input); } subpartsToParams(); }
// Path: EclipsePhaseLifePath/src/com/github/distanteye/ep_utils/core/CharacterEnvironment.java // public interface CharacterEnvironment { // // EpCharacter getPC(); // SecureRandom getRng(); // UI getUI(); // // /** // * Emulates a dice roll // * @param numSides upper limit of the dice roll, will return number from 1 to numSides, inclusive // * @param rollMessage Prompt/Message relevant to the roll, will display if interactive choice mode triggers // * @param forceRoll If true, is always a true random roll, if false, and if isRolling is false, prompts the user to make an interactive choice // * @return // */ // int rollDice(int numSides, String rollMessage, boolean forceRoll); // // /** // * Resets the CharacterEnvironment to its default state // */ // void reset(); // // void setHasFinished(boolean hasFinished); // // /** // * Flags the effects processing engine to notStop after finishing this current step // */ // void setNoStop(); // // /** // * Flags the effects processing engine that it needs to return control to UI after finishing // * the current step. If setNoStop was called, this will be ignored. // */ // void setEffectsNeedReturn(); // // /** // * Flags the effects processing engine to skip to the specified effects String, overriding // * default behavior when moving to the next step // * @param stepSkipTo Valid command/effects string // */ // void setStepSkipTo(String stepSkipTo); // // /** // * A "quick save" that pushes to an internal String the current character state. // * Can be loaded to character with loadBackup // */ // public void backupCharacter(); // // /** // * Takes the backup from backupCharacter and overwrites Character with it // * Will not work if backupCharacter hasn't been called yet // */ // public void loadBackup(); // // public boolean isAllRandom(); // } // Path: EclipsePhaseLifePath/src/com/github/distanteye/ep_utils/commands/SetVarCommand.java import com.github.distanteye.ep_utils.core.CharacterEnvironment; package com.github.distanteye.ep_utils.commands; /** * Command of following syntax types: * setVar(<name>,<value>) * * @author Vigilant * */ public class SetVarCommand extends Command { /** *Creates a command from the given effects string * @param input Valid input string, this should be the full String with command name and () still */ public SetVarCommand(String input) { super(input); if (subparts.length != 3 ) { throw new IllegalArgumentException("Poorly formated effect (wrong number params) " + input); } else if (!( subparts[1].length() > 0 && subparts[2].length() > 0)) { throw new IllegalArgumentException("Poorly formated effect (params blank) " + input); } subpartsToParams(); }
public String run(CharacterEnvironment env)
DistantEye/EP_Utilities
EclipsePhaseLifePath/src/com/github/distanteye/ep_utils/commands/LoadCharBackupCommand.java
// Path: EclipsePhaseLifePath/src/com/github/distanteye/ep_utils/core/CharacterEnvironment.java // public interface CharacterEnvironment { // // EpCharacter getPC(); // SecureRandom getRng(); // UI getUI(); // // /** // * Emulates a dice roll // * @param numSides upper limit of the dice roll, will return number from 1 to numSides, inclusive // * @param rollMessage Prompt/Message relevant to the roll, will display if interactive choice mode triggers // * @param forceRoll If true, is always a true random roll, if false, and if isRolling is false, prompts the user to make an interactive choice // * @return // */ // int rollDice(int numSides, String rollMessage, boolean forceRoll); // // /** // * Resets the CharacterEnvironment to its default state // */ // void reset(); // // void setHasFinished(boolean hasFinished); // // /** // * Flags the effects processing engine to notStop after finishing this current step // */ // void setNoStop(); // // /** // * Flags the effects processing engine that it needs to return control to UI after finishing // * the current step. If setNoStop was called, this will be ignored. // */ // void setEffectsNeedReturn(); // // /** // * Flags the effects processing engine to skip to the specified effects String, overriding // * default behavior when moving to the next step // * @param stepSkipTo Valid command/effects string // */ // void setStepSkipTo(String stepSkipTo); // // /** // * A "quick save" that pushes to an internal String the current character state. // * Can be loaded to character with loadBackup // */ // public void backupCharacter(); // // /** // * Takes the backup from backupCharacter and overwrites Character with it // * Will not work if backupCharacter hasn't been called yet // */ // public void loadBackup(); // // public boolean isAllRandom(); // }
import com.github.distanteye.ep_utils.core.CharacterEnvironment;
package com.github.distanteye.ep_utils.commands; /** * Command of following syntax types: * loadCharBackup() * * @author Vigilant * */ public class LoadCharBackupCommand extends Command { /** *Creates a command from the given effects string * @param input Valid input string, this should be the full String with command name and () still */ public LoadCharBackupCommand(String input) { super(input); if (subparts.length != 1) { throw new IllegalArgumentException("Poorly formated effect (wrong number params) " + input); } }
// Path: EclipsePhaseLifePath/src/com/github/distanteye/ep_utils/core/CharacterEnvironment.java // public interface CharacterEnvironment { // // EpCharacter getPC(); // SecureRandom getRng(); // UI getUI(); // // /** // * Emulates a dice roll // * @param numSides upper limit of the dice roll, will return number from 1 to numSides, inclusive // * @param rollMessage Prompt/Message relevant to the roll, will display if interactive choice mode triggers // * @param forceRoll If true, is always a true random roll, if false, and if isRolling is false, prompts the user to make an interactive choice // * @return // */ // int rollDice(int numSides, String rollMessage, boolean forceRoll); // // /** // * Resets the CharacterEnvironment to its default state // */ // void reset(); // // void setHasFinished(boolean hasFinished); // // /** // * Flags the effects processing engine to notStop after finishing this current step // */ // void setNoStop(); // // /** // * Flags the effects processing engine that it needs to return control to UI after finishing // * the current step. If setNoStop was called, this will be ignored. // */ // void setEffectsNeedReturn(); // // /** // * Flags the effects processing engine to skip to the specified effects String, overriding // * default behavior when moving to the next step // * @param stepSkipTo Valid command/effects string // */ // void setStepSkipTo(String stepSkipTo); // // /** // * A "quick save" that pushes to an internal String the current character state. // * Can be loaded to character with loadBackup // */ // public void backupCharacter(); // // /** // * Takes the backup from backupCharacter and overwrites Character with it // * Will not work if backupCharacter hasn't been called yet // */ // public void loadBackup(); // // public boolean isAllRandom(); // } // Path: EclipsePhaseLifePath/src/com/github/distanteye/ep_utils/commands/LoadCharBackupCommand.java import com.github.distanteye.ep_utils.core.CharacterEnvironment; package com.github.distanteye.ep_utils.commands; /** * Command of following syntax types: * loadCharBackup() * * @author Vigilant * */ public class LoadCharBackupCommand extends Command { /** *Creates a command from the given effects string * @param input Valid input string, this should be the full String with command name and () still */ public LoadCharBackupCommand(String input) { super(input); if (subparts.length != 1) { throw new IllegalArgumentException("Poorly formated effect (wrong number params) " + input); } }
public String run(CharacterEnvironment env)
DistantEye/EP_Utilities
EclipsePhaseLifePath/src/com/github/distanteye/ep_utils/commands/RemVarCommand.java
// Path: EclipsePhaseLifePath/src/com/github/distanteye/ep_utils/core/CharacterEnvironment.java // public interface CharacterEnvironment { // // EpCharacter getPC(); // SecureRandom getRng(); // UI getUI(); // // /** // * Emulates a dice roll // * @param numSides upper limit of the dice roll, will return number from 1 to numSides, inclusive // * @param rollMessage Prompt/Message relevant to the roll, will display if interactive choice mode triggers // * @param forceRoll If true, is always a true random roll, if false, and if isRolling is false, prompts the user to make an interactive choice // * @return // */ // int rollDice(int numSides, String rollMessage, boolean forceRoll); // // /** // * Resets the CharacterEnvironment to its default state // */ // void reset(); // // void setHasFinished(boolean hasFinished); // // /** // * Flags the effects processing engine to notStop after finishing this current step // */ // void setNoStop(); // // /** // * Flags the effects processing engine that it needs to return control to UI after finishing // * the current step. If setNoStop was called, this will be ignored. // */ // void setEffectsNeedReturn(); // // /** // * Flags the effects processing engine to skip to the specified effects String, overriding // * default behavior when moving to the next step // * @param stepSkipTo Valid command/effects string // */ // void setStepSkipTo(String stepSkipTo); // // /** // * A "quick save" that pushes to an internal String the current character state. // * Can be loaded to character with loadBackup // */ // public void backupCharacter(); // // /** // * Takes the backup from backupCharacter and overwrites Character with it // * Will not work if backupCharacter hasn't been called yet // */ // public void loadBackup(); // // public boolean isAllRandom(); // }
import com.github.distanteye.ep_utils.core.CharacterEnvironment;
package com.github.distanteye.ep_utils.commands; /** * Command of following syntax types: * remVar(<name>) * * @author Vigilant * */ public class RemVarCommand extends Command { /** * Creates a command from the given effects string * @param input Valid input string, this should be the full String with command name and () still */ public RemVarCommand(String input) { super(input); if (subparts.length != 2 ) { throw new IllegalArgumentException("Poorly formated effect (wrong number params) " + input); } else if (subparts[1].length() == 0 ) { throw new IllegalArgumentException("Poorly formated effect (params blank) " + input); } params.put(1, subparts[1]); }
// Path: EclipsePhaseLifePath/src/com/github/distanteye/ep_utils/core/CharacterEnvironment.java // public interface CharacterEnvironment { // // EpCharacter getPC(); // SecureRandom getRng(); // UI getUI(); // // /** // * Emulates a dice roll // * @param numSides upper limit of the dice roll, will return number from 1 to numSides, inclusive // * @param rollMessage Prompt/Message relevant to the roll, will display if interactive choice mode triggers // * @param forceRoll If true, is always a true random roll, if false, and if isRolling is false, prompts the user to make an interactive choice // * @return // */ // int rollDice(int numSides, String rollMessage, boolean forceRoll); // // /** // * Resets the CharacterEnvironment to its default state // */ // void reset(); // // void setHasFinished(boolean hasFinished); // // /** // * Flags the effects processing engine to notStop after finishing this current step // */ // void setNoStop(); // // /** // * Flags the effects processing engine that it needs to return control to UI after finishing // * the current step. If setNoStop was called, this will be ignored. // */ // void setEffectsNeedReturn(); // // /** // * Flags the effects processing engine to skip to the specified effects String, overriding // * default behavior when moving to the next step // * @param stepSkipTo Valid command/effects string // */ // void setStepSkipTo(String stepSkipTo); // // /** // * A "quick save" that pushes to an internal String the current character state. // * Can be loaded to character with loadBackup // */ // public void backupCharacter(); // // /** // * Takes the backup from backupCharacter and overwrites Character with it // * Will not work if backupCharacter hasn't been called yet // */ // public void loadBackup(); // // public boolean isAllRandom(); // } // Path: EclipsePhaseLifePath/src/com/github/distanteye/ep_utils/commands/RemVarCommand.java import com.github.distanteye.ep_utils.core.CharacterEnvironment; package com.github.distanteye.ep_utils.commands; /** * Command of following syntax types: * remVar(<name>) * * @author Vigilant * */ public class RemVarCommand extends Command { /** * Creates a command from the given effects string * @param input Valid input string, this should be the full String with command name and () still */ public RemVarCommand(String input) { super(input); if (subparts.length != 2 ) { throw new IllegalArgumentException("Poorly formated effect (wrong number params) " + input); } else if (subparts[1].length() == 0 ) { throw new IllegalArgumentException("Poorly formated effect (params blank) " + input); } params.put(1, subparts[1]); }
public String run(CharacterEnvironment env)
DistantEye/EP_Utilities
EclipsePhaseLifePath/src/com/github/distanteye/ep_utils/ui/GBagPanel.java
// Path: EclipsePhaseLifePath/src/com/github/distanteye/ep_utils/wrappers/AccessWrapper.java // public abstract class AccessWrapper<T> { // abstract public T getValue(); // abstract public void setValue(T item); // // /** // * Reflects whether the underlying value is an Integer or not // * // * This provides an accessibility/performance bonus to some contexts // * // * @return True/False as appropriate // */ // abstract public boolean isInt(); // // } // // Path: EclipsePhaseLifePath/src/com/github/distanteye/ep_utils/wrappers/MappedComponent.java // public class MappedComponent { // private DataFlow df; // private AccessWrapper<String> linkedData; // private JComponent comp; // // // /** // * @param df Valid enum for what direction data flows between comp and linkedData // * Use DataFlow.STATIC for non-updating components // * @param linkedData AccessWrapper for interacting with the backend/character-data. This can be null if df==STATIC // * @param comp the JComponent being wrapped. If df is not STATIC, JComponent must extend JTextComponent // */ // public MappedComponent(DataFlow df, AccessWrapper<String> linkedData, JComponent comp) { // super(); // this.df = df; // this.comp = comp; // // if (df!=DataFlow.STATIC && !(comp instanceof JTextComponent || comp instanceof JButton)) // { // throw new IllegalArgumentException("Non-static DataFlow components must be JTextComponents or JButtons for MappedComponent"); // } // // this.linkedData = linkedData; // } // // public JComponent getComp() { // return comp; // } // // /** // * Cause any attached JTextComponents to refresh their displayed text via pulling from linkedData // */ // public void refresh() // { // // STATIC Components don't update or refresh // if (df==DataFlow.STATIC) // { // return; // } // else // { // setCompText(linkedData.getValue()); // } // } // // public void update() // { // // STATIC Components don't update // if (df==DataFlow.STATIC) // { // return; // } // // if (df == DataFlow.PULL) // { // setCompText(linkedData.getValue()); // } // else // { // // PUSH // linkedData.setValue(getCompText()); // } // } // // /** // * Resolves whether comp is JTextComponent or JButton and calls setText accordingly // * @param val Valid string to set on comp // */ // private void setCompText(String val) // { // if (comp instanceof JTextComponent) // { // ((JTextComponent)comp).setText(val); // } // else if (comp instanceof JButton) // { // ((JButton)comp).setText(val); // } // else // { // throw new IllegalStateException("Could not recognize what subclass JComponent comp is"); // } // } // // /** // * Resolves whether comp is JTextComponent or JButton and calls getText accordingly // * @return Text contents of comp // */ // private String getCompText() // { // if (comp instanceof JTextComponent) // { // return ((JTextComponent)comp).getText(); // } // else if (comp instanceof JButton) // { // return ((JButton)comp).getText(); // } // else // { // throw new IllegalStateException("Could not recognize what subclass JComponent comp is"); // } // } // // /** // * The nature of the DataFlow between comp and linkedData // * If STATIC, no behavior during updates // * If PULL, comp is setText to the result of linkedData.getValue() // * If PUSH, linkedData is set to comp.getText() // * @author Vigilant // * // */ // public enum DataFlow // { // PULL,PUSH,STATIC // } // } // // Path: EclipsePhaseLifePath/src/com/github/distanteye/ep_utils/wrappers/MappedComponent.java // public enum DataFlow // { // PULL,PUSH,STATIC // }
import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.UIManager; import com.github.distanteye.ep_utils.wrappers.AccessWrapper; import com.github.distanteye.ep_utils.wrappers.MappedComponent; import com.github.distanteye.ep_utils.wrappers.MappedComponent.DataFlow;
DataFlow df; // for later if (editState == EditState.FIXED) { parentUIForTextChangeListener = null; // sanity check to prevent odd behavior df = DataFlow.PULL; } else { df = DataFlow.PUSH; } // however if accessWrapper is null, df becomes static as a fallback if (accessWrapper == null) { df = DataFlow.STATIC; } // no label if no orientation if (o != null) { addLabel(x,y,labelText); } JTextField temp = addTextF(newX,newY,value,cols,parentUIForTextChangeListener); if (editState == EditState.FIXED) { temp.setEditable(false); }
// Path: EclipsePhaseLifePath/src/com/github/distanteye/ep_utils/wrappers/AccessWrapper.java // public abstract class AccessWrapper<T> { // abstract public T getValue(); // abstract public void setValue(T item); // // /** // * Reflects whether the underlying value is an Integer or not // * // * This provides an accessibility/performance bonus to some contexts // * // * @return True/False as appropriate // */ // abstract public boolean isInt(); // // } // // Path: EclipsePhaseLifePath/src/com/github/distanteye/ep_utils/wrappers/MappedComponent.java // public class MappedComponent { // private DataFlow df; // private AccessWrapper<String> linkedData; // private JComponent comp; // // // /** // * @param df Valid enum for what direction data flows between comp and linkedData // * Use DataFlow.STATIC for non-updating components // * @param linkedData AccessWrapper for interacting with the backend/character-data. This can be null if df==STATIC // * @param comp the JComponent being wrapped. If df is not STATIC, JComponent must extend JTextComponent // */ // public MappedComponent(DataFlow df, AccessWrapper<String> linkedData, JComponent comp) { // super(); // this.df = df; // this.comp = comp; // // if (df!=DataFlow.STATIC && !(comp instanceof JTextComponent || comp instanceof JButton)) // { // throw new IllegalArgumentException("Non-static DataFlow components must be JTextComponents or JButtons for MappedComponent"); // } // // this.linkedData = linkedData; // } // // public JComponent getComp() { // return comp; // } // // /** // * Cause any attached JTextComponents to refresh their displayed text via pulling from linkedData // */ // public void refresh() // { // // STATIC Components don't update or refresh // if (df==DataFlow.STATIC) // { // return; // } // else // { // setCompText(linkedData.getValue()); // } // } // // public void update() // { // // STATIC Components don't update // if (df==DataFlow.STATIC) // { // return; // } // // if (df == DataFlow.PULL) // { // setCompText(linkedData.getValue()); // } // else // { // // PUSH // linkedData.setValue(getCompText()); // } // } // // /** // * Resolves whether comp is JTextComponent or JButton and calls setText accordingly // * @param val Valid string to set on comp // */ // private void setCompText(String val) // { // if (comp instanceof JTextComponent) // { // ((JTextComponent)comp).setText(val); // } // else if (comp instanceof JButton) // { // ((JButton)comp).setText(val); // } // else // { // throw new IllegalStateException("Could not recognize what subclass JComponent comp is"); // } // } // // /** // * Resolves whether comp is JTextComponent or JButton and calls getText accordingly // * @return Text contents of comp // */ // private String getCompText() // { // if (comp instanceof JTextComponent) // { // return ((JTextComponent)comp).getText(); // } // else if (comp instanceof JButton) // { // return ((JButton)comp).getText(); // } // else // { // throw new IllegalStateException("Could not recognize what subclass JComponent comp is"); // } // } // // /** // * The nature of the DataFlow between comp and linkedData // * If STATIC, no behavior during updates // * If PULL, comp is setText to the result of linkedData.getValue() // * If PUSH, linkedData is set to comp.getText() // * @author Vigilant // * // */ // public enum DataFlow // { // PULL,PUSH,STATIC // } // } // // Path: EclipsePhaseLifePath/src/com/github/distanteye/ep_utils/wrappers/MappedComponent.java // public enum DataFlow // { // PULL,PUSH,STATIC // } // Path: EclipsePhaseLifePath/src/com/github/distanteye/ep_utils/ui/GBagPanel.java import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JTextArea; import javax.swing.JTextField; import javax.swing.UIManager; import com.github.distanteye.ep_utils.wrappers.AccessWrapper; import com.github.distanteye.ep_utils.wrappers.MappedComponent; import com.github.distanteye.ep_utils.wrappers.MappedComponent.DataFlow; DataFlow df; // for later if (editState == EditState.FIXED) { parentUIForTextChangeListener = null; // sanity check to prevent odd behavior df = DataFlow.PULL; } else { df = DataFlow.PUSH; } // however if accessWrapper is null, df becomes static as a fallback if (accessWrapper == null) { df = DataFlow.STATIC; } // no label if no orientation if (o != null) { addLabel(x,y,labelText); } JTextField temp = addTextF(newX,newY,value,cols,parentUIForTextChangeListener); if (editState == EditState.FIXED) { temp.setEditable(false); }
this.putMapped(mapName, new MappedComponent(df,accessWrapper,temp)); // TODO fix this later
DistantEye/EP_Utilities
EclipsePhaseLifePath/src/com/github/distanteye/ep_utils/commands/directives/GetVarDirective.java
// Path: EclipsePhaseLifePath/src/com/github/distanteye/ep_utils/core/CharacterEnvironment.java // public interface CharacterEnvironment { // // EpCharacter getPC(); // SecureRandom getRng(); // UI getUI(); // // /** // * Emulates a dice roll // * @param numSides upper limit of the dice roll, will return number from 1 to numSides, inclusive // * @param rollMessage Prompt/Message relevant to the roll, will display if interactive choice mode triggers // * @param forceRoll If true, is always a true random roll, if false, and if isRolling is false, prompts the user to make an interactive choice // * @return // */ // int rollDice(int numSides, String rollMessage, boolean forceRoll); // // /** // * Resets the CharacterEnvironment to its default state // */ // void reset(); // // void setHasFinished(boolean hasFinished); // // /** // * Flags the effects processing engine to notStop after finishing this current step // */ // void setNoStop(); // // /** // * Flags the effects processing engine that it needs to return control to UI after finishing // * the current step. If setNoStop was called, this will be ignored. // */ // void setEffectsNeedReturn(); // // /** // * Flags the effects processing engine to skip to the specified effects String, overriding // * default behavior when moving to the next step // * @param stepSkipTo Valid command/effects string // */ // void setStepSkipTo(String stepSkipTo); // // /** // * A "quick save" that pushes to an internal String the current character state. // * Can be loaded to character with loadBackup // */ // public void backupCharacter(); // // /** // * Takes the backup from backupCharacter and overwrites Character with it // * Will not work if backupCharacter hasn't been called yet // */ // public void loadBackup(); // // public boolean isAllRandom(); // }
import com.github.distanteye.ep_utils.core.CharacterEnvironment;
package com.github.distanteye.ep_utils.commands.directives; /** * Directive of syntax: * getVar(<name>) (returns data stored for this var) (some character fields can be accessed via {}, like _nextPath) * * @author Vigilant * */ public class GetVarDirective extends Directive { /** *Creates a Directive from the given effects string * @param input Valid formatted command effect string, this should be the full String with command name and still */ public GetVarDirective(String input) { super(input); // no advanced validation on this command is particularly possible subpartsToParams(); } /* (non-Javadoc) * @see com.github.distanteye.ep_utils.commands.directives.Directive#process(com.github.distanteye.ep_utils.containers.EpCharacter) */ @Override
// Path: EclipsePhaseLifePath/src/com/github/distanteye/ep_utils/core/CharacterEnvironment.java // public interface CharacterEnvironment { // // EpCharacter getPC(); // SecureRandom getRng(); // UI getUI(); // // /** // * Emulates a dice roll // * @param numSides upper limit of the dice roll, will return number from 1 to numSides, inclusive // * @param rollMessage Prompt/Message relevant to the roll, will display if interactive choice mode triggers // * @param forceRoll If true, is always a true random roll, if false, and if isRolling is false, prompts the user to make an interactive choice // * @return // */ // int rollDice(int numSides, String rollMessage, boolean forceRoll); // // /** // * Resets the CharacterEnvironment to its default state // */ // void reset(); // // void setHasFinished(boolean hasFinished); // // /** // * Flags the effects processing engine to notStop after finishing this current step // */ // void setNoStop(); // // /** // * Flags the effects processing engine that it needs to return control to UI after finishing // * the current step. If setNoStop was called, this will be ignored. // */ // void setEffectsNeedReturn(); // // /** // * Flags the effects processing engine to skip to the specified effects String, overriding // * default behavior when moving to the next step // * @param stepSkipTo Valid command/effects string // */ // void setStepSkipTo(String stepSkipTo); // // /** // * A "quick save" that pushes to an internal String the current character state. // * Can be loaded to character with loadBackup // */ // public void backupCharacter(); // // /** // * Takes the backup from backupCharacter and overwrites Character with it // * Will not work if backupCharacter hasn't been called yet // */ // public void loadBackup(); // // public boolean isAllRandom(); // } // Path: EclipsePhaseLifePath/src/com/github/distanteye/ep_utils/commands/directives/GetVarDirective.java import com.github.distanteye.ep_utils.core.CharacterEnvironment; package com.github.distanteye.ep_utils.commands.directives; /** * Directive of syntax: * getVar(<name>) (returns data stored for this var) (some character fields can be accessed via {}, like _nextPath) * * @author Vigilant * */ public class GetVarDirective extends Directive { /** *Creates a Directive from the given effects string * @param input Valid formatted command effect string, this should be the full String with command name and still */ public GetVarDirective(String input) { super(input); // no advanced validation on this command is particularly possible subpartsToParams(); } /* (non-Javadoc) * @see com.github.distanteye.ep_utils.commands.directives.Directive#process(com.github.distanteye.ep_utils.containers.EpCharacter) */ @Override
public String process(CharacterEnvironment env) {
DistantEye/EP_Utilities
EclipsePhaseLifePath/src/com/github/distanteye/ep_utils/commands/directives/RollDiceDirective.java
// Path: EclipsePhaseLifePath/src/com/github/distanteye/ep_utils/core/CharacterEnvironment.java // public interface CharacterEnvironment { // // EpCharacter getPC(); // SecureRandom getRng(); // UI getUI(); // // /** // * Emulates a dice roll // * @param numSides upper limit of the dice roll, will return number from 1 to numSides, inclusive // * @param rollMessage Prompt/Message relevant to the roll, will display if interactive choice mode triggers // * @param forceRoll If true, is always a true random roll, if false, and if isRolling is false, prompts the user to make an interactive choice // * @return // */ // int rollDice(int numSides, String rollMessage, boolean forceRoll); // // /** // * Resets the CharacterEnvironment to its default state // */ // void reset(); // // void setHasFinished(boolean hasFinished); // // /** // * Flags the effects processing engine to notStop after finishing this current step // */ // void setNoStop(); // // /** // * Flags the effects processing engine that it needs to return control to UI after finishing // * the current step. If setNoStop was called, this will be ignored. // */ // void setEffectsNeedReturn(); // // /** // * Flags the effects processing engine to skip to the specified effects String, overriding // * default behavior when moving to the next step // * @param stepSkipTo Valid command/effects string // */ // void setStepSkipTo(String stepSkipTo); // // /** // * A "quick save" that pushes to an internal String the current character state. // * Can be loaded to character with loadBackup // */ // public void backupCharacter(); // // /** // * Takes the backup from backupCharacter and overwrites Character with it // * Will not work if backupCharacter hasn't been called yet // */ // public void loadBackup(); // // public boolean isAllRandom(); // }
import com.github.distanteye.ep_utils.core.CharacterEnvironment;
package com.github.distanteye.ep_utils.commands.directives; /** * Directive of syntax: * rollDice(<sides>,<message>) players can choose the result of this if choose mode is on * * @author Vigilant * */ public class RollDiceDirective extends Directive { /** *Creates a Directive from the given effects string * @param input Valid formatted command effect string, this should be the full String with command name and still */ public RollDiceDirective(String input) { super(input); // validation comes during process() subpartsToParams(); } /* (non-Javadoc) * @see com.github.distanteye.ep_utils.commands.directives.Directive#process(com.github.distanteye.ep_utils.containers.EpCharacter) */ @Override
// Path: EclipsePhaseLifePath/src/com/github/distanteye/ep_utils/core/CharacterEnvironment.java // public interface CharacterEnvironment { // // EpCharacter getPC(); // SecureRandom getRng(); // UI getUI(); // // /** // * Emulates a dice roll // * @param numSides upper limit of the dice roll, will return number from 1 to numSides, inclusive // * @param rollMessage Prompt/Message relevant to the roll, will display if interactive choice mode triggers // * @param forceRoll If true, is always a true random roll, if false, and if isRolling is false, prompts the user to make an interactive choice // * @return // */ // int rollDice(int numSides, String rollMessage, boolean forceRoll); // // /** // * Resets the CharacterEnvironment to its default state // */ // void reset(); // // void setHasFinished(boolean hasFinished); // // /** // * Flags the effects processing engine to notStop after finishing this current step // */ // void setNoStop(); // // /** // * Flags the effects processing engine that it needs to return control to UI after finishing // * the current step. If setNoStop was called, this will be ignored. // */ // void setEffectsNeedReturn(); // // /** // * Flags the effects processing engine to skip to the specified effects String, overriding // * default behavior when moving to the next step // * @param stepSkipTo Valid command/effects string // */ // void setStepSkipTo(String stepSkipTo); // // /** // * A "quick save" that pushes to an internal String the current character state. // * Can be loaded to character with loadBackup // */ // public void backupCharacter(); // // /** // * Takes the backup from backupCharacter and overwrites Character with it // * Will not work if backupCharacter hasn't been called yet // */ // public void loadBackup(); // // public boolean isAllRandom(); // } // Path: EclipsePhaseLifePath/src/com/github/distanteye/ep_utils/commands/directives/RollDiceDirective.java import com.github.distanteye.ep_utils.core.CharacterEnvironment; package com.github.distanteye.ep_utils.commands.directives; /** * Directive of syntax: * rollDice(<sides>,<message>) players can choose the result of this if choose mode is on * * @author Vigilant * */ public class RollDiceDirective extends Directive { /** *Creates a Directive from the given effects string * @param input Valid formatted command effect string, this should be the full String with command name and still */ public RollDiceDirective(String input) { super(input); // validation comes during process() subpartsToParams(); } /* (non-Javadoc) * @see com.github.distanteye.ep_utils.commands.directives.Directive#process(com.github.distanteye.ep_utils.containers.EpCharacter) */ @Override
public String process(CharacterEnvironment env) {
DistantEye/EP_Utilities
EclipsePhaseLifePath/src/com/github/distanteye/ep_utils/core/DataProc.java
// Path: EclipsePhaseLifePath/src/com/github/distanteye/ep_utils/core/Package.java // public class Package implements UniqueNamedData { // private String name; // private String description; // private HashMap<Integer,String> effects; // effects for each PP value // private String motivationsList; // if any // private String specialNotes; // if any // // // /** // * @param name Name of package // * @param effects Raw mechanical effects split by package // * @param description human form description of package (can be empty) // * @param motivationsList suggested motivations for package (can be empty // * @param specialNotes special footnotes about about package // */ // public Package(String name, String description, HashMap<Integer, String> effects, // String motivationsList, String specialNotes) { // super(); // this.name = name; // this.description = description; // this.effects = effects; // this.motivationsList = motivationsList; // this.specialNotes = specialNotes; // } // // /** // * Returns the effects list for the given PP value // * @param PP positive integer matching one of the PP sets for the package // * @return Either a String or null if no such set exists // */ // public String getEffects(int PP) // { // return effects.get(PP); // } // // public String getName() { // return name; // } // // public String getMotivationsList() { // return motivationsList; // } // // // public String getSpecialNotes() { // return specialNotes; // } // // /** // * Differentiates this class from Table and such, which implement the same interface // * @return "package" // */ // public String getType() // { // return "package"; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // /** // * Returns the entire structure of effects (reference) // * // * @return HashMap structure of the effects // */ // public HashMap<Integer, String> getAllEffects() { // return effects; // } // // public void setName(String name) { // this.name = name; // } // // public void setMotivationsList(String motivationsList) { // this.motivationsList = motivationsList; // } // // public void setSpecialNotes(String specialNotes) { // this.specialNotes = specialNotes; // } // // // // }
import java.io.BufferedReader; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.HashMap; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.lang3.StringUtils; import com.github.distanteye.ep_utils.containers.*; import com.github.distanteye.ep_utils.core.Package;
if (ppValue <= 0) { throw new IllegalArgumentException("Incorrect format on effects (PP value must be > 0 ): " + line); } String effects = parts[1]; effectsList.put(ppValue, effects); i++; if (i+1 > lines.length) { line = ""; } else { line = lines[i]; } } // either this will be blank or it will contain the special notes line // because the loop replaces line with "" if it detects the end of the chunk String specialNotes = line; if (!effectsList.containsKey(1)) { throw new IllegalArgumentException("Incorrect format on package (must contain PP;1 package " + name); }
// Path: EclipsePhaseLifePath/src/com/github/distanteye/ep_utils/core/Package.java // public class Package implements UniqueNamedData { // private String name; // private String description; // private HashMap<Integer,String> effects; // effects for each PP value // private String motivationsList; // if any // private String specialNotes; // if any // // // /** // * @param name Name of package // * @param effects Raw mechanical effects split by package // * @param description human form description of package (can be empty) // * @param motivationsList suggested motivations for package (can be empty // * @param specialNotes special footnotes about about package // */ // public Package(String name, String description, HashMap<Integer, String> effects, // String motivationsList, String specialNotes) { // super(); // this.name = name; // this.description = description; // this.effects = effects; // this.motivationsList = motivationsList; // this.specialNotes = specialNotes; // } // // /** // * Returns the effects list for the given PP value // * @param PP positive integer matching one of the PP sets for the package // * @return Either a String or null if no such set exists // */ // public String getEffects(int PP) // { // return effects.get(PP); // } // // public String getName() { // return name; // } // // public String getMotivationsList() { // return motivationsList; // } // // // public String getSpecialNotes() { // return specialNotes; // } // // /** // * Differentiates this class from Table and such, which implement the same interface // * @return "package" // */ // public String getType() // { // return "package"; // } // // public String getDescription() { // return description; // } // // public void setDescription(String description) { // this.description = description; // } // // /** // * Returns the entire structure of effects (reference) // * // * @return HashMap structure of the effects // */ // public HashMap<Integer, String> getAllEffects() { // return effects; // } // // public void setName(String name) { // this.name = name; // } // // public void setMotivationsList(String motivationsList) { // this.motivationsList = motivationsList; // } // // public void setSpecialNotes(String specialNotes) { // this.specialNotes = specialNotes; // } // // // // } // Path: EclipsePhaseLifePath/src/com/github/distanteye/ep_utils/core/DataProc.java import java.io.BufferedReader; import java.io.IOException; import java.nio.charset.Charset; import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.HashMap; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.lang3.StringUtils; import com.github.distanteye.ep_utils.containers.*; import com.github.distanteye.ep_utils.core.Package; if (ppValue <= 0) { throw new IllegalArgumentException("Incorrect format on effects (PP value must be > 0 ): " + line); } String effects = parts[1]; effectsList.put(ppValue, effects); i++; if (i+1 > lines.length) { line = ""; } else { line = lines[i]; } } // either this will be blank or it will contain the special notes line // because the loop replaces line with "" if it detects the end of the chunk String specialNotes = line; if (!effectsList.containsKey(1)) { throw new IllegalArgumentException("Incorrect format on package (must contain PP;1 package " + name); }
dataStore.put(name, new Package(name,desc,effectsList,motiv,specialNotes));
DistantEye/EP_Utilities
EclipsePhaseLifePath/src/com/github/distanteye/ep_utils/commands/MsgClientCommand.java
// Path: EclipsePhaseLifePath/src/com/github/distanteye/ep_utils/core/CharacterEnvironment.java // public interface CharacterEnvironment { // // EpCharacter getPC(); // SecureRandom getRng(); // UI getUI(); // // /** // * Emulates a dice roll // * @param numSides upper limit of the dice roll, will return number from 1 to numSides, inclusive // * @param rollMessage Prompt/Message relevant to the roll, will display if interactive choice mode triggers // * @param forceRoll If true, is always a true random roll, if false, and if isRolling is false, prompts the user to make an interactive choice // * @return // */ // int rollDice(int numSides, String rollMessage, boolean forceRoll); // // /** // * Resets the CharacterEnvironment to its default state // */ // void reset(); // // void setHasFinished(boolean hasFinished); // // /** // * Flags the effects processing engine to notStop after finishing this current step // */ // void setNoStop(); // // /** // * Flags the effects processing engine that it needs to return control to UI after finishing // * the current step. If setNoStop was called, this will be ignored. // */ // void setEffectsNeedReturn(); // // /** // * Flags the effects processing engine to skip to the specified effects String, overriding // * default behavior when moving to the next step // * @param stepSkipTo Valid command/effects string // */ // void setStepSkipTo(String stepSkipTo); // // /** // * A "quick save" that pushes to an internal String the current character state. // * Can be loaded to character with loadBackup // */ // public void backupCharacter(); // // /** // * Takes the backup from backupCharacter and overwrites Character with it // * Will not work if backupCharacter hasn't been called yet // */ // public void loadBackup(); // // public boolean isAllRandom(); // }
import org.apache.commons.lang3.StringUtils; import com.github.distanteye.ep_utils.core.CharacterEnvironment;
package com.github.distanteye.ep_utils.commands; /** * Command of following syntax types: * msgClient(<message>) (says something to the UI about character changes) * * @author Vigilant * */ public class MsgClientCommand extends Command { /** *Creates a command from the given effects string * @param input Valid input string, this should be the full String with command name and () still */ public MsgClientCommand(String input) { super(input); if (subparts.length < 2 ) { throw new IllegalArgumentException("Poorly formated effect (wrong number params) " + input); } else if ( subparts[1].length() > 0) { // sometimes we have extra commas because of message text // these should be escaped, but since it's hard to enforce that from users, // auto join parts after the first index if (subparts.length > 2) { String message = subparts[1]; for (int i = 2; i < subparts.length; i++) { message += "," + subparts[i]; } this.subparts = new String[]{ subparts[0], message }; } params.put(1, subparts[1]); } else { throw new IllegalArgumentException("Poorly formated effect (params empty)" + input); } }
// Path: EclipsePhaseLifePath/src/com/github/distanteye/ep_utils/core/CharacterEnvironment.java // public interface CharacterEnvironment { // // EpCharacter getPC(); // SecureRandom getRng(); // UI getUI(); // // /** // * Emulates a dice roll // * @param numSides upper limit of the dice roll, will return number from 1 to numSides, inclusive // * @param rollMessage Prompt/Message relevant to the roll, will display if interactive choice mode triggers // * @param forceRoll If true, is always a true random roll, if false, and if isRolling is false, prompts the user to make an interactive choice // * @return // */ // int rollDice(int numSides, String rollMessage, boolean forceRoll); // // /** // * Resets the CharacterEnvironment to its default state // */ // void reset(); // // void setHasFinished(boolean hasFinished); // // /** // * Flags the effects processing engine to notStop after finishing this current step // */ // void setNoStop(); // // /** // * Flags the effects processing engine that it needs to return control to UI after finishing // * the current step. If setNoStop was called, this will be ignored. // */ // void setEffectsNeedReturn(); // // /** // * Flags the effects processing engine to skip to the specified effects String, overriding // * default behavior when moving to the next step // * @param stepSkipTo Valid command/effects string // */ // void setStepSkipTo(String stepSkipTo); // // /** // * A "quick save" that pushes to an internal String the current character state. // * Can be loaded to character with loadBackup // */ // public void backupCharacter(); // // /** // * Takes the backup from backupCharacter and overwrites Character with it // * Will not work if backupCharacter hasn't been called yet // */ // public void loadBackup(); // // public boolean isAllRandom(); // } // Path: EclipsePhaseLifePath/src/com/github/distanteye/ep_utils/commands/MsgClientCommand.java import org.apache.commons.lang3.StringUtils; import com.github.distanteye.ep_utils.core.CharacterEnvironment; package com.github.distanteye.ep_utils.commands; /** * Command of following syntax types: * msgClient(<message>) (says something to the UI about character changes) * * @author Vigilant * */ public class MsgClientCommand extends Command { /** *Creates a command from the given effects string * @param input Valid input string, this should be the full String with command name and () still */ public MsgClientCommand(String input) { super(input); if (subparts.length < 2 ) { throw new IllegalArgumentException("Poorly formated effect (wrong number params) " + input); } else if ( subparts[1].length() > 0) { // sometimes we have extra commas because of message text // these should be escaped, but since it's hard to enforce that from users, // auto join parts after the first index if (subparts.length > 2) { String message = subparts[1]; for (int i = 2; i < subparts.length; i++) { message += "," + subparts[i]; } this.subparts = new String[]{ subparts[0], message }; } params.put(1, subparts[1]); } else { throw new IllegalArgumentException("Poorly formated effect (params empty)" + input); } }
public String run(CharacterEnvironment env)
DistantEye/EP_Utilities
EclipsePhaseLifePath/src/com/github/distanteye/ep_utils/commands/directives/ConcatDirective.java
// Path: EclipsePhaseLifePath/src/com/github/distanteye/ep_utils/core/CharacterEnvironment.java // public interface CharacterEnvironment { // // EpCharacter getPC(); // SecureRandom getRng(); // UI getUI(); // // /** // * Emulates a dice roll // * @param numSides upper limit of the dice roll, will return number from 1 to numSides, inclusive // * @param rollMessage Prompt/Message relevant to the roll, will display if interactive choice mode triggers // * @param forceRoll If true, is always a true random roll, if false, and if isRolling is false, prompts the user to make an interactive choice // * @return // */ // int rollDice(int numSides, String rollMessage, boolean forceRoll); // // /** // * Resets the CharacterEnvironment to its default state // */ // void reset(); // // void setHasFinished(boolean hasFinished); // // /** // * Flags the effects processing engine to notStop after finishing this current step // */ // void setNoStop(); // // /** // * Flags the effects processing engine that it needs to return control to UI after finishing // * the current step. If setNoStop was called, this will be ignored. // */ // void setEffectsNeedReturn(); // // /** // * Flags the effects processing engine to skip to the specified effects String, overriding // * default behavior when moving to the next step // * @param stepSkipTo Valid command/effects string // */ // void setStepSkipTo(String stepSkipTo); // // /** // * A "quick save" that pushes to an internal String the current character state. // * Can be loaded to character with loadBackup // */ // public void backupCharacter(); // // /** // * Takes the backup from backupCharacter and overwrites Character with it // * Will not work if backupCharacter hasn't been called yet // */ // public void loadBackup(); // // public boolean isAllRandom(); // }
import com.github.distanteye.ep_utils.core.CharacterEnvironment;
package com.github.distanteye.ep_utils.commands.directives; /** * Directive of syntax: * concat(<value1>,<value2>) (appends value2 to the end of value1) * * @author Vigilant * */ public class ConcatDirective extends Directive { /** * Creates a Directive from the given effects string * @param input Valid input string, this should be the full String with command name and () still */ public ConcatDirective(String input) { super(input); subpartsToParams(); } /* (non-Javadoc) * @see com.github.distanteye.ep_utils.commands.directives.Directive#process(com.github.distanteye.ep_utils.containers.EpCharacter) */ @Override
// Path: EclipsePhaseLifePath/src/com/github/distanteye/ep_utils/core/CharacterEnvironment.java // public interface CharacterEnvironment { // // EpCharacter getPC(); // SecureRandom getRng(); // UI getUI(); // // /** // * Emulates a dice roll // * @param numSides upper limit of the dice roll, will return number from 1 to numSides, inclusive // * @param rollMessage Prompt/Message relevant to the roll, will display if interactive choice mode triggers // * @param forceRoll If true, is always a true random roll, if false, and if isRolling is false, prompts the user to make an interactive choice // * @return // */ // int rollDice(int numSides, String rollMessage, boolean forceRoll); // // /** // * Resets the CharacterEnvironment to its default state // */ // void reset(); // // void setHasFinished(boolean hasFinished); // // /** // * Flags the effects processing engine to notStop after finishing this current step // */ // void setNoStop(); // // /** // * Flags the effects processing engine that it needs to return control to UI after finishing // * the current step. If setNoStop was called, this will be ignored. // */ // void setEffectsNeedReturn(); // // /** // * Flags the effects processing engine to skip to the specified effects String, overriding // * default behavior when moving to the next step // * @param stepSkipTo Valid command/effects string // */ // void setStepSkipTo(String stepSkipTo); // // /** // * A "quick save" that pushes to an internal String the current character state. // * Can be loaded to character with loadBackup // */ // public void backupCharacter(); // // /** // * Takes the backup from backupCharacter and overwrites Character with it // * Will not work if backupCharacter hasn't been called yet // */ // public void loadBackup(); // // public boolean isAllRandom(); // } // Path: EclipsePhaseLifePath/src/com/github/distanteye/ep_utils/commands/directives/ConcatDirective.java import com.github.distanteye.ep_utils.core.CharacterEnvironment; package com.github.distanteye.ep_utils.commands.directives; /** * Directive of syntax: * concat(<value1>,<value2>) (appends value2 to the end of value1) * * @author Vigilant * */ public class ConcatDirective extends Directive { /** * Creates a Directive from the given effects string * @param input Valid input string, this should be the full String with command name and () still */ public ConcatDirective(String input) { super(input); subpartsToParams(); } /* (non-Javadoc) * @see com.github.distanteye.ep_utils.commands.directives.Directive#process(com.github.distanteye.ep_utils.containers.EpCharacter) */ @Override
public String process(CharacterEnvironment env) {
DistantEye/EP_Utilities
EclipsePhaseLifePath/src/com/github/distanteye/ep_utils/commands/StopCommand.java
// Path: EclipsePhaseLifePath/src/com/github/distanteye/ep_utils/core/CharacterEnvironment.java // public interface CharacterEnvironment { // // EpCharacter getPC(); // SecureRandom getRng(); // UI getUI(); // // /** // * Emulates a dice roll // * @param numSides upper limit of the dice roll, will return number from 1 to numSides, inclusive // * @param rollMessage Prompt/Message relevant to the roll, will display if interactive choice mode triggers // * @param forceRoll If true, is always a true random roll, if false, and if isRolling is false, prompts the user to make an interactive choice // * @return // */ // int rollDice(int numSides, String rollMessage, boolean forceRoll); // // /** // * Resets the CharacterEnvironment to its default state // */ // void reset(); // // void setHasFinished(boolean hasFinished); // // /** // * Flags the effects processing engine to notStop after finishing this current step // */ // void setNoStop(); // // /** // * Flags the effects processing engine that it needs to return control to UI after finishing // * the current step. If setNoStop was called, this will be ignored. // */ // void setEffectsNeedReturn(); // // /** // * Flags the effects processing engine to skip to the specified effects String, overriding // * default behavior when moving to the next step // * @param stepSkipTo Valid command/effects string // */ // void setStepSkipTo(String stepSkipTo); // // /** // * A "quick save" that pushes to an internal String the current character state. // * Can be loaded to character with loadBackup // */ // public void backupCharacter(); // // /** // * Takes the backup from backupCharacter and overwrites Character with it // * Will not work if backupCharacter hasn't been called yet // */ // public void loadBackup(); // // public boolean isAllRandom(); // }
import com.github.distanteye.ep_utils.core.CharacterEnvironment;
package com.github.distanteye.ep_utils.commands; /** * Command of following syntax types: * stop() * * @author Vigilant * */ public class StopCommand extends Command { /** *Creates a command from the given effects string * @param input Valid input string, this should be the full String with command name and () still */ public StopCommand(String input) { super(input); if (subparts.length != 1) { throw new IllegalArgumentException("Poorly formated effect (wrong number params) " + input); } }
// Path: EclipsePhaseLifePath/src/com/github/distanteye/ep_utils/core/CharacterEnvironment.java // public interface CharacterEnvironment { // // EpCharacter getPC(); // SecureRandom getRng(); // UI getUI(); // // /** // * Emulates a dice roll // * @param numSides upper limit of the dice roll, will return number from 1 to numSides, inclusive // * @param rollMessage Prompt/Message relevant to the roll, will display if interactive choice mode triggers // * @param forceRoll If true, is always a true random roll, if false, and if isRolling is false, prompts the user to make an interactive choice // * @return // */ // int rollDice(int numSides, String rollMessage, boolean forceRoll); // // /** // * Resets the CharacterEnvironment to its default state // */ // void reset(); // // void setHasFinished(boolean hasFinished); // // /** // * Flags the effects processing engine to notStop after finishing this current step // */ // void setNoStop(); // // /** // * Flags the effects processing engine that it needs to return control to UI after finishing // * the current step. If setNoStop was called, this will be ignored. // */ // void setEffectsNeedReturn(); // // /** // * Flags the effects processing engine to skip to the specified effects String, overriding // * default behavior when moving to the next step // * @param stepSkipTo Valid command/effects string // */ // void setStepSkipTo(String stepSkipTo); // // /** // * A "quick save" that pushes to an internal String the current character state. // * Can be loaded to character with loadBackup // */ // public void backupCharacter(); // // /** // * Takes the backup from backupCharacter and overwrites Character with it // * Will not work if backupCharacter hasn't been called yet // */ // public void loadBackup(); // // public boolean isAllRandom(); // } // Path: EclipsePhaseLifePath/src/com/github/distanteye/ep_utils/commands/StopCommand.java import com.github.distanteye.ep_utils.core.CharacterEnvironment; package com.github.distanteye.ep_utils.commands; /** * Command of following syntax types: * stop() * * @author Vigilant * */ public class StopCommand extends Command { /** *Creates a command from the given effects string * @param input Valid input string, this should be the full String with command name and () still */ public StopCommand(String input) { super(input); if (subparts.length != 1) { throw new IllegalArgumentException("Poorly formated effect (wrong number params) " + input); } }
public String run(CharacterEnvironment env)
BBN-D/poi-visio
src/main/java/org/apache/poi/xdgf/usermodel/XDGFPages.java
// Path: src/main/java/org/apache/poi/xdgf/exceptions/XDGFException.java // public class XDGFException { // // /** // * Creates an error message to be thrown // */ // public static POIXMLException error(String message, Object o) { // return new POIXMLException(o.toString() + ": " + message); // } // // public static POIXMLException error(String message, Object o, Throwable t) { // return new POIXMLException(o.toString() + ": " + message, t); // } // // // // // Use these to wrap error messages coming up so that we have at least // // some idea where the error was located // // // // public static POIXMLException wrap(POIXMLDocumentPart part, POIXMLException e) { // return new POIXMLException(part.getPackagePart().getPartName().toString() + ": " + e.getMessage(), // e.getCause() == null ? e : e.getCause()); // } // // public static POIXMLException wrap(String where, POIXMLException e) { // return new POIXMLException(where + ": " + e.getMessage(), // e.getCause() == null ? e : e.getCause()); // } // } // // Path: src/main/java/org/apache/poi/xdgf/xml/XDGFXMLDocumentPart.java // public class XDGFXMLDocumentPart extends POIXMLDocumentPart { // // protected XDGFDocument _document; // // public XDGFXMLDocumentPart(PackagePart part, PackageRelationship rel, XDGFDocument document) { // super(part, rel); // _document = document; // } // // }
import com.microsoft.schemas.office.visio.x2012.main.PageType; import com.microsoft.schemas.office.visio.x2012.main.PagesDocument; import com.microsoft.schemas.office.visio.x2012.main.PagesType; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.apache.poi.POIXMLDocumentPart; import org.apache.poi.POIXMLException; import org.apache.poi.openxml4j.opc.PackagePart; import org.apache.poi.openxml4j.opc.PackageRelationship; import org.apache.poi.util.Internal; import org.apache.poi.xdgf.exceptions.XDGFException; import org.apache.poi.xdgf.xml.XDGFXMLDocumentPart; import org.apache.xmlbeans.XmlException;
@Override protected void onDocumentRead() { try { try { _pagesObject = PagesDocument.Factory.parse(getPackagePart().getInputStream()).getPages(); } catch (XmlException | IOException e) { throw new POIXMLException(e); } // this iteration is ordered by page number for (PageType pageSettings: _pagesObject.getPageArray()) { String relId = pageSettings.getRel().getId(); POIXMLDocumentPart pageContentsPart = getRelationById(relId); if (pageContentsPart == null) throw new POIXMLException("PageSettings relationship for " + relId + " not found"); if (!(pageContentsPart instanceof XDGFPageContents)) throw new POIXMLException("Unexpected pages relationship for " + relId + ": " + pageContentsPart); XDGFPageContents contents = (XDGFPageContents)pageContentsPart; XDGFPage page = new XDGFPage(pageSettings, contents, _document, this); contents.onDocumentRead(); _pages.add(page); } } catch (POIXMLException e) {
// Path: src/main/java/org/apache/poi/xdgf/exceptions/XDGFException.java // public class XDGFException { // // /** // * Creates an error message to be thrown // */ // public static POIXMLException error(String message, Object o) { // return new POIXMLException(o.toString() + ": " + message); // } // // public static POIXMLException error(String message, Object o, Throwable t) { // return new POIXMLException(o.toString() + ": " + message, t); // } // // // // // Use these to wrap error messages coming up so that we have at least // // some idea where the error was located // // // // public static POIXMLException wrap(POIXMLDocumentPart part, POIXMLException e) { // return new POIXMLException(part.getPackagePart().getPartName().toString() + ": " + e.getMessage(), // e.getCause() == null ? e : e.getCause()); // } // // public static POIXMLException wrap(String where, POIXMLException e) { // return new POIXMLException(where + ": " + e.getMessage(), // e.getCause() == null ? e : e.getCause()); // } // } // // Path: src/main/java/org/apache/poi/xdgf/xml/XDGFXMLDocumentPart.java // public class XDGFXMLDocumentPart extends POIXMLDocumentPart { // // protected XDGFDocument _document; // // public XDGFXMLDocumentPart(PackagePart part, PackageRelationship rel, XDGFDocument document) { // super(part, rel); // _document = document; // } // // } // Path: src/main/java/org/apache/poi/xdgf/usermodel/XDGFPages.java import com.microsoft.schemas.office.visio.x2012.main.PageType; import com.microsoft.schemas.office.visio.x2012.main.PagesDocument; import com.microsoft.schemas.office.visio.x2012.main.PagesType; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.apache.poi.POIXMLDocumentPart; import org.apache.poi.POIXMLException; import org.apache.poi.openxml4j.opc.PackagePart; import org.apache.poi.openxml4j.opc.PackageRelationship; import org.apache.poi.util.Internal; import org.apache.poi.xdgf.exceptions.XDGFException; import org.apache.poi.xdgf.xml.XDGFXMLDocumentPart; import org.apache.xmlbeans.XmlException; @Override protected void onDocumentRead() { try { try { _pagesObject = PagesDocument.Factory.parse(getPackagePart().getInputStream()).getPages(); } catch (XmlException | IOException e) { throw new POIXMLException(e); } // this iteration is ordered by page number for (PageType pageSettings: _pagesObject.getPageArray()) { String relId = pageSettings.getRel().getId(); POIXMLDocumentPart pageContentsPart = getRelationById(relId); if (pageContentsPart == null) throw new POIXMLException("PageSettings relationship for " + relId + " not found"); if (!(pageContentsPart instanceof XDGFPageContents)) throw new POIXMLException("Unexpected pages relationship for " + relId + ": " + pageContentsPart); XDGFPageContents contents = (XDGFPageContents)pageContentsPart; XDGFPage page = new XDGFPage(pageSettings, contents, _document, this); contents.onDocumentRead(); _pages.add(page); } } catch (POIXMLException e) {
throw XDGFException.wrap(this, e);
BBN-D/poi-visio
src/main/java/org/apache/poi/xdgf/usermodel/XDGFRelation.java
// Path: src/main/java/org/apache/poi/xdgf/xml/XDGFXMLDocumentPart.java // public class XDGFXMLDocumentPart extends POIXMLDocumentPart { // // protected XDGFDocument _document; // // public XDGFXMLDocumentPart(PackagePart part, PackageRelationship rel, XDGFDocument document) { // super(part, rel); // _document = document; // } // // }
import java.util.HashMap; import java.util.Map; import org.apache.poi.POIXMLRelation; import org.apache.poi.openxml4j.opc.PackageRelationshipTypes; import org.apache.poi.xdgf.xml.XDGFXMLDocumentPart;
); public static final XDGFRelation IMAGES = new XDGFRelation( null, PackageRelationshipTypes.IMAGE_PART, null, null // XSSFPictureData.class ); public static final XDGFRelation PAGES = new XDGFRelation( "application/vnd.ms-visio.pages+xml", "http://schemas.microsoft.com/visio/2010/relationships/pages", "/visio/pages/pages.xml", XDGFPages.class ); public static final XDGFRelation PAGE = new XDGFRelation( "application/vnd.ms-visio.page+xml", "http://schemas.microsoft.com/visio/2010/relationships/page", "/visio/pages/page#.xml", XDGFPageContents.class ); public static final XDGFRelation WINDOW = new XDGFRelation( "application/vnd.ms-visio.windows+xml", "http://schemas.microsoft.com/visio/2010/relationships/windows", "/visio/windows.xml", null );
// Path: src/main/java/org/apache/poi/xdgf/xml/XDGFXMLDocumentPart.java // public class XDGFXMLDocumentPart extends POIXMLDocumentPart { // // protected XDGFDocument _document; // // public XDGFXMLDocumentPart(PackagePart part, PackageRelationship rel, XDGFDocument document) { // super(part, rel); // _document = document; // } // // } // Path: src/main/java/org/apache/poi/xdgf/usermodel/XDGFRelation.java import java.util.HashMap; import java.util.Map; import org.apache.poi.POIXMLRelation; import org.apache.poi.openxml4j.opc.PackageRelationshipTypes; import org.apache.poi.xdgf.xml.XDGFXMLDocumentPart; ); public static final XDGFRelation IMAGES = new XDGFRelation( null, PackageRelationshipTypes.IMAGE_PART, null, null // XSSFPictureData.class ); public static final XDGFRelation PAGES = new XDGFRelation( "application/vnd.ms-visio.pages+xml", "http://schemas.microsoft.com/visio/2010/relationships/pages", "/visio/pages/pages.xml", XDGFPages.class ); public static final XDGFRelation PAGE = new XDGFRelation( "application/vnd.ms-visio.page+xml", "http://schemas.microsoft.com/visio/2010/relationships/page", "/visio/pages/page#.xml", XDGFPageContents.class ); public static final XDGFRelation WINDOW = new XDGFRelation( "application/vnd.ms-visio.windows+xml", "http://schemas.microsoft.com/visio/2010/relationships/windows", "/visio/windows.xml", null );
private XDGFRelation(String type, String rel, String defaultName, Class<? extends XDGFXMLDocumentPart> cls) {
BBN-D/poi-visio
src/main/java/org/apache/poi/xdgf/usermodel/XDGFMasters.java
// Path: src/main/java/org/apache/poi/xdgf/exceptions/XDGFException.java // public class XDGFException { // // /** // * Creates an error message to be thrown // */ // public static POIXMLException error(String message, Object o) { // return new POIXMLException(o.toString() + ": " + message); // } // // public static POIXMLException error(String message, Object o, Throwable t) { // return new POIXMLException(o.toString() + ": " + message, t); // } // // // // // Use these to wrap error messages coming up so that we have at least // // some idea where the error was located // // // // public static POIXMLException wrap(POIXMLDocumentPart part, POIXMLException e) { // return new POIXMLException(part.getPackagePart().getPartName().toString() + ": " + e.getMessage(), // e.getCause() == null ? e : e.getCause()); // } // // public static POIXMLException wrap(String where, POIXMLException e) { // return new POIXMLException(where + ": " + e.getMessage(), // e.getCause() == null ? e : e.getCause()); // } // } // // Path: src/main/java/org/apache/poi/xdgf/xml/XDGFXMLDocumentPart.java // public class XDGFXMLDocumentPart extends POIXMLDocumentPart { // // protected XDGFDocument _document; // // public XDGFXMLDocumentPart(PackagePart part, PackageRelationship rel, XDGFDocument document) { // super(part, rel); // _document = document; // } // // }
import com.microsoft.schemas.office.visio.x2012.main.MasterType; import com.microsoft.schemas.office.visio.x2012.main.MastersDocument; import com.microsoft.schemas.office.visio.x2012.main.MastersType; import java.io.IOException; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map; import org.apache.poi.POIXMLDocumentPart; import org.apache.poi.POIXMLException; import org.apache.poi.openxml4j.opc.PackagePart; import org.apache.poi.openxml4j.opc.PackageRelationship; import org.apache.poi.util.Internal; import org.apache.poi.xdgf.exceptions.XDGFException; import org.apache.poi.xdgf.xml.XDGFXMLDocumentPart; import org.apache.xmlbeans.XmlException;
try { _mastersObject = MastersDocument.Factory.parse(getPackagePart().getInputStream()).getMasters(); } catch (XmlException | IOException e) { throw new POIXMLException(e); } Map<String, MasterType> masterSettings = new HashMap<>(); for (MasterType master: _mastersObject.getMasterArray()) { masterSettings.put(master.getRel().getId(), master); } // create the masters for (POIXMLDocumentPart part: getRelations()) { String relId = part.getPackageRelationship().getId(); MasterType settings = masterSettings.get(relId); if (settings == null) throw new POIXMLException("Master relationship for " + relId + " not found"); if (!(part instanceof XDGFMasterContents)) throw new POIXMLException("Unexpected masters relationship for " + relId + ": " + part); XDGFMasterContents contents = (XDGFMasterContents)part; contents.onDocumentRead(); XDGFMaster master = new XDGFMaster(settings, contents, _document); _masters.put(master.getID(), master); } } catch (POIXMLException e) {
// Path: src/main/java/org/apache/poi/xdgf/exceptions/XDGFException.java // public class XDGFException { // // /** // * Creates an error message to be thrown // */ // public static POIXMLException error(String message, Object o) { // return new POIXMLException(o.toString() + ": " + message); // } // // public static POIXMLException error(String message, Object o, Throwable t) { // return new POIXMLException(o.toString() + ": " + message, t); // } // // // // // Use these to wrap error messages coming up so that we have at least // // some idea where the error was located // // // // public static POIXMLException wrap(POIXMLDocumentPart part, POIXMLException e) { // return new POIXMLException(part.getPackagePart().getPartName().toString() + ": " + e.getMessage(), // e.getCause() == null ? e : e.getCause()); // } // // public static POIXMLException wrap(String where, POIXMLException e) { // return new POIXMLException(where + ": " + e.getMessage(), // e.getCause() == null ? e : e.getCause()); // } // } // // Path: src/main/java/org/apache/poi/xdgf/xml/XDGFXMLDocumentPart.java // public class XDGFXMLDocumentPart extends POIXMLDocumentPart { // // protected XDGFDocument _document; // // public XDGFXMLDocumentPart(PackagePart part, PackageRelationship rel, XDGFDocument document) { // super(part, rel); // _document = document; // } // // } // Path: src/main/java/org/apache/poi/xdgf/usermodel/XDGFMasters.java import com.microsoft.schemas.office.visio.x2012.main.MasterType; import com.microsoft.schemas.office.visio.x2012.main.MastersDocument; import com.microsoft.schemas.office.visio.x2012.main.MastersType; import java.io.IOException; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map; import org.apache.poi.POIXMLDocumentPart; import org.apache.poi.POIXMLException; import org.apache.poi.openxml4j.opc.PackagePart; import org.apache.poi.openxml4j.opc.PackageRelationship; import org.apache.poi.util.Internal; import org.apache.poi.xdgf.exceptions.XDGFException; import org.apache.poi.xdgf.xml.XDGFXMLDocumentPart; import org.apache.xmlbeans.XmlException; try { _mastersObject = MastersDocument.Factory.parse(getPackagePart().getInputStream()).getMasters(); } catch (XmlException | IOException e) { throw new POIXMLException(e); } Map<String, MasterType> masterSettings = new HashMap<>(); for (MasterType master: _mastersObject.getMasterArray()) { masterSettings.put(master.getRel().getId(), master); } // create the masters for (POIXMLDocumentPart part: getRelations()) { String relId = part.getPackageRelationship().getId(); MasterType settings = masterSettings.get(relId); if (settings == null) throw new POIXMLException("Master relationship for " + relId + " not found"); if (!(part instanceof XDGFMasterContents)) throw new POIXMLException("Unexpected masters relationship for " + relId + ": " + part); XDGFMasterContents contents = (XDGFMasterContents)part; contents.onDocumentRead(); XDGFMaster master = new XDGFMaster(settings, contents, _document); _masters.put(master.getID(), master); } } catch (POIXMLException e) {
throw XDGFException.wrap(this, e);
BBN-D/poi-visio
src/main/java/org/apache/poi/xdgf/usermodel/XDGFMasterContents.java
// Path: src/main/java/org/apache/poi/xdgf/exceptions/XDGFException.java // public class XDGFException { // // /** // * Creates an error message to be thrown // */ // public static POIXMLException error(String message, Object o) { // return new POIXMLException(o.toString() + ": " + message); // } // // public static POIXMLException error(String message, Object o, Throwable t) { // return new POIXMLException(o.toString() + ": " + message, t); // } // // // // // Use these to wrap error messages coming up so that we have at least // // some idea where the error was located // // // // public static POIXMLException wrap(POIXMLDocumentPart part, POIXMLException e) { // return new POIXMLException(part.getPackagePart().getPartName().toString() + ": " + e.getMessage(), // e.getCause() == null ? e : e.getCause()); // } // // public static POIXMLException wrap(String where, POIXMLException e) { // return new POIXMLException(where + ": " + e.getMessage(), // e.getCause() == null ? e : e.getCause()); // } // }
import java.io.IOException; import org.apache.poi.POIXMLException; import org.apache.poi.openxml4j.opc.PackagePart; import org.apache.poi.openxml4j.opc.PackageRelationship; import org.apache.poi.xdgf.exceptions.XDGFException; import org.apache.xmlbeans.XmlException; import com.microsoft.schemas.office.visio.x2012.main.MasterContentsDocument;
/* * Copyright (c) 2015 Raytheon BBN Technologies Corp * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.poi.xdgf.usermodel; public class XDGFMasterContents extends XDGFBaseContents { private XDGFMaster _master; public XDGFMasterContents(PackagePart part, PackageRelationship rel, XDGFDocument document) { super(part, rel, document); } @Override protected void onDocumentRead() { try { try { _pageContents = MasterContentsDocument.Factory.parse(getPackagePart().getInputStream()).getMasterContents(); } catch (XmlException | IOException e) { throw new POIXMLException(e); } super.onDocumentRead(); } catch (POIXMLException e) {
// Path: src/main/java/org/apache/poi/xdgf/exceptions/XDGFException.java // public class XDGFException { // // /** // * Creates an error message to be thrown // */ // public static POIXMLException error(String message, Object o) { // return new POIXMLException(o.toString() + ": " + message); // } // // public static POIXMLException error(String message, Object o, Throwable t) { // return new POIXMLException(o.toString() + ": " + message, t); // } // // // // // Use these to wrap error messages coming up so that we have at least // // some idea where the error was located // // // // public static POIXMLException wrap(POIXMLDocumentPart part, POIXMLException e) { // return new POIXMLException(part.getPackagePart().getPartName().toString() + ": " + e.getMessage(), // e.getCause() == null ? e : e.getCause()); // } // // public static POIXMLException wrap(String where, POIXMLException e) { // return new POIXMLException(where + ": " + e.getMessage(), // e.getCause() == null ? e : e.getCause()); // } // } // Path: src/main/java/org/apache/poi/xdgf/usermodel/XDGFMasterContents.java import java.io.IOException; import org.apache.poi.POIXMLException; import org.apache.poi.openxml4j.opc.PackagePart; import org.apache.poi.openxml4j.opc.PackageRelationship; import org.apache.poi.xdgf.exceptions.XDGFException; import org.apache.xmlbeans.XmlException; import com.microsoft.schemas.office.visio.x2012.main.MasterContentsDocument; /* * Copyright (c) 2015 Raytheon BBN Technologies Corp * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.poi.xdgf.usermodel; public class XDGFMasterContents extends XDGFBaseContents { private XDGFMaster _master; public XDGFMasterContents(PackagePart part, PackageRelationship rel, XDGFDocument document) { super(part, rel, document); } @Override protected void onDocumentRead() { try { try { _pageContents = MasterContentsDocument.Factory.parse(getPackagePart().getInputStream()).getMasterContents(); } catch (XmlException | IOException e) { throw new POIXMLException(e); } super.onDocumentRead(); } catch (POIXMLException e) {
throw XDGFException.wrap(this, e);
BBN-D/poi-visio
src/main/java/org/apache/poi/xdgf/usermodel/XDGFPage.java
// Path: src/main/java/org/apache/poi/xdgf/geom/Dimension2dDouble.java // public class Dimension2dDouble extends Dimension2D { // // double width; // double height; // // public Dimension2dDouble() { // width = 0d; // height = 0d; // } // // public Dimension2dDouble(double width, double height) { // this.width = width; // this.height = height; // } // // @Override // public double getWidth() { // return width; // } // // @Override // public double getHeight() { // return height; // } // // @Override // public void setSize(double width, double height) { // this.width = width; // this.height = height; // } // // @Override // public boolean equals(Object obj) { // if (obj instanceof Dimension2dDouble) { // Dimension2dDouble other = (Dimension2dDouble)obj; // return width == other.width && height == other.height; // } // // return false; // } // // @Override // public int hashCode() { // double sum = width + height; // return (int)Math.ceil(sum * (sum + 1)/2 + width); // } // // @Override // public String toString() { // return "Dimension2dDouble[" + width + ", " + height + "]"; // } // }
import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import org.apache.poi.POIXMLException; import org.apache.poi.util.Internal; import org.apache.poi.xdgf.geom.Dimension2dDouble; import com.microsoft.schemas.office.visio.x2012.main.PageType;
if (page.isSetPageSheet()) _pageSheet = new XDGFPageSheet(page.getPageSheet(), document); } @Internal PageType getXmlObject() { return _page; } public long getID() { return _page.getID(); } public String getName() { return _page.getName(); } public XDGFPageContents getContent() { return _content; } public XDGFSheet getPageSheet() { return _pageSheet; } public long getPageNumber() { return _pages.getPageList().indexOf(this) + 1; } // height/width of page
// Path: src/main/java/org/apache/poi/xdgf/geom/Dimension2dDouble.java // public class Dimension2dDouble extends Dimension2D { // // double width; // double height; // // public Dimension2dDouble() { // width = 0d; // height = 0d; // } // // public Dimension2dDouble(double width, double height) { // this.width = width; // this.height = height; // } // // @Override // public double getWidth() { // return width; // } // // @Override // public double getHeight() { // return height; // } // // @Override // public void setSize(double width, double height) { // this.width = width; // this.height = height; // } // // @Override // public boolean equals(Object obj) { // if (obj instanceof Dimension2dDouble) { // Dimension2dDouble other = (Dimension2dDouble)obj; // return width == other.width && height == other.height; // } // // return false; // } // // @Override // public int hashCode() { // double sum = width + height; // return (int)Math.ceil(sum * (sum + 1)/2 + width); // } // // @Override // public String toString() { // return "Dimension2dDouble[" + width + ", " + height + "]"; // } // } // Path: src/main/java/org/apache/poi/xdgf/usermodel/XDGFPage.java import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import org.apache.poi.POIXMLException; import org.apache.poi.util.Internal; import org.apache.poi.xdgf.geom.Dimension2dDouble; import com.microsoft.schemas.office.visio.x2012.main.PageType; if (page.isSetPageSheet()) _pageSheet = new XDGFPageSheet(page.getPageSheet(), document); } @Internal PageType getXmlObject() { return _page; } public long getID() { return _page.getID(); } public String getName() { return _page.getName(); } public XDGFPageContents getContent() { return _content; } public XDGFSheet getPageSheet() { return _pageSheet; } public long getPageNumber() { return _pages.getPageList().indexOf(this) + 1; } // height/width of page
public Dimension2dDouble getPageSize() {
BBN-D/poi-visio
src/main/java/org/apache/poi/xdgf/usermodel/XDGFPageContents.java
// Path: src/main/java/org/apache/poi/xdgf/exceptions/XDGFException.java // public class XDGFException { // // /** // * Creates an error message to be thrown // */ // public static POIXMLException error(String message, Object o) { // return new POIXMLException(o.toString() + ": " + message); // } // // public static POIXMLException error(String message, Object o, Throwable t) { // return new POIXMLException(o.toString() + ": " + message, t); // } // // // // // Use these to wrap error messages coming up so that we have at least // // some idea where the error was located // // // // public static POIXMLException wrap(POIXMLDocumentPart part, POIXMLException e) { // return new POIXMLException(part.getPackagePart().getPartName().toString() + ": " + e.getMessage(), // e.getCause() == null ? e : e.getCause()); // } // // public static POIXMLException wrap(String where, POIXMLException e) { // return new POIXMLException(where + ": " + e.getMessage(), // e.getCause() == null ? e : e.getCause()); // } // }
import java.io.IOException; import java.util.HashMap; import java.util.Map; import org.apache.poi.POIXMLDocumentPart; import org.apache.poi.POIXMLException; import org.apache.poi.openxml4j.opc.PackagePart; import org.apache.poi.openxml4j.opc.PackageRelationship; import org.apache.poi.xdgf.exceptions.XDGFException; import org.apache.xmlbeans.XmlException; import com.microsoft.schemas.office.visio.x2012.main.PageContentsDocument;
/* * Copyright (c) 2015 Raytheon BBN Technologies Corp * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.poi.xdgf.usermodel; public class XDGFPageContents extends XDGFBaseContents { Map<Long, XDGFMaster> _masters = new HashMap<>(); XDGFPage _page; public XDGFPageContents(PackagePart part, PackageRelationship rel, XDGFDocument document) { super(part, rel, document); } @Override protected void onDocumentRead() { try { try { _pageContents = PageContentsDocument.Factory.parse(getPackagePart().getInputStream()).getPageContents(); } catch (XmlException | IOException e) { throw new POIXMLException(e); } for (POIXMLDocumentPart part: getRelations()) { if (!(part instanceof XDGFMasterContents)) continue; //throw new POIXMLException("Unexpected page relation: " + part); XDGFMaster master = ((XDGFMasterContents)part).getMaster(); _masters.put(master.getID(), master); } super.onDocumentRead(); for (XDGFShape shape: _shapes.values()) { if (shape.isTopmost()) shape.setupMaster(this, null); } } catch (POIXMLException e) {
// Path: src/main/java/org/apache/poi/xdgf/exceptions/XDGFException.java // public class XDGFException { // // /** // * Creates an error message to be thrown // */ // public static POIXMLException error(String message, Object o) { // return new POIXMLException(o.toString() + ": " + message); // } // // public static POIXMLException error(String message, Object o, Throwable t) { // return new POIXMLException(o.toString() + ": " + message, t); // } // // // // // Use these to wrap error messages coming up so that we have at least // // some idea where the error was located // // // // public static POIXMLException wrap(POIXMLDocumentPart part, POIXMLException e) { // return new POIXMLException(part.getPackagePart().getPartName().toString() + ": " + e.getMessage(), // e.getCause() == null ? e : e.getCause()); // } // // public static POIXMLException wrap(String where, POIXMLException e) { // return new POIXMLException(where + ": " + e.getMessage(), // e.getCause() == null ? e : e.getCause()); // } // } // Path: src/main/java/org/apache/poi/xdgf/usermodel/XDGFPageContents.java import java.io.IOException; import java.util.HashMap; import java.util.Map; import org.apache.poi.POIXMLDocumentPart; import org.apache.poi.POIXMLException; import org.apache.poi.openxml4j.opc.PackagePart; import org.apache.poi.openxml4j.opc.PackageRelationship; import org.apache.poi.xdgf.exceptions.XDGFException; import org.apache.xmlbeans.XmlException; import com.microsoft.schemas.office.visio.x2012.main.PageContentsDocument; /* * Copyright (c) 2015 Raytheon BBN Technologies Corp * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.poi.xdgf.usermodel; public class XDGFPageContents extends XDGFBaseContents { Map<Long, XDGFMaster> _masters = new HashMap<>(); XDGFPage _page; public XDGFPageContents(PackagePart part, PackageRelationship rel, XDGFDocument document) { super(part, rel, document); } @Override protected void onDocumentRead() { try { try { _pageContents = PageContentsDocument.Factory.parse(getPackagePart().getInputStream()).getPageContents(); } catch (XmlException | IOException e) { throw new POIXMLException(e); } for (POIXMLDocumentPart part: getRelations()) { if (!(part instanceof XDGFMasterContents)) continue; //throw new POIXMLException("Unexpected page relation: " + part); XDGFMaster master = ((XDGFMasterContents)part).getMaster(); _masters.put(master.getID(), master); } super.onDocumentRead(); for (XDGFShape shape: _shapes.values()) { if (shape.isTopmost()) shape.setupMaster(this, null); } } catch (POIXMLException e) {
throw XDGFException.wrap(this, e);
porunov/acme_client
src/main/java/com/jblur/acme_client/CommandExecutor.java
// Path: src/main/java/com/jblur/acme_client/command/ACMECommand.java // public abstract class ACMECommand implements Command { // private static final Logger LOG = LoggerFactory.getLogger(ACMECommand.class); // public boolean error = false; // protected JsonObject result = new JsonObject(); // private Parameters parameters; // private Session session; // private Gson gson = new Gson(); // // public ACMECommand(Parameters parameters) { // this.parameters = parameters; // this.session = new Session(this.parameters.getAcmeServerUrl()); // } // // public Parameters getParameters() { // return this.parameters; // } // // protected Session getSession() { // return this.session; // } // // public Gson getGson() { // return this.gson; // } // // public String getResult() { // return gson.toJson(result); // } // // private void preExecution() { // error = false; // result = new JsonObject(); // } // // @Override // public void execute() { // preExecution(); // commandExecution(); // postExecution(); // } // // private void postExecution() { // result.add("status", getGson().toJsonTree((error) ? "error" : "ok")); // } // // public abstract void commandExecution(); // // } // // Path: src/main/java/com/jblur/acme_client/command/AccountKeyNotFoundException.java // public class AccountKeyNotFoundException extends Exception { // // public AccountKeyNotFoundException(Throwable throwable) { // super(throwable); // } // } // // Path: src/main/java/com/jblur/acme_client/manager/AccountManager.java // public class AccountManager { // // private static final Logger LOG = LoggerFactory.getLogger(Application.class); // // private Account account; // private Login login; // // public AccountManager(Login login) { // this.account = login.getAccount(); // this.login = login; // } // // public AccountManager(KeyPair keyPair, Session session, boolean agreeToTermsOfService) // throws AcmeException { // AccountBuilder accountBuilder = new AccountBuilder().useKeyPair(keyPair); // if(agreeToTermsOfService){ // accountBuilder = accountBuilder.agreeToTermsOfService(); // } // this.login = accountBuilder.createLogin(session); // this.account = this.login.getAccount(); // } // // public AccountManager(KeyPair keyPair, Session session, String keyIdentifier, // SecretKey macKey, boolean agreeToTermsOfService) // throws AcmeException { // AccountBuilder accountBuilder = new AccountBuilder() // .withKeyIdentifier(keyIdentifier, macKey).useKeyPair(keyPair); // if(agreeToTermsOfService){ // accountBuilder = accountBuilder.agreeToTermsOfService(); // } // this.login = accountBuilder.createLogin(session); // this.account = this.login.getAccount(); // } // // public AccountManager(KeyPair keyPair, Session session, String keyIdentifier, // String macKey, boolean agreeToTermsOfService) // throws AcmeException { // AccountBuilder accountBuilder = new AccountBuilder() // .withKeyIdentifier(keyIdentifier, macKey).useKeyPair(keyPair); // if(agreeToTermsOfService){ // accountBuilder = accountBuilder.agreeToTermsOfService(); // } // this.login = accountBuilder.createLogin(session); // this.account = this.login.getAccount(); // } // // public AccountManager(KeyPair keyPair, Session session, URL accountLocationUrl) { // this.login = session.login(accountLocationUrl, keyPair); // this.account = this.login.getAccount(); // } // // public Account getAccount() { // return this.account; // } // // public Login getLogin(){ // return this.login; // } // // public void addContact(URI contactURI) throws AcmeException { // this.account.modify() // .addContact(contactURI) // .commit(); // } // // public void changeAccountKeyPair(KeyPair keyPair) throws AcmeException { // this.account.changeKey(keyPair); // } // // public void deactivateAccount() throws AcmeException { // try { // this.account.deactivate(); // } catch (AcmeException e) { // if (!e.getMessage().equals("HTTP 202: Accepted")) { // throw e; // } // } // } // // }
import com.google.gson.Gson; import com.google.gson.JsonObject; import com.jblur.acme_client.command.ACMECommand; import com.jblur.acme_client.command.AccountKeyNotFoundException; import com.jblur.acme_client.command.certificate.*; import com.jblur.acme_client.command.registration.*; import com.jblur.acme_client.manager.AccountManager; import org.shredzone.acme4j.exception.AcmeException; import org.shredzone.acme4j.exception.AcmeUserActionRequiredException; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
package com.jblur.acme_client; public class CommandExecutor { private static final Logger LOG = LoggerFactory.getLogger(CommandExecutor.class); private Parameters parameters; public static final String RESULT_ERROR; static { Gson gson = new Gson(); JsonObject jsonObject = new JsonObject(); jsonObject.add("status", gson.toJsonTree("error")); RESULT_ERROR = gson.toJson(jsonObject); } private String result; public CommandExecutor(Parameters parameters) { this.parameters = parameters; } public void execute() {
// Path: src/main/java/com/jblur/acme_client/command/ACMECommand.java // public abstract class ACMECommand implements Command { // private static final Logger LOG = LoggerFactory.getLogger(ACMECommand.class); // public boolean error = false; // protected JsonObject result = new JsonObject(); // private Parameters parameters; // private Session session; // private Gson gson = new Gson(); // // public ACMECommand(Parameters parameters) { // this.parameters = parameters; // this.session = new Session(this.parameters.getAcmeServerUrl()); // } // // public Parameters getParameters() { // return this.parameters; // } // // protected Session getSession() { // return this.session; // } // // public Gson getGson() { // return this.gson; // } // // public String getResult() { // return gson.toJson(result); // } // // private void preExecution() { // error = false; // result = new JsonObject(); // } // // @Override // public void execute() { // preExecution(); // commandExecution(); // postExecution(); // } // // private void postExecution() { // result.add("status", getGson().toJsonTree((error) ? "error" : "ok")); // } // // public abstract void commandExecution(); // // } // // Path: src/main/java/com/jblur/acme_client/command/AccountKeyNotFoundException.java // public class AccountKeyNotFoundException extends Exception { // // public AccountKeyNotFoundException(Throwable throwable) { // super(throwable); // } // } // // Path: src/main/java/com/jblur/acme_client/manager/AccountManager.java // public class AccountManager { // // private static final Logger LOG = LoggerFactory.getLogger(Application.class); // // private Account account; // private Login login; // // public AccountManager(Login login) { // this.account = login.getAccount(); // this.login = login; // } // // public AccountManager(KeyPair keyPair, Session session, boolean agreeToTermsOfService) // throws AcmeException { // AccountBuilder accountBuilder = new AccountBuilder().useKeyPair(keyPair); // if(agreeToTermsOfService){ // accountBuilder = accountBuilder.agreeToTermsOfService(); // } // this.login = accountBuilder.createLogin(session); // this.account = this.login.getAccount(); // } // // public AccountManager(KeyPair keyPair, Session session, String keyIdentifier, // SecretKey macKey, boolean agreeToTermsOfService) // throws AcmeException { // AccountBuilder accountBuilder = new AccountBuilder() // .withKeyIdentifier(keyIdentifier, macKey).useKeyPair(keyPair); // if(agreeToTermsOfService){ // accountBuilder = accountBuilder.agreeToTermsOfService(); // } // this.login = accountBuilder.createLogin(session); // this.account = this.login.getAccount(); // } // // public AccountManager(KeyPair keyPair, Session session, String keyIdentifier, // String macKey, boolean agreeToTermsOfService) // throws AcmeException { // AccountBuilder accountBuilder = new AccountBuilder() // .withKeyIdentifier(keyIdentifier, macKey).useKeyPair(keyPair); // if(agreeToTermsOfService){ // accountBuilder = accountBuilder.agreeToTermsOfService(); // } // this.login = accountBuilder.createLogin(session); // this.account = this.login.getAccount(); // } // // public AccountManager(KeyPair keyPair, Session session, URL accountLocationUrl) { // this.login = session.login(accountLocationUrl, keyPair); // this.account = this.login.getAccount(); // } // // public Account getAccount() { // return this.account; // } // // public Login getLogin(){ // return this.login; // } // // public void addContact(URI contactURI) throws AcmeException { // this.account.modify() // .addContact(contactURI) // .commit(); // } // // public void changeAccountKeyPair(KeyPair keyPair) throws AcmeException { // this.account.changeKey(keyPair); // } // // public void deactivateAccount() throws AcmeException { // try { // this.account.deactivate(); // } catch (AcmeException e) { // if (!e.getMessage().equals("HTTP 202: Accepted")) { // throw e; // } // } // } // // } // Path: src/main/java/com/jblur/acme_client/CommandExecutor.java import com.google.gson.Gson; import com.google.gson.JsonObject; import com.jblur.acme_client.command.ACMECommand; import com.jblur.acme_client.command.AccountKeyNotFoundException; import com.jblur.acme_client.command.certificate.*; import com.jblur.acme_client.command.registration.*; import com.jblur.acme_client.manager.AccountManager; import org.shredzone.acme4j.exception.AcmeException; import org.shredzone.acme4j.exception.AcmeUserActionRequiredException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; package com.jblur.acme_client; public class CommandExecutor { private static final Logger LOG = LoggerFactory.getLogger(CommandExecutor.class); private Parameters parameters; public static final String RESULT_ERROR; static { Gson gson = new Gson(); JsonObject jsonObject = new JsonObject(); jsonObject.add("status", gson.toJsonTree("error")); RESULT_ERROR = gson.toJson(jsonObject); } private String result; public CommandExecutor(Parameters parameters) { this.parameters = parameters; } public void execute() {
AccountManager accountManager = null;
porunov/acme_client
src/main/java/com/jblur/acme_client/CommandExecutor.java
// Path: src/main/java/com/jblur/acme_client/command/ACMECommand.java // public abstract class ACMECommand implements Command { // private static final Logger LOG = LoggerFactory.getLogger(ACMECommand.class); // public boolean error = false; // protected JsonObject result = new JsonObject(); // private Parameters parameters; // private Session session; // private Gson gson = new Gson(); // // public ACMECommand(Parameters parameters) { // this.parameters = parameters; // this.session = new Session(this.parameters.getAcmeServerUrl()); // } // // public Parameters getParameters() { // return this.parameters; // } // // protected Session getSession() { // return this.session; // } // // public Gson getGson() { // return this.gson; // } // // public String getResult() { // return gson.toJson(result); // } // // private void preExecution() { // error = false; // result = new JsonObject(); // } // // @Override // public void execute() { // preExecution(); // commandExecution(); // postExecution(); // } // // private void postExecution() { // result.add("status", getGson().toJsonTree((error) ? "error" : "ok")); // } // // public abstract void commandExecution(); // // } // // Path: src/main/java/com/jblur/acme_client/command/AccountKeyNotFoundException.java // public class AccountKeyNotFoundException extends Exception { // // public AccountKeyNotFoundException(Throwable throwable) { // super(throwable); // } // } // // Path: src/main/java/com/jblur/acme_client/manager/AccountManager.java // public class AccountManager { // // private static final Logger LOG = LoggerFactory.getLogger(Application.class); // // private Account account; // private Login login; // // public AccountManager(Login login) { // this.account = login.getAccount(); // this.login = login; // } // // public AccountManager(KeyPair keyPair, Session session, boolean agreeToTermsOfService) // throws AcmeException { // AccountBuilder accountBuilder = new AccountBuilder().useKeyPair(keyPair); // if(agreeToTermsOfService){ // accountBuilder = accountBuilder.agreeToTermsOfService(); // } // this.login = accountBuilder.createLogin(session); // this.account = this.login.getAccount(); // } // // public AccountManager(KeyPair keyPair, Session session, String keyIdentifier, // SecretKey macKey, boolean agreeToTermsOfService) // throws AcmeException { // AccountBuilder accountBuilder = new AccountBuilder() // .withKeyIdentifier(keyIdentifier, macKey).useKeyPair(keyPair); // if(agreeToTermsOfService){ // accountBuilder = accountBuilder.agreeToTermsOfService(); // } // this.login = accountBuilder.createLogin(session); // this.account = this.login.getAccount(); // } // // public AccountManager(KeyPair keyPair, Session session, String keyIdentifier, // String macKey, boolean agreeToTermsOfService) // throws AcmeException { // AccountBuilder accountBuilder = new AccountBuilder() // .withKeyIdentifier(keyIdentifier, macKey).useKeyPair(keyPair); // if(agreeToTermsOfService){ // accountBuilder = accountBuilder.agreeToTermsOfService(); // } // this.login = accountBuilder.createLogin(session); // this.account = this.login.getAccount(); // } // // public AccountManager(KeyPair keyPair, Session session, URL accountLocationUrl) { // this.login = session.login(accountLocationUrl, keyPair); // this.account = this.login.getAccount(); // } // // public Account getAccount() { // return this.account; // } // // public Login getLogin(){ // return this.login; // } // // public void addContact(URI contactURI) throws AcmeException { // this.account.modify() // .addContact(contactURI) // .commit(); // } // // public void changeAccountKeyPair(KeyPair keyPair) throws AcmeException { // this.account.changeKey(keyPair); // } // // public void deactivateAccount() throws AcmeException { // try { // this.account.deactivate(); // } catch (AcmeException e) { // if (!e.getMessage().equals("HTTP 202: Accepted")) { // throw e; // } // } // } // // }
import com.google.gson.Gson; import com.google.gson.JsonObject; import com.jblur.acme_client.command.ACMECommand; import com.jblur.acme_client.command.AccountKeyNotFoundException; import com.jblur.acme_client.command.certificate.*; import com.jblur.acme_client.command.registration.*; import com.jblur.acme_client.manager.AccountManager; import org.shredzone.acme4j.exception.AcmeException; import org.shredzone.acme4j.exception.AcmeUserActionRequiredException; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
LOG.error("Manual action required. Please visit url with instructions: "+e.getInstance().toString(), e); if(e.getTermsOfServiceUri()!=null){ LOG.error("You should agree to terms of service: "+e.getTermsOfServiceUri()); } result=RESULT_ERROR; } catch (AcmeException e) { e.printStackTrace(); result=RESULT_ERROR; } System.out.println(result); } private AccountManager getAccountManager() { AccountManager accountManager = null; try { RegistrationCommand registrationCommand = new RegistrationCommand(parameters); result = executeACMECommand(registrationCommand); accountManager = registrationCommand.getAccountManager(); if (accountManager == null) { LOG.error("Cannot get account information."); } } catch (AccountKeyNotFoundException e) { LOG.error("Account key not found.", e); } catch (AcmeException e) { LOG.error("Cannot be authorized.", e); } return accountManager; }
// Path: src/main/java/com/jblur/acme_client/command/ACMECommand.java // public abstract class ACMECommand implements Command { // private static final Logger LOG = LoggerFactory.getLogger(ACMECommand.class); // public boolean error = false; // protected JsonObject result = new JsonObject(); // private Parameters parameters; // private Session session; // private Gson gson = new Gson(); // // public ACMECommand(Parameters parameters) { // this.parameters = parameters; // this.session = new Session(this.parameters.getAcmeServerUrl()); // } // // public Parameters getParameters() { // return this.parameters; // } // // protected Session getSession() { // return this.session; // } // // public Gson getGson() { // return this.gson; // } // // public String getResult() { // return gson.toJson(result); // } // // private void preExecution() { // error = false; // result = new JsonObject(); // } // // @Override // public void execute() { // preExecution(); // commandExecution(); // postExecution(); // } // // private void postExecution() { // result.add("status", getGson().toJsonTree((error) ? "error" : "ok")); // } // // public abstract void commandExecution(); // // } // // Path: src/main/java/com/jblur/acme_client/command/AccountKeyNotFoundException.java // public class AccountKeyNotFoundException extends Exception { // // public AccountKeyNotFoundException(Throwable throwable) { // super(throwable); // } // } // // Path: src/main/java/com/jblur/acme_client/manager/AccountManager.java // public class AccountManager { // // private static final Logger LOG = LoggerFactory.getLogger(Application.class); // // private Account account; // private Login login; // // public AccountManager(Login login) { // this.account = login.getAccount(); // this.login = login; // } // // public AccountManager(KeyPair keyPair, Session session, boolean agreeToTermsOfService) // throws AcmeException { // AccountBuilder accountBuilder = new AccountBuilder().useKeyPair(keyPair); // if(agreeToTermsOfService){ // accountBuilder = accountBuilder.agreeToTermsOfService(); // } // this.login = accountBuilder.createLogin(session); // this.account = this.login.getAccount(); // } // // public AccountManager(KeyPair keyPair, Session session, String keyIdentifier, // SecretKey macKey, boolean agreeToTermsOfService) // throws AcmeException { // AccountBuilder accountBuilder = new AccountBuilder() // .withKeyIdentifier(keyIdentifier, macKey).useKeyPair(keyPair); // if(agreeToTermsOfService){ // accountBuilder = accountBuilder.agreeToTermsOfService(); // } // this.login = accountBuilder.createLogin(session); // this.account = this.login.getAccount(); // } // // public AccountManager(KeyPair keyPair, Session session, String keyIdentifier, // String macKey, boolean agreeToTermsOfService) // throws AcmeException { // AccountBuilder accountBuilder = new AccountBuilder() // .withKeyIdentifier(keyIdentifier, macKey).useKeyPair(keyPair); // if(agreeToTermsOfService){ // accountBuilder = accountBuilder.agreeToTermsOfService(); // } // this.login = accountBuilder.createLogin(session); // this.account = this.login.getAccount(); // } // // public AccountManager(KeyPair keyPair, Session session, URL accountLocationUrl) { // this.login = session.login(accountLocationUrl, keyPair); // this.account = this.login.getAccount(); // } // // public Account getAccount() { // return this.account; // } // // public Login getLogin(){ // return this.login; // } // // public void addContact(URI contactURI) throws AcmeException { // this.account.modify() // .addContact(contactURI) // .commit(); // } // // public void changeAccountKeyPair(KeyPair keyPair) throws AcmeException { // this.account.changeKey(keyPair); // } // // public void deactivateAccount() throws AcmeException { // try { // this.account.deactivate(); // } catch (AcmeException e) { // if (!e.getMessage().equals("HTTP 202: Accepted")) { // throw e; // } // } // } // // } // Path: src/main/java/com/jblur/acme_client/CommandExecutor.java import com.google.gson.Gson; import com.google.gson.JsonObject; import com.jblur.acme_client.command.ACMECommand; import com.jblur.acme_client.command.AccountKeyNotFoundException; import com.jblur.acme_client.command.certificate.*; import com.jblur.acme_client.command.registration.*; import com.jblur.acme_client.manager.AccountManager; import org.shredzone.acme4j.exception.AcmeException; import org.shredzone.acme4j.exception.AcmeUserActionRequiredException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; LOG.error("Manual action required. Please visit url with instructions: "+e.getInstance().toString(), e); if(e.getTermsOfServiceUri()!=null){ LOG.error("You should agree to terms of service: "+e.getTermsOfServiceUri()); } result=RESULT_ERROR; } catch (AcmeException e) { e.printStackTrace(); result=RESULT_ERROR; } System.out.println(result); } private AccountManager getAccountManager() { AccountManager accountManager = null; try { RegistrationCommand registrationCommand = new RegistrationCommand(parameters); result = executeACMECommand(registrationCommand); accountManager = registrationCommand.getAccountManager(); if (accountManager == null) { LOG.error("Cannot get account information."); } } catch (AccountKeyNotFoundException e) { LOG.error("Account key not found.", e); } catch (AcmeException e) { LOG.error("Cannot be authorized.", e); } return accountManager; }
private String executeACMECommand(ACMECommand acmeCommand) {
mvmn/gp2srv
src/main/java/x/mvmn/log/PrintStreamLogger.java
// Path: src/main/java/x/mvmn/lang/util/DateHelper.java // public class DateHelper { // private static final FastDateFormat FDF = FastDateFormat.getInstance("yyyy-MM-dd HH:mm:ss.SSS"); // // public static String getDateSortFriendlyStr() { // return FDF.format(Calendar.getInstance()); // } // } // // Path: src/main/java/x/mvmn/log/api/Logger.java // public interface Logger { // // public static enum LogLevel { // TRACE, DEBUG, INFO, WARN, ERROR, SEVERE, FATAL // } // // public Logger setLevel(LogLevel level); // // public LogLevel getLevel(); // // public boolean shouldLog(LogLevel logLevel); // // public Logger log(LogLevel level, String text); // // public Logger log(LogLevel level, String text, Throwable t); // // public Logger log(LogLevel level, Throwable t); // // public Logger trace(String text); // // public Logger trace(String text, Throwable t); // // public Logger trace(Throwable t); // // public Logger debug(String text); // // public Logger debug(String text, Throwable t); // // public Logger debug(Throwable t); // // public Logger info(String text); // // public Logger info(String text, Throwable t); // // public Logger info(Throwable t); // // public Logger warn(String text); // // public Logger warn(String text, Throwable t); // // public Logger warn(Throwable t); // // public Logger error(String text); // // public Logger error(String text, Throwable t); // // public Logger error(Throwable t); // // public Logger severe(String text); // // public Logger severe(String text, Throwable t); // // public Logger severe(Throwable t); // // public Logger fatal(String text); // // public Logger fatal(String text, Throwable t); // // public Logger fatal(Throwable t); // }
import java.io.PrintStream; import java.io.PrintWriter; import java.io.StringWriter; import x.mvmn.lang.util.DateHelper; import x.mvmn.log.api.Logger;
package x.mvmn.log; public class PrintStreamLogger extends AbstractLogger { private final PrintStream out; public PrintStreamLogger(final PrintStream out) { this.out = out; } private String getDateStr() {
// Path: src/main/java/x/mvmn/lang/util/DateHelper.java // public class DateHelper { // private static final FastDateFormat FDF = FastDateFormat.getInstance("yyyy-MM-dd HH:mm:ss.SSS"); // // public static String getDateSortFriendlyStr() { // return FDF.format(Calendar.getInstance()); // } // } // // Path: src/main/java/x/mvmn/log/api/Logger.java // public interface Logger { // // public static enum LogLevel { // TRACE, DEBUG, INFO, WARN, ERROR, SEVERE, FATAL // } // // public Logger setLevel(LogLevel level); // // public LogLevel getLevel(); // // public boolean shouldLog(LogLevel logLevel); // // public Logger log(LogLevel level, String text); // // public Logger log(LogLevel level, String text, Throwable t); // // public Logger log(LogLevel level, Throwable t); // // public Logger trace(String text); // // public Logger trace(String text, Throwable t); // // public Logger trace(Throwable t); // // public Logger debug(String text); // // public Logger debug(String text, Throwable t); // // public Logger debug(Throwable t); // // public Logger info(String text); // // public Logger info(String text, Throwable t); // // public Logger info(Throwable t); // // public Logger warn(String text); // // public Logger warn(String text, Throwable t); // // public Logger warn(Throwable t); // // public Logger error(String text); // // public Logger error(String text, Throwable t); // // public Logger error(Throwable t); // // public Logger severe(String text); // // public Logger severe(String text, Throwable t); // // public Logger severe(Throwable t); // // public Logger fatal(String text); // // public Logger fatal(String text, Throwable t); // // public Logger fatal(Throwable t); // } // Path: src/main/java/x/mvmn/log/PrintStreamLogger.java import java.io.PrintStream; import java.io.PrintWriter; import java.io.StringWriter; import x.mvmn.lang.util.DateHelper; import x.mvmn.log.api.Logger; package x.mvmn.log; public class PrintStreamLogger extends AbstractLogger { private final PrintStream out; public PrintStreamLogger(final PrintStream out) { this.out = out; } private String getDateStr() {
return DateHelper.getDateSortFriendlyStr();
mvmn/gp2srv
src/main/java/x/mvmn/log/PrintStreamLogger.java
// Path: src/main/java/x/mvmn/lang/util/DateHelper.java // public class DateHelper { // private static final FastDateFormat FDF = FastDateFormat.getInstance("yyyy-MM-dd HH:mm:ss.SSS"); // // public static String getDateSortFriendlyStr() { // return FDF.format(Calendar.getInstance()); // } // } // // Path: src/main/java/x/mvmn/log/api/Logger.java // public interface Logger { // // public static enum LogLevel { // TRACE, DEBUG, INFO, WARN, ERROR, SEVERE, FATAL // } // // public Logger setLevel(LogLevel level); // // public LogLevel getLevel(); // // public boolean shouldLog(LogLevel logLevel); // // public Logger log(LogLevel level, String text); // // public Logger log(LogLevel level, String text, Throwable t); // // public Logger log(LogLevel level, Throwable t); // // public Logger trace(String text); // // public Logger trace(String text, Throwable t); // // public Logger trace(Throwable t); // // public Logger debug(String text); // // public Logger debug(String text, Throwable t); // // public Logger debug(Throwable t); // // public Logger info(String text); // // public Logger info(String text, Throwable t); // // public Logger info(Throwable t); // // public Logger warn(String text); // // public Logger warn(String text, Throwable t); // // public Logger warn(Throwable t); // // public Logger error(String text); // // public Logger error(String text, Throwable t); // // public Logger error(Throwable t); // // public Logger severe(String text); // // public Logger severe(String text, Throwable t); // // public Logger severe(Throwable t); // // public Logger fatal(String text); // // public Logger fatal(String text, Throwable t); // // public Logger fatal(Throwable t); // }
import java.io.PrintStream; import java.io.PrintWriter; import java.io.StringWriter; import x.mvmn.lang.util.DateHelper; import x.mvmn.log.api.Logger;
package x.mvmn.log; public class PrintStreamLogger extends AbstractLogger { private final PrintStream out; public PrintStreamLogger(final PrintStream out) { this.out = out; } private String getDateStr() { return DateHelper.getDateSortFriendlyStr(); } private String stacktraceToString(final Throwable t) { StringWriter writer = new StringWriter(); t.printStackTrace(new PrintWriter(writer)); return writer.toString(); } private String concatStr(final String... strings) { StringBuilder result = new StringBuilder(); for (String str : strings) { result.append(str); } return result.toString(); }
// Path: src/main/java/x/mvmn/lang/util/DateHelper.java // public class DateHelper { // private static final FastDateFormat FDF = FastDateFormat.getInstance("yyyy-MM-dd HH:mm:ss.SSS"); // // public static String getDateSortFriendlyStr() { // return FDF.format(Calendar.getInstance()); // } // } // // Path: src/main/java/x/mvmn/log/api/Logger.java // public interface Logger { // // public static enum LogLevel { // TRACE, DEBUG, INFO, WARN, ERROR, SEVERE, FATAL // } // // public Logger setLevel(LogLevel level); // // public LogLevel getLevel(); // // public boolean shouldLog(LogLevel logLevel); // // public Logger log(LogLevel level, String text); // // public Logger log(LogLevel level, String text, Throwable t); // // public Logger log(LogLevel level, Throwable t); // // public Logger trace(String text); // // public Logger trace(String text, Throwable t); // // public Logger trace(Throwable t); // // public Logger debug(String text); // // public Logger debug(String text, Throwable t); // // public Logger debug(Throwable t); // // public Logger info(String text); // // public Logger info(String text, Throwable t); // // public Logger info(Throwable t); // // public Logger warn(String text); // // public Logger warn(String text, Throwable t); // // public Logger warn(Throwable t); // // public Logger error(String text); // // public Logger error(String text, Throwable t); // // public Logger error(Throwable t); // // public Logger severe(String text); // // public Logger severe(String text, Throwable t); // // public Logger severe(Throwable t); // // public Logger fatal(String text); // // public Logger fatal(String text, Throwable t); // // public Logger fatal(Throwable t); // } // Path: src/main/java/x/mvmn/log/PrintStreamLogger.java import java.io.PrintStream; import java.io.PrintWriter; import java.io.StringWriter; import x.mvmn.lang.util.DateHelper; import x.mvmn.log.api.Logger; package x.mvmn.log; public class PrintStreamLogger extends AbstractLogger { private final PrintStream out; public PrintStreamLogger(final PrintStream out) { this.out = out; } private String getDateStr() { return DateHelper.getDateSortFriendlyStr(); } private String stacktraceToString(final Throwable t) { StringWriter writer = new StringWriter(); t.printStackTrace(new PrintWriter(writer)); return writer.toString(); } private String concatStr(final String... strings) { StringBuilder result = new StringBuilder(); for (String str : strings) { result.append(str); } return result.toString(); }
public Logger log(final LogLevel level, final Throwable t) {
mvmn/gp2srv
src/main/java/x/mvmn/gp2srv/GPhoto2ServerLauncher.java
// Path: src/main/java/x/mvmn/log/api/Logger.java // public static enum LogLevel { // TRACE, DEBUG, INFO, WARN, ERROR, SEVERE, FATAL // }
import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.Options; import org.apache.commons.cli.PosixParser; import x.mvmn.log.api.Logger.LogLevel;
package x.mvmn.gp2srv; public class GPhoto2ServerLauncher { public static void main(String[] args) throws Exception { Integer port = null; final Options cliOptions = new Options(); cliOptions.addOption("usemocks", false, "Use mocks instead of real gphoto2 - for code testing."); cliOptions.addOption("port", true, "HTTP port."); cliOptions.addOption("gphoto2path", true, "Path to gphoto2 executable."); cliOptions.addOption("logLevel", true, "Log level (TRACE, DEBUG, INFO, WARN, ERROR, SEVERE, FATAL)."); cliOptions.addOption("auth", true, "Require authentication (login:password)."); cliOptions.addOption("imgfolder", true, "Path to store downloaded images at."); String imageDldPath = null; final CommandLine commandLine = new PosixParser().parse(cliOptions, args); if (commandLine.hasOption("imgfolder")) { imageDldPath = commandLine.getOptionValue("imgfolder"); } if (commandLine.hasOption("port")) { String portOptionVal = commandLine.getOptionValue("port"); try { int parsedPort = Integer.parseInt(portOptionVal.trim()); if (parsedPort < 1 || parsedPort > 65535) { throw new RuntimeException("Bad port value: " + parsedPort); } else { port = parsedPort; } } catch (NumberFormatException e) { throw new RuntimeException("Unable to parse port parameter as integer: '" + portOptionVal + "'."); } }
// Path: src/main/java/x/mvmn/log/api/Logger.java // public static enum LogLevel { // TRACE, DEBUG, INFO, WARN, ERROR, SEVERE, FATAL // } // Path: src/main/java/x/mvmn/gp2srv/GPhoto2ServerLauncher.java import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.Options; import org.apache.commons.cli.PosixParser; import x.mvmn.log.api.Logger.LogLevel; package x.mvmn.gp2srv; public class GPhoto2ServerLauncher { public static void main(String[] args) throws Exception { Integer port = null; final Options cliOptions = new Options(); cliOptions.addOption("usemocks", false, "Use mocks instead of real gphoto2 - for code testing."); cliOptions.addOption("port", true, "HTTP port."); cliOptions.addOption("gphoto2path", true, "Path to gphoto2 executable."); cliOptions.addOption("logLevel", true, "Log level (TRACE, DEBUG, INFO, WARN, ERROR, SEVERE, FATAL)."); cliOptions.addOption("auth", true, "Require authentication (login:password)."); cliOptions.addOption("imgfolder", true, "Path to store downloaded images at."); String imageDldPath = null; final CommandLine commandLine = new PosixParser().parse(cliOptions, args); if (commandLine.hasOption("imgfolder")) { imageDldPath = commandLine.getOptionValue("imgfolder"); } if (commandLine.hasOption("port")) { String portOptionVal = commandLine.getOptionValue("port"); try { int parsedPort = Integer.parseInt(portOptionVal.trim()); if (parsedPort < 1 || parsedPort > 65535) { throw new RuntimeException("Bad port value: " + parsedPort); } else { port = parsedPort; } } catch (NumberFormatException e) { throw new RuntimeException("Unable to parse port parameter as integer: '" + portOptionVal + "'."); } }
final LogLevel logLevel;
mvmn/gp2srv
src/main/java/x/mvmn/gp2srv/scripting/model/ScriptStep.java
// Path: src/main/java/x/mvmn/gp2srv/camera/CameraService.java // public interface CameraService { // public void close(); // // public byte[] capturePreview(); // // public CameraService releaseCamera(); // // public CameraFileSystemEntryBean capture(); // // public CameraFileSystemEntryBean capture(GP2CameraCaptureType captureType); // // public String getSummary(); // // public GP2CameraEventType waitForSpecificEvent(int timeout, GP2CameraEventType expectedEventType); // // public GP2CameraEventType waitForEvent(int timeout); // // public List<CameraConfigEntryBean> getConfig(); // // public Map<String, CameraConfigEntryBean> getConfigAsMap(); // // public CameraService setConfig(CameraConfigEntryBean configEntry); // // public List<CameraFileSystemEntryBean> filesList(final String path, boolean includeFiles, boolean includeFolders, boolean recursive); // // public CameraService fileDelete(final String filePath, final String fileName); // // public byte[] fileGetContents(final String filePath, final String fileName); // // public byte[] fileGetThumb(final String filePath, final String fileName); // // public String downloadFile(final String cameraFilePath, final String cameraFileName, final File downloadFolder); // // public CameraProvider getCameraProvider(); // } // // Path: src/main/java/x/mvmn/gp2srv/scripting/service/impl/JexlMapContext.java // public class JexlMapContext extends MapContext { // // protected final Map<String, Object> vars; // // public JexlMapContext() { // this(new TreeMap<String, Object>()); // } // // protected JexlMapContext(Map<String, Object> vars) { // super(vars); // this.vars = vars; // } // // public Set<String> variableNames() { // return Collections.unmodifiableSet(vars.keySet()); // } // // public Map<String, Object> toMap() { // return new TreeMap<String, Object>(vars); // } // } // // Path: src/main/java/x/mvmn/lang/util/WaitUtil.java // public class WaitUtil { // // public static void ensuredWait(long totalWaitTime) { // long waitTime = totalWaitTime; // long startTime = System.currentTimeMillis(); // long projectedEndTime = startTime + totalWaitTime; // do { // try { // if (waitTime > 0) { // Thread.sleep(waitTime); // } // } catch (InterruptedException e) { // // Wait time = Total wait time - passed time (e.g. total wait for 10 sec, interrupted after 3 sec, still 7 sec to wait) // // Passed time = now - start time // waitTime = totalWaitTime - (System.currentTimeMillis() - startTime); // } // } while (System.currentTimeMillis() < projectedEndTime); // } // }
import java.io.File; import org.apache.commons.jexl3.JexlEngine; import org.apache.commons.jexl3.JexlExpression; import x.mvmn.gp2srv.camera.CameraService; import x.mvmn.gp2srv.scripting.service.impl.JexlMapContext; import x.mvmn.jlibgphoto2.api.CameraConfigEntryBean; import x.mvmn.jlibgphoto2.api.CameraFileSystemEntryBean; import x.mvmn.jlibgphoto2.api.GP2Camera.GP2CameraEventType; import x.mvmn.lang.util.WaitUtil;
package x.mvmn.gp2srv.scripting.model; public class ScriptStep { public static enum ScriptStepType { CAPTURE(false), DELAY(true), CAMEVENT_WAIT(true), CAMPROP_SET(true), EXEC_SCRIPT(false), VAR_SET(true), STOP(false), DOWNLOAD_TO_PC(true), DELETE(true); protected final boolean usesExpression; ScriptStepType(boolean usesExpression) { this.usesExpression = usesExpression; } public boolean getUsesExpression() { return usesExpression; } } protected ScriptStepType type; protected String key; protected String expression; protected String condition; protected transient volatile JexlExpression conditionExpressionCache; protected transient volatile JexlExpression expressionExpressionCache; public ScriptStep() { } public ScriptStep(ScriptStepType type, String key, String expression, String condition) { this.setType(type); this.setKey(key); this.setExpression(expression); this.setCondition(condition); }
// Path: src/main/java/x/mvmn/gp2srv/camera/CameraService.java // public interface CameraService { // public void close(); // // public byte[] capturePreview(); // // public CameraService releaseCamera(); // // public CameraFileSystemEntryBean capture(); // // public CameraFileSystemEntryBean capture(GP2CameraCaptureType captureType); // // public String getSummary(); // // public GP2CameraEventType waitForSpecificEvent(int timeout, GP2CameraEventType expectedEventType); // // public GP2CameraEventType waitForEvent(int timeout); // // public List<CameraConfigEntryBean> getConfig(); // // public Map<String, CameraConfigEntryBean> getConfigAsMap(); // // public CameraService setConfig(CameraConfigEntryBean configEntry); // // public List<CameraFileSystemEntryBean> filesList(final String path, boolean includeFiles, boolean includeFolders, boolean recursive); // // public CameraService fileDelete(final String filePath, final String fileName); // // public byte[] fileGetContents(final String filePath, final String fileName); // // public byte[] fileGetThumb(final String filePath, final String fileName); // // public String downloadFile(final String cameraFilePath, final String cameraFileName, final File downloadFolder); // // public CameraProvider getCameraProvider(); // } // // Path: src/main/java/x/mvmn/gp2srv/scripting/service/impl/JexlMapContext.java // public class JexlMapContext extends MapContext { // // protected final Map<String, Object> vars; // // public JexlMapContext() { // this(new TreeMap<String, Object>()); // } // // protected JexlMapContext(Map<String, Object> vars) { // super(vars); // this.vars = vars; // } // // public Set<String> variableNames() { // return Collections.unmodifiableSet(vars.keySet()); // } // // public Map<String, Object> toMap() { // return new TreeMap<String, Object>(vars); // } // } // // Path: src/main/java/x/mvmn/lang/util/WaitUtil.java // public class WaitUtil { // // public static void ensuredWait(long totalWaitTime) { // long waitTime = totalWaitTime; // long startTime = System.currentTimeMillis(); // long projectedEndTime = startTime + totalWaitTime; // do { // try { // if (waitTime > 0) { // Thread.sleep(waitTime); // } // } catch (InterruptedException e) { // // Wait time = Total wait time - passed time (e.g. total wait for 10 sec, interrupted after 3 sec, still 7 sec to wait) // // Passed time = now - start time // waitTime = totalWaitTime - (System.currentTimeMillis() - startTime); // } // } while (System.currentTimeMillis() < projectedEndTime); // } // } // Path: src/main/java/x/mvmn/gp2srv/scripting/model/ScriptStep.java import java.io.File; import org.apache.commons.jexl3.JexlEngine; import org.apache.commons.jexl3.JexlExpression; import x.mvmn.gp2srv.camera.CameraService; import x.mvmn.gp2srv.scripting.service.impl.JexlMapContext; import x.mvmn.jlibgphoto2.api.CameraConfigEntryBean; import x.mvmn.jlibgphoto2.api.CameraFileSystemEntryBean; import x.mvmn.jlibgphoto2.api.GP2Camera.GP2CameraEventType; import x.mvmn.lang.util.WaitUtil; package x.mvmn.gp2srv.scripting.model; public class ScriptStep { public static enum ScriptStepType { CAPTURE(false), DELAY(true), CAMEVENT_WAIT(true), CAMPROP_SET(true), EXEC_SCRIPT(false), VAR_SET(true), STOP(false), DOWNLOAD_TO_PC(true), DELETE(true); protected final boolean usesExpression; ScriptStepType(boolean usesExpression) { this.usesExpression = usesExpression; } public boolean getUsesExpression() { return usesExpression; } } protected ScriptStepType type; protected String key; protected String expression; protected String condition; protected transient volatile JexlExpression conditionExpressionCache; protected transient volatile JexlExpression expressionExpressionCache; public ScriptStep() { } public ScriptStep(ScriptStepType type, String key, String expression, String condition) { this.setType(type); this.setKey(key); this.setExpression(expression); this.setCondition(condition); }
public boolean evalCondition(JexlEngine engine, JexlMapContext context) {
mvmn/gp2srv
src/main/java/x/mvmn/gp2srv/scripting/model/ScriptStep.java
// Path: src/main/java/x/mvmn/gp2srv/camera/CameraService.java // public interface CameraService { // public void close(); // // public byte[] capturePreview(); // // public CameraService releaseCamera(); // // public CameraFileSystemEntryBean capture(); // // public CameraFileSystemEntryBean capture(GP2CameraCaptureType captureType); // // public String getSummary(); // // public GP2CameraEventType waitForSpecificEvent(int timeout, GP2CameraEventType expectedEventType); // // public GP2CameraEventType waitForEvent(int timeout); // // public List<CameraConfigEntryBean> getConfig(); // // public Map<String, CameraConfigEntryBean> getConfigAsMap(); // // public CameraService setConfig(CameraConfigEntryBean configEntry); // // public List<CameraFileSystemEntryBean> filesList(final String path, boolean includeFiles, boolean includeFolders, boolean recursive); // // public CameraService fileDelete(final String filePath, final String fileName); // // public byte[] fileGetContents(final String filePath, final String fileName); // // public byte[] fileGetThumb(final String filePath, final String fileName); // // public String downloadFile(final String cameraFilePath, final String cameraFileName, final File downloadFolder); // // public CameraProvider getCameraProvider(); // } // // Path: src/main/java/x/mvmn/gp2srv/scripting/service/impl/JexlMapContext.java // public class JexlMapContext extends MapContext { // // protected final Map<String, Object> vars; // // public JexlMapContext() { // this(new TreeMap<String, Object>()); // } // // protected JexlMapContext(Map<String, Object> vars) { // super(vars); // this.vars = vars; // } // // public Set<String> variableNames() { // return Collections.unmodifiableSet(vars.keySet()); // } // // public Map<String, Object> toMap() { // return new TreeMap<String, Object>(vars); // } // } // // Path: src/main/java/x/mvmn/lang/util/WaitUtil.java // public class WaitUtil { // // public static void ensuredWait(long totalWaitTime) { // long waitTime = totalWaitTime; // long startTime = System.currentTimeMillis(); // long projectedEndTime = startTime + totalWaitTime; // do { // try { // if (waitTime > 0) { // Thread.sleep(waitTime); // } // } catch (InterruptedException e) { // // Wait time = Total wait time - passed time (e.g. total wait for 10 sec, interrupted after 3 sec, still 7 sec to wait) // // Passed time = now - start time // waitTime = totalWaitTime - (System.currentTimeMillis() - startTime); // } // } while (System.currentTimeMillis() < projectedEndTime); // } // }
import java.io.File; import org.apache.commons.jexl3.JexlEngine; import org.apache.commons.jexl3.JexlExpression; import x.mvmn.gp2srv.camera.CameraService; import x.mvmn.gp2srv.scripting.service.impl.JexlMapContext; import x.mvmn.jlibgphoto2.api.CameraConfigEntryBean; import x.mvmn.jlibgphoto2.api.CameraFileSystemEntryBean; import x.mvmn.jlibgphoto2.api.GP2Camera.GP2CameraEventType; import x.mvmn.lang.util.WaitUtil;
protected ScriptStepType type; protected String key; protected String expression; protected String condition; protected transient volatile JexlExpression conditionExpressionCache; protected transient volatile JexlExpression expressionExpressionCache; public ScriptStep() { } public ScriptStep(ScriptStepType type, String key, String expression, String condition) { this.setType(type); this.setKey(key); this.setExpression(expression); this.setCondition(condition); } public boolean evalCondition(JexlEngine engine, JexlMapContext context) { boolean execute = true; if (condition != null && !condition.trim().isEmpty()) { execute = Boolean .valueOf((conditionExpressionCache == null ? (conditionExpressionCache = engine.createExpression(condition)) : conditionExpressionCache) .evaluate(context).toString()); } return execute; }
// Path: src/main/java/x/mvmn/gp2srv/camera/CameraService.java // public interface CameraService { // public void close(); // // public byte[] capturePreview(); // // public CameraService releaseCamera(); // // public CameraFileSystemEntryBean capture(); // // public CameraFileSystemEntryBean capture(GP2CameraCaptureType captureType); // // public String getSummary(); // // public GP2CameraEventType waitForSpecificEvent(int timeout, GP2CameraEventType expectedEventType); // // public GP2CameraEventType waitForEvent(int timeout); // // public List<CameraConfigEntryBean> getConfig(); // // public Map<String, CameraConfigEntryBean> getConfigAsMap(); // // public CameraService setConfig(CameraConfigEntryBean configEntry); // // public List<CameraFileSystemEntryBean> filesList(final String path, boolean includeFiles, boolean includeFolders, boolean recursive); // // public CameraService fileDelete(final String filePath, final String fileName); // // public byte[] fileGetContents(final String filePath, final String fileName); // // public byte[] fileGetThumb(final String filePath, final String fileName); // // public String downloadFile(final String cameraFilePath, final String cameraFileName, final File downloadFolder); // // public CameraProvider getCameraProvider(); // } // // Path: src/main/java/x/mvmn/gp2srv/scripting/service/impl/JexlMapContext.java // public class JexlMapContext extends MapContext { // // protected final Map<String, Object> vars; // // public JexlMapContext() { // this(new TreeMap<String, Object>()); // } // // protected JexlMapContext(Map<String, Object> vars) { // super(vars); // this.vars = vars; // } // // public Set<String> variableNames() { // return Collections.unmodifiableSet(vars.keySet()); // } // // public Map<String, Object> toMap() { // return new TreeMap<String, Object>(vars); // } // } // // Path: src/main/java/x/mvmn/lang/util/WaitUtil.java // public class WaitUtil { // // public static void ensuredWait(long totalWaitTime) { // long waitTime = totalWaitTime; // long startTime = System.currentTimeMillis(); // long projectedEndTime = startTime + totalWaitTime; // do { // try { // if (waitTime > 0) { // Thread.sleep(waitTime); // } // } catch (InterruptedException e) { // // Wait time = Total wait time - passed time (e.g. total wait for 10 sec, interrupted after 3 sec, still 7 sec to wait) // // Passed time = now - start time // waitTime = totalWaitTime - (System.currentTimeMillis() - startTime); // } // } while (System.currentTimeMillis() < projectedEndTime); // } // } // Path: src/main/java/x/mvmn/gp2srv/scripting/model/ScriptStep.java import java.io.File; import org.apache.commons.jexl3.JexlEngine; import org.apache.commons.jexl3.JexlExpression; import x.mvmn.gp2srv.camera.CameraService; import x.mvmn.gp2srv.scripting.service.impl.JexlMapContext; import x.mvmn.jlibgphoto2.api.CameraConfigEntryBean; import x.mvmn.jlibgphoto2.api.CameraFileSystemEntryBean; import x.mvmn.jlibgphoto2.api.GP2Camera.GP2CameraEventType; import x.mvmn.lang.util.WaitUtil; protected ScriptStepType type; protected String key; protected String expression; protected String condition; protected transient volatile JexlExpression conditionExpressionCache; protected transient volatile JexlExpression expressionExpressionCache; public ScriptStep() { } public ScriptStep(ScriptStepType type, String key, String expression, String condition) { this.setType(type); this.setKey(key); this.setExpression(expression); this.setCondition(condition); } public boolean evalCondition(JexlEngine engine, JexlMapContext context) { boolean execute = true; if (condition != null && !condition.trim().isEmpty()) { execute = Boolean .valueOf((conditionExpressionCache == null ? (conditionExpressionCache = engine.createExpression(condition)) : conditionExpressionCache) .evaluate(context).toString()); } return execute; }
public CameraConfigEntryBean getConfigEntryForEval(CameraService cameraService) {
mvmn/gp2srv
src/main/java/x/mvmn/gp2srv/scripting/model/ScriptStep.java
// Path: src/main/java/x/mvmn/gp2srv/camera/CameraService.java // public interface CameraService { // public void close(); // // public byte[] capturePreview(); // // public CameraService releaseCamera(); // // public CameraFileSystemEntryBean capture(); // // public CameraFileSystemEntryBean capture(GP2CameraCaptureType captureType); // // public String getSummary(); // // public GP2CameraEventType waitForSpecificEvent(int timeout, GP2CameraEventType expectedEventType); // // public GP2CameraEventType waitForEvent(int timeout); // // public List<CameraConfigEntryBean> getConfig(); // // public Map<String, CameraConfigEntryBean> getConfigAsMap(); // // public CameraService setConfig(CameraConfigEntryBean configEntry); // // public List<CameraFileSystemEntryBean> filesList(final String path, boolean includeFiles, boolean includeFolders, boolean recursive); // // public CameraService fileDelete(final String filePath, final String fileName); // // public byte[] fileGetContents(final String filePath, final String fileName); // // public byte[] fileGetThumb(final String filePath, final String fileName); // // public String downloadFile(final String cameraFilePath, final String cameraFileName, final File downloadFolder); // // public CameraProvider getCameraProvider(); // } // // Path: src/main/java/x/mvmn/gp2srv/scripting/service/impl/JexlMapContext.java // public class JexlMapContext extends MapContext { // // protected final Map<String, Object> vars; // // public JexlMapContext() { // this(new TreeMap<String, Object>()); // } // // protected JexlMapContext(Map<String, Object> vars) { // super(vars); // this.vars = vars; // } // // public Set<String> variableNames() { // return Collections.unmodifiableSet(vars.keySet()); // } // // public Map<String, Object> toMap() { // return new TreeMap<String, Object>(vars); // } // } // // Path: src/main/java/x/mvmn/lang/util/WaitUtil.java // public class WaitUtil { // // public static void ensuredWait(long totalWaitTime) { // long waitTime = totalWaitTime; // long startTime = System.currentTimeMillis(); // long projectedEndTime = startTime + totalWaitTime; // do { // try { // if (waitTime > 0) { // Thread.sleep(waitTime); // } // } catch (InterruptedException e) { // // Wait time = Total wait time - passed time (e.g. total wait for 10 sec, interrupted after 3 sec, still 7 sec to wait) // // Passed time = now - start time // waitTime = totalWaitTime - (System.currentTimeMillis() - startTime); // } // } while (System.currentTimeMillis() < projectedEndTime); // } // }
import java.io.File; import org.apache.commons.jexl3.JexlEngine; import org.apache.commons.jexl3.JexlExpression; import x.mvmn.gp2srv.camera.CameraService; import x.mvmn.gp2srv.scripting.service.impl.JexlMapContext; import x.mvmn.jlibgphoto2.api.CameraConfigEntryBean; import x.mvmn.jlibgphoto2.api.CameraFileSystemEntryBean; import x.mvmn.jlibgphoto2.api.GP2Camera.GP2CameraEventType; import x.mvmn.lang.util.WaitUtil;
switch (type) { case DELETE: { final int separatorIndex = evaluatedValueAsString.lastIndexOf("/"); String path = evaluatedValueAsString.substring(0, separatorIndex); if (path.trim().isEmpty()) { path = "/"; } cameraService.fileDelete(path, evaluatedValueAsString.substring(separatorIndex + 1)); } break; case DOWNLOAD_TO_PC: { final int separatorIndex = evaluatedValueAsString.lastIndexOf("/"); String path = evaluatedValueAsString.substring(0, separatorIndex); if (path.trim().isEmpty()) { path = "/"; } cameraService.downloadFile(path, evaluatedValueAsString.substring(separatorIndex + 1), imgDownloadPath); } break; case EXEC_SCRIPT: engine.createScript(expression).execute(context); break; case STOP: result = true; break; case CAPTURE: CameraFileSystemEntryBean cfseb = cameraService.capture(); context.set("__capturedFile", cfseb.getPath() + (cfseb.getPath().endsWith("/") ? "" : "/") + cfseb.getName()); break; case DELAY:
// Path: src/main/java/x/mvmn/gp2srv/camera/CameraService.java // public interface CameraService { // public void close(); // // public byte[] capturePreview(); // // public CameraService releaseCamera(); // // public CameraFileSystemEntryBean capture(); // // public CameraFileSystemEntryBean capture(GP2CameraCaptureType captureType); // // public String getSummary(); // // public GP2CameraEventType waitForSpecificEvent(int timeout, GP2CameraEventType expectedEventType); // // public GP2CameraEventType waitForEvent(int timeout); // // public List<CameraConfigEntryBean> getConfig(); // // public Map<String, CameraConfigEntryBean> getConfigAsMap(); // // public CameraService setConfig(CameraConfigEntryBean configEntry); // // public List<CameraFileSystemEntryBean> filesList(final String path, boolean includeFiles, boolean includeFolders, boolean recursive); // // public CameraService fileDelete(final String filePath, final String fileName); // // public byte[] fileGetContents(final String filePath, final String fileName); // // public byte[] fileGetThumb(final String filePath, final String fileName); // // public String downloadFile(final String cameraFilePath, final String cameraFileName, final File downloadFolder); // // public CameraProvider getCameraProvider(); // } // // Path: src/main/java/x/mvmn/gp2srv/scripting/service/impl/JexlMapContext.java // public class JexlMapContext extends MapContext { // // protected final Map<String, Object> vars; // // public JexlMapContext() { // this(new TreeMap<String, Object>()); // } // // protected JexlMapContext(Map<String, Object> vars) { // super(vars); // this.vars = vars; // } // // public Set<String> variableNames() { // return Collections.unmodifiableSet(vars.keySet()); // } // // public Map<String, Object> toMap() { // return new TreeMap<String, Object>(vars); // } // } // // Path: src/main/java/x/mvmn/lang/util/WaitUtil.java // public class WaitUtil { // // public static void ensuredWait(long totalWaitTime) { // long waitTime = totalWaitTime; // long startTime = System.currentTimeMillis(); // long projectedEndTime = startTime + totalWaitTime; // do { // try { // if (waitTime > 0) { // Thread.sleep(waitTime); // } // } catch (InterruptedException e) { // // Wait time = Total wait time - passed time (e.g. total wait for 10 sec, interrupted after 3 sec, still 7 sec to wait) // // Passed time = now - start time // waitTime = totalWaitTime - (System.currentTimeMillis() - startTime); // } // } while (System.currentTimeMillis() < projectedEndTime); // } // } // Path: src/main/java/x/mvmn/gp2srv/scripting/model/ScriptStep.java import java.io.File; import org.apache.commons.jexl3.JexlEngine; import org.apache.commons.jexl3.JexlExpression; import x.mvmn.gp2srv.camera.CameraService; import x.mvmn.gp2srv.scripting.service.impl.JexlMapContext; import x.mvmn.jlibgphoto2.api.CameraConfigEntryBean; import x.mvmn.jlibgphoto2.api.CameraFileSystemEntryBean; import x.mvmn.jlibgphoto2.api.GP2Camera.GP2CameraEventType; import x.mvmn.lang.util.WaitUtil; switch (type) { case DELETE: { final int separatorIndex = evaluatedValueAsString.lastIndexOf("/"); String path = evaluatedValueAsString.substring(0, separatorIndex); if (path.trim().isEmpty()) { path = "/"; } cameraService.fileDelete(path, evaluatedValueAsString.substring(separatorIndex + 1)); } break; case DOWNLOAD_TO_PC: { final int separatorIndex = evaluatedValueAsString.lastIndexOf("/"); String path = evaluatedValueAsString.substring(0, separatorIndex); if (path.trim().isEmpty()) { path = "/"; } cameraService.downloadFile(path, evaluatedValueAsString.substring(separatorIndex + 1), imgDownloadPath); } break; case EXEC_SCRIPT: engine.createScript(expression).execute(context); break; case STOP: result = true; break; case CAPTURE: CameraFileSystemEntryBean cfseb = cameraService.capture(); context.set("__capturedFile", cfseb.getPath() + (cfseb.getPath().endsWith("/") ? "" : "/") + cfseb.getName()); break; case DELAY:
WaitUtil.ensuredWait(Long.parseLong(evaluatedValueAsString));
mvmn/gp2srv
src/main/java/x/mvmn/gp2srv/web/servlets/AbstractErrorHandlingServlet.java
// Path: src/main/java/x/mvmn/gp2srv/web/service/velocity/TemplateEngine.java // public class TemplateEngine { // // public static final String DEFAULT_TEMPLATES_CLASSPATH_PREFIX = "/x/mvmn/gp2srv/web/templates/"; // // private final VelocityEngine engine; // private final String templatesClasspathPrefix; // // protected static class StaticToolsHelper { // // private static final Class<?> TOOLS[] = new Class<?>[] { DateHelper.class }; // // public static void populateTools(final Context context) { // for (final Class<?> toolClass : TOOLS) { // context.put("tool" + toolClass.getSimpleName(), toolClass); // } // } // } // // public TemplateEngine(Map<String, String> pathToTempalteMapping) { // this(DEFAULT_TEMPLATES_CLASSPATH_PREFIX, pathToTempalteMapping); // } // // public TemplateEngine(String templatesClasspathPrefix, Map<String, String> pathToTempalteMapping) { // this.templatesClasspathPrefix = templatesClasspathPrefix; // try { // initStringResourceRepository(pathToTempalteMapping); // engine = new VelocityEngine(getConfigurationAsProperties()); // } catch (Exception e) { // throw new RuntimeException("Failed in initialize Template Engine", e); // } // } // // private StringResourceRepository initStringResourceRepository(Map<String, String> pathToTempalteMapping) throws IOException { // StringResourceRepository result = new StringResourceRepositoryImpl(); // StringResourceLoader.setRepository(StringResourceLoader.REPOSITORY_NAME_DEFAULT, result); // registerResource(result, RuntimeConstants.VM_LIBRARY_DEFAULT, RuntimeConstants.VM_LIBRARY_DEFAULT); // for (Map.Entry<String, String> pathToTempalteMappingItem : pathToTempalteMapping.entrySet()) { // registerResource(result, pathToTempalteMappingItem.getKey(), pathToTempalteMappingItem.getValue()); // } // return result; // } // // private void registerResource(StringResourceRepository repo, String registeredName, String relativeClasspathRef) throws IOException { // String templateClasspathRef = templatesClasspathPrefix + relativeClasspathRef.replaceAll("\\.\\./", ""); // InputStream templateBodyInputStream = GPhoto2Server.class.getResourceAsStream(templateClasspathRef); // String templateBodyString = IOUtils.toString(templateBodyInputStream, "UTF-8"); // repo.putStringResource(registeredName, templateBodyString); // } // // private Properties getConfigurationAsProperties() { // Properties result = new Properties(); // // result.setProperty(RuntimeConstants.RESOURCE_LOADER, "string"); // result.setProperty(RuntimeConstants.VM_LIBRARY_AUTORELOAD, "false"); // result.setProperty(RuntimeConstants.VM_LIBRARY, RuntimeConstants.VM_LIBRARY_DEFAULT); // result.setProperty("string.resource.loader.class", StringResourceLoader.class.getName()); // result.setProperty("string.resource.loader.modificationCheckInterval", "0"); // result.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS, SystemLogChute.class.getName()); // // return result; // } // // public void renderTemplate(String tempalteName, String encoding, Context context, Writer output) { // StaticToolsHelper.populateTools(context); // engine.mergeTemplate(tempalteName, encoding, context, output); // } // } // // Path: src/main/java/x/mvmn/lang/util/Provider.java // public interface Provider<T> { // // public T provide(); // } // // Path: src/main/java/x/mvmn/log/api/Logger.java // public interface Logger { // // public static enum LogLevel { // TRACE, DEBUG, INFO, WARN, ERROR, SEVERE, FATAL // } // // public Logger setLevel(LogLevel level); // // public LogLevel getLevel(); // // public boolean shouldLog(LogLevel logLevel); // // public Logger log(LogLevel level, String text); // // public Logger log(LogLevel level, String text, Throwable t); // // public Logger log(LogLevel level, Throwable t); // // public Logger trace(String text); // // public Logger trace(String text, Throwable t); // // public Logger trace(Throwable t); // // public Logger debug(String text); // // public Logger debug(String text, Throwable t); // // public Logger debug(Throwable t); // // public Logger info(String text); // // public Logger info(String text, Throwable t); // // public Logger info(Throwable t); // // public Logger warn(String text); // // public Logger warn(String text, Throwable t); // // public Logger warn(Throwable t); // // public Logger error(String text); // // public Logger error(String text, Throwable t); // // public Logger error(Throwable t); // // public Logger severe(String text); // // public Logger severe(String text, Throwable t); // // public Logger severe(Throwable t); // // public Logger fatal(String text); // // public Logger fatal(String text, Throwable t); // // public Logger fatal(Throwable t); // }
import java.io.IOException; import java.io.Writer; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.velocity.VelocityContext; import x.mvmn.gp2srv.web.service.velocity.TemplateEngine; import x.mvmn.lang.util.Provider; import x.mvmn.log.api.Logger;
package x.mvmn.gp2srv.web.servlets; public abstract class AbstractErrorHandlingServlet extends HttpServletWithTemplates { private static final long serialVersionUID = 8638499002251355635L;
// Path: src/main/java/x/mvmn/gp2srv/web/service/velocity/TemplateEngine.java // public class TemplateEngine { // // public static final String DEFAULT_TEMPLATES_CLASSPATH_PREFIX = "/x/mvmn/gp2srv/web/templates/"; // // private final VelocityEngine engine; // private final String templatesClasspathPrefix; // // protected static class StaticToolsHelper { // // private static final Class<?> TOOLS[] = new Class<?>[] { DateHelper.class }; // // public static void populateTools(final Context context) { // for (final Class<?> toolClass : TOOLS) { // context.put("tool" + toolClass.getSimpleName(), toolClass); // } // } // } // // public TemplateEngine(Map<String, String> pathToTempalteMapping) { // this(DEFAULT_TEMPLATES_CLASSPATH_PREFIX, pathToTempalteMapping); // } // // public TemplateEngine(String templatesClasspathPrefix, Map<String, String> pathToTempalteMapping) { // this.templatesClasspathPrefix = templatesClasspathPrefix; // try { // initStringResourceRepository(pathToTempalteMapping); // engine = new VelocityEngine(getConfigurationAsProperties()); // } catch (Exception e) { // throw new RuntimeException("Failed in initialize Template Engine", e); // } // } // // private StringResourceRepository initStringResourceRepository(Map<String, String> pathToTempalteMapping) throws IOException { // StringResourceRepository result = new StringResourceRepositoryImpl(); // StringResourceLoader.setRepository(StringResourceLoader.REPOSITORY_NAME_DEFAULT, result); // registerResource(result, RuntimeConstants.VM_LIBRARY_DEFAULT, RuntimeConstants.VM_LIBRARY_DEFAULT); // for (Map.Entry<String, String> pathToTempalteMappingItem : pathToTempalteMapping.entrySet()) { // registerResource(result, pathToTempalteMappingItem.getKey(), pathToTempalteMappingItem.getValue()); // } // return result; // } // // private void registerResource(StringResourceRepository repo, String registeredName, String relativeClasspathRef) throws IOException { // String templateClasspathRef = templatesClasspathPrefix + relativeClasspathRef.replaceAll("\\.\\./", ""); // InputStream templateBodyInputStream = GPhoto2Server.class.getResourceAsStream(templateClasspathRef); // String templateBodyString = IOUtils.toString(templateBodyInputStream, "UTF-8"); // repo.putStringResource(registeredName, templateBodyString); // } // // private Properties getConfigurationAsProperties() { // Properties result = new Properties(); // // result.setProperty(RuntimeConstants.RESOURCE_LOADER, "string"); // result.setProperty(RuntimeConstants.VM_LIBRARY_AUTORELOAD, "false"); // result.setProperty(RuntimeConstants.VM_LIBRARY, RuntimeConstants.VM_LIBRARY_DEFAULT); // result.setProperty("string.resource.loader.class", StringResourceLoader.class.getName()); // result.setProperty("string.resource.loader.modificationCheckInterval", "0"); // result.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS, SystemLogChute.class.getName()); // // return result; // } // // public void renderTemplate(String tempalteName, String encoding, Context context, Writer output) { // StaticToolsHelper.populateTools(context); // engine.mergeTemplate(tempalteName, encoding, context, output); // } // } // // Path: src/main/java/x/mvmn/lang/util/Provider.java // public interface Provider<T> { // // public T provide(); // } // // Path: src/main/java/x/mvmn/log/api/Logger.java // public interface Logger { // // public static enum LogLevel { // TRACE, DEBUG, INFO, WARN, ERROR, SEVERE, FATAL // } // // public Logger setLevel(LogLevel level); // // public LogLevel getLevel(); // // public boolean shouldLog(LogLevel logLevel); // // public Logger log(LogLevel level, String text); // // public Logger log(LogLevel level, String text, Throwable t); // // public Logger log(LogLevel level, Throwable t); // // public Logger trace(String text); // // public Logger trace(String text, Throwable t); // // public Logger trace(Throwable t); // // public Logger debug(String text); // // public Logger debug(String text, Throwable t); // // public Logger debug(Throwable t); // // public Logger info(String text); // // public Logger info(String text, Throwable t); // // public Logger info(Throwable t); // // public Logger warn(String text); // // public Logger warn(String text, Throwable t); // // public Logger warn(Throwable t); // // public Logger error(String text); // // public Logger error(String text, Throwable t); // // public Logger error(Throwable t); // // public Logger severe(String text); // // public Logger severe(String text, Throwable t); // // public Logger severe(Throwable t); // // public Logger fatal(String text); // // public Logger fatal(String text, Throwable t); // // public Logger fatal(Throwable t); // } // Path: src/main/java/x/mvmn/gp2srv/web/servlets/AbstractErrorHandlingServlet.java import java.io.IOException; import java.io.Writer; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.velocity.VelocityContext; import x.mvmn.gp2srv.web.service.velocity.TemplateEngine; import x.mvmn.lang.util.Provider; import x.mvmn.log.api.Logger; package x.mvmn.gp2srv.web.servlets; public abstract class AbstractErrorHandlingServlet extends HttpServletWithTemplates { private static final long serialVersionUID = 8638499002251355635L;
protected final Logger logger;
mvmn/gp2srv
src/main/java/x/mvmn/gp2srv/web/servlets/AbstractErrorHandlingServlet.java
// Path: src/main/java/x/mvmn/gp2srv/web/service/velocity/TemplateEngine.java // public class TemplateEngine { // // public static final String DEFAULT_TEMPLATES_CLASSPATH_PREFIX = "/x/mvmn/gp2srv/web/templates/"; // // private final VelocityEngine engine; // private final String templatesClasspathPrefix; // // protected static class StaticToolsHelper { // // private static final Class<?> TOOLS[] = new Class<?>[] { DateHelper.class }; // // public static void populateTools(final Context context) { // for (final Class<?> toolClass : TOOLS) { // context.put("tool" + toolClass.getSimpleName(), toolClass); // } // } // } // // public TemplateEngine(Map<String, String> pathToTempalteMapping) { // this(DEFAULT_TEMPLATES_CLASSPATH_PREFIX, pathToTempalteMapping); // } // // public TemplateEngine(String templatesClasspathPrefix, Map<String, String> pathToTempalteMapping) { // this.templatesClasspathPrefix = templatesClasspathPrefix; // try { // initStringResourceRepository(pathToTempalteMapping); // engine = new VelocityEngine(getConfigurationAsProperties()); // } catch (Exception e) { // throw new RuntimeException("Failed in initialize Template Engine", e); // } // } // // private StringResourceRepository initStringResourceRepository(Map<String, String> pathToTempalteMapping) throws IOException { // StringResourceRepository result = new StringResourceRepositoryImpl(); // StringResourceLoader.setRepository(StringResourceLoader.REPOSITORY_NAME_DEFAULT, result); // registerResource(result, RuntimeConstants.VM_LIBRARY_DEFAULT, RuntimeConstants.VM_LIBRARY_DEFAULT); // for (Map.Entry<String, String> pathToTempalteMappingItem : pathToTempalteMapping.entrySet()) { // registerResource(result, pathToTempalteMappingItem.getKey(), pathToTempalteMappingItem.getValue()); // } // return result; // } // // private void registerResource(StringResourceRepository repo, String registeredName, String relativeClasspathRef) throws IOException { // String templateClasspathRef = templatesClasspathPrefix + relativeClasspathRef.replaceAll("\\.\\./", ""); // InputStream templateBodyInputStream = GPhoto2Server.class.getResourceAsStream(templateClasspathRef); // String templateBodyString = IOUtils.toString(templateBodyInputStream, "UTF-8"); // repo.putStringResource(registeredName, templateBodyString); // } // // private Properties getConfigurationAsProperties() { // Properties result = new Properties(); // // result.setProperty(RuntimeConstants.RESOURCE_LOADER, "string"); // result.setProperty(RuntimeConstants.VM_LIBRARY_AUTORELOAD, "false"); // result.setProperty(RuntimeConstants.VM_LIBRARY, RuntimeConstants.VM_LIBRARY_DEFAULT); // result.setProperty("string.resource.loader.class", StringResourceLoader.class.getName()); // result.setProperty("string.resource.loader.modificationCheckInterval", "0"); // result.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS, SystemLogChute.class.getName()); // // return result; // } // // public void renderTemplate(String tempalteName, String encoding, Context context, Writer output) { // StaticToolsHelper.populateTools(context); // engine.mergeTemplate(tempalteName, encoding, context, output); // } // } // // Path: src/main/java/x/mvmn/lang/util/Provider.java // public interface Provider<T> { // // public T provide(); // } // // Path: src/main/java/x/mvmn/log/api/Logger.java // public interface Logger { // // public static enum LogLevel { // TRACE, DEBUG, INFO, WARN, ERROR, SEVERE, FATAL // } // // public Logger setLevel(LogLevel level); // // public LogLevel getLevel(); // // public boolean shouldLog(LogLevel logLevel); // // public Logger log(LogLevel level, String text); // // public Logger log(LogLevel level, String text, Throwable t); // // public Logger log(LogLevel level, Throwable t); // // public Logger trace(String text); // // public Logger trace(String text, Throwable t); // // public Logger trace(Throwable t); // // public Logger debug(String text); // // public Logger debug(String text, Throwable t); // // public Logger debug(Throwable t); // // public Logger info(String text); // // public Logger info(String text, Throwable t); // // public Logger info(Throwable t); // // public Logger warn(String text); // // public Logger warn(String text, Throwable t); // // public Logger warn(Throwable t); // // public Logger error(String text); // // public Logger error(String text, Throwable t); // // public Logger error(Throwable t); // // public Logger severe(String text); // // public Logger severe(String text, Throwable t); // // public Logger severe(Throwable t); // // public Logger fatal(String text); // // public Logger fatal(String text, Throwable t); // // public Logger fatal(Throwable t); // }
import java.io.IOException; import java.io.Writer; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.velocity.VelocityContext; import x.mvmn.gp2srv.web.service.velocity.TemplateEngine; import x.mvmn.lang.util.Provider; import x.mvmn.log.api.Logger;
package x.mvmn.gp2srv.web.servlets; public abstract class AbstractErrorHandlingServlet extends HttpServletWithTemplates { private static final long serialVersionUID = 8638499002251355635L; protected final Logger logger;
// Path: src/main/java/x/mvmn/gp2srv/web/service/velocity/TemplateEngine.java // public class TemplateEngine { // // public static final String DEFAULT_TEMPLATES_CLASSPATH_PREFIX = "/x/mvmn/gp2srv/web/templates/"; // // private final VelocityEngine engine; // private final String templatesClasspathPrefix; // // protected static class StaticToolsHelper { // // private static final Class<?> TOOLS[] = new Class<?>[] { DateHelper.class }; // // public static void populateTools(final Context context) { // for (final Class<?> toolClass : TOOLS) { // context.put("tool" + toolClass.getSimpleName(), toolClass); // } // } // } // // public TemplateEngine(Map<String, String> pathToTempalteMapping) { // this(DEFAULT_TEMPLATES_CLASSPATH_PREFIX, pathToTempalteMapping); // } // // public TemplateEngine(String templatesClasspathPrefix, Map<String, String> pathToTempalteMapping) { // this.templatesClasspathPrefix = templatesClasspathPrefix; // try { // initStringResourceRepository(pathToTempalteMapping); // engine = new VelocityEngine(getConfigurationAsProperties()); // } catch (Exception e) { // throw new RuntimeException("Failed in initialize Template Engine", e); // } // } // // private StringResourceRepository initStringResourceRepository(Map<String, String> pathToTempalteMapping) throws IOException { // StringResourceRepository result = new StringResourceRepositoryImpl(); // StringResourceLoader.setRepository(StringResourceLoader.REPOSITORY_NAME_DEFAULT, result); // registerResource(result, RuntimeConstants.VM_LIBRARY_DEFAULT, RuntimeConstants.VM_LIBRARY_DEFAULT); // for (Map.Entry<String, String> pathToTempalteMappingItem : pathToTempalteMapping.entrySet()) { // registerResource(result, pathToTempalteMappingItem.getKey(), pathToTempalteMappingItem.getValue()); // } // return result; // } // // private void registerResource(StringResourceRepository repo, String registeredName, String relativeClasspathRef) throws IOException { // String templateClasspathRef = templatesClasspathPrefix + relativeClasspathRef.replaceAll("\\.\\./", ""); // InputStream templateBodyInputStream = GPhoto2Server.class.getResourceAsStream(templateClasspathRef); // String templateBodyString = IOUtils.toString(templateBodyInputStream, "UTF-8"); // repo.putStringResource(registeredName, templateBodyString); // } // // private Properties getConfigurationAsProperties() { // Properties result = new Properties(); // // result.setProperty(RuntimeConstants.RESOURCE_LOADER, "string"); // result.setProperty(RuntimeConstants.VM_LIBRARY_AUTORELOAD, "false"); // result.setProperty(RuntimeConstants.VM_LIBRARY, RuntimeConstants.VM_LIBRARY_DEFAULT); // result.setProperty("string.resource.loader.class", StringResourceLoader.class.getName()); // result.setProperty("string.resource.loader.modificationCheckInterval", "0"); // result.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS, SystemLogChute.class.getName()); // // return result; // } // // public void renderTemplate(String tempalteName, String encoding, Context context, Writer output) { // StaticToolsHelper.populateTools(context); // engine.mergeTemplate(tempalteName, encoding, context, output); // } // } // // Path: src/main/java/x/mvmn/lang/util/Provider.java // public interface Provider<T> { // // public T provide(); // } // // Path: src/main/java/x/mvmn/log/api/Logger.java // public interface Logger { // // public static enum LogLevel { // TRACE, DEBUG, INFO, WARN, ERROR, SEVERE, FATAL // } // // public Logger setLevel(LogLevel level); // // public LogLevel getLevel(); // // public boolean shouldLog(LogLevel logLevel); // // public Logger log(LogLevel level, String text); // // public Logger log(LogLevel level, String text, Throwable t); // // public Logger log(LogLevel level, Throwable t); // // public Logger trace(String text); // // public Logger trace(String text, Throwable t); // // public Logger trace(Throwable t); // // public Logger debug(String text); // // public Logger debug(String text, Throwable t); // // public Logger debug(Throwable t); // // public Logger info(String text); // // public Logger info(String text, Throwable t); // // public Logger info(Throwable t); // // public Logger warn(String text); // // public Logger warn(String text, Throwable t); // // public Logger warn(Throwable t); // // public Logger error(String text); // // public Logger error(String text, Throwable t); // // public Logger error(Throwable t); // // public Logger severe(String text); // // public Logger severe(String text, Throwable t); // // public Logger severe(Throwable t); // // public Logger fatal(String text); // // public Logger fatal(String text, Throwable t); // // public Logger fatal(Throwable t); // } // Path: src/main/java/x/mvmn/gp2srv/web/servlets/AbstractErrorHandlingServlet.java import java.io.IOException; import java.io.Writer; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.velocity.VelocityContext; import x.mvmn.gp2srv.web.service.velocity.TemplateEngine; import x.mvmn.lang.util.Provider; import x.mvmn.log.api.Logger; package x.mvmn.gp2srv.web.servlets; public abstract class AbstractErrorHandlingServlet extends HttpServletWithTemplates { private static final long serialVersionUID = 8638499002251355635L; protected final Logger logger;
public AbstractErrorHandlingServlet(final Provider<TemplateEngine> templateEngineProvider, final Logger logger) {
mvmn/gp2srv
src/main/java/x/mvmn/gp2srv/web/servlets/AbstractErrorHandlingServlet.java
// Path: src/main/java/x/mvmn/gp2srv/web/service/velocity/TemplateEngine.java // public class TemplateEngine { // // public static final String DEFAULT_TEMPLATES_CLASSPATH_PREFIX = "/x/mvmn/gp2srv/web/templates/"; // // private final VelocityEngine engine; // private final String templatesClasspathPrefix; // // protected static class StaticToolsHelper { // // private static final Class<?> TOOLS[] = new Class<?>[] { DateHelper.class }; // // public static void populateTools(final Context context) { // for (final Class<?> toolClass : TOOLS) { // context.put("tool" + toolClass.getSimpleName(), toolClass); // } // } // } // // public TemplateEngine(Map<String, String> pathToTempalteMapping) { // this(DEFAULT_TEMPLATES_CLASSPATH_PREFIX, pathToTempalteMapping); // } // // public TemplateEngine(String templatesClasspathPrefix, Map<String, String> pathToTempalteMapping) { // this.templatesClasspathPrefix = templatesClasspathPrefix; // try { // initStringResourceRepository(pathToTempalteMapping); // engine = new VelocityEngine(getConfigurationAsProperties()); // } catch (Exception e) { // throw new RuntimeException("Failed in initialize Template Engine", e); // } // } // // private StringResourceRepository initStringResourceRepository(Map<String, String> pathToTempalteMapping) throws IOException { // StringResourceRepository result = new StringResourceRepositoryImpl(); // StringResourceLoader.setRepository(StringResourceLoader.REPOSITORY_NAME_DEFAULT, result); // registerResource(result, RuntimeConstants.VM_LIBRARY_DEFAULT, RuntimeConstants.VM_LIBRARY_DEFAULT); // for (Map.Entry<String, String> pathToTempalteMappingItem : pathToTempalteMapping.entrySet()) { // registerResource(result, pathToTempalteMappingItem.getKey(), pathToTempalteMappingItem.getValue()); // } // return result; // } // // private void registerResource(StringResourceRepository repo, String registeredName, String relativeClasspathRef) throws IOException { // String templateClasspathRef = templatesClasspathPrefix + relativeClasspathRef.replaceAll("\\.\\./", ""); // InputStream templateBodyInputStream = GPhoto2Server.class.getResourceAsStream(templateClasspathRef); // String templateBodyString = IOUtils.toString(templateBodyInputStream, "UTF-8"); // repo.putStringResource(registeredName, templateBodyString); // } // // private Properties getConfigurationAsProperties() { // Properties result = new Properties(); // // result.setProperty(RuntimeConstants.RESOURCE_LOADER, "string"); // result.setProperty(RuntimeConstants.VM_LIBRARY_AUTORELOAD, "false"); // result.setProperty(RuntimeConstants.VM_LIBRARY, RuntimeConstants.VM_LIBRARY_DEFAULT); // result.setProperty("string.resource.loader.class", StringResourceLoader.class.getName()); // result.setProperty("string.resource.loader.modificationCheckInterval", "0"); // result.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS, SystemLogChute.class.getName()); // // return result; // } // // public void renderTemplate(String tempalteName, String encoding, Context context, Writer output) { // StaticToolsHelper.populateTools(context); // engine.mergeTemplate(tempalteName, encoding, context, output); // } // } // // Path: src/main/java/x/mvmn/lang/util/Provider.java // public interface Provider<T> { // // public T provide(); // } // // Path: src/main/java/x/mvmn/log/api/Logger.java // public interface Logger { // // public static enum LogLevel { // TRACE, DEBUG, INFO, WARN, ERROR, SEVERE, FATAL // } // // public Logger setLevel(LogLevel level); // // public LogLevel getLevel(); // // public boolean shouldLog(LogLevel logLevel); // // public Logger log(LogLevel level, String text); // // public Logger log(LogLevel level, String text, Throwable t); // // public Logger log(LogLevel level, Throwable t); // // public Logger trace(String text); // // public Logger trace(String text, Throwable t); // // public Logger trace(Throwable t); // // public Logger debug(String text); // // public Logger debug(String text, Throwable t); // // public Logger debug(Throwable t); // // public Logger info(String text); // // public Logger info(String text, Throwable t); // // public Logger info(Throwable t); // // public Logger warn(String text); // // public Logger warn(String text, Throwable t); // // public Logger warn(Throwable t); // // public Logger error(String text); // // public Logger error(String text, Throwable t); // // public Logger error(Throwable t); // // public Logger severe(String text); // // public Logger severe(String text, Throwable t); // // public Logger severe(Throwable t); // // public Logger fatal(String text); // // public Logger fatal(String text, Throwable t); // // public Logger fatal(Throwable t); // }
import java.io.IOException; import java.io.Writer; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.velocity.VelocityContext; import x.mvmn.gp2srv.web.service.velocity.TemplateEngine; import x.mvmn.lang.util.Provider; import x.mvmn.log.api.Logger;
package x.mvmn.gp2srv.web.servlets; public abstract class AbstractErrorHandlingServlet extends HttpServletWithTemplates { private static final long serialVersionUID = 8638499002251355635L; protected final Logger logger;
// Path: src/main/java/x/mvmn/gp2srv/web/service/velocity/TemplateEngine.java // public class TemplateEngine { // // public static final String DEFAULT_TEMPLATES_CLASSPATH_PREFIX = "/x/mvmn/gp2srv/web/templates/"; // // private final VelocityEngine engine; // private final String templatesClasspathPrefix; // // protected static class StaticToolsHelper { // // private static final Class<?> TOOLS[] = new Class<?>[] { DateHelper.class }; // // public static void populateTools(final Context context) { // for (final Class<?> toolClass : TOOLS) { // context.put("tool" + toolClass.getSimpleName(), toolClass); // } // } // } // // public TemplateEngine(Map<String, String> pathToTempalteMapping) { // this(DEFAULT_TEMPLATES_CLASSPATH_PREFIX, pathToTempalteMapping); // } // // public TemplateEngine(String templatesClasspathPrefix, Map<String, String> pathToTempalteMapping) { // this.templatesClasspathPrefix = templatesClasspathPrefix; // try { // initStringResourceRepository(pathToTempalteMapping); // engine = new VelocityEngine(getConfigurationAsProperties()); // } catch (Exception e) { // throw new RuntimeException("Failed in initialize Template Engine", e); // } // } // // private StringResourceRepository initStringResourceRepository(Map<String, String> pathToTempalteMapping) throws IOException { // StringResourceRepository result = new StringResourceRepositoryImpl(); // StringResourceLoader.setRepository(StringResourceLoader.REPOSITORY_NAME_DEFAULT, result); // registerResource(result, RuntimeConstants.VM_LIBRARY_DEFAULT, RuntimeConstants.VM_LIBRARY_DEFAULT); // for (Map.Entry<String, String> pathToTempalteMappingItem : pathToTempalteMapping.entrySet()) { // registerResource(result, pathToTempalteMappingItem.getKey(), pathToTempalteMappingItem.getValue()); // } // return result; // } // // private void registerResource(StringResourceRepository repo, String registeredName, String relativeClasspathRef) throws IOException { // String templateClasspathRef = templatesClasspathPrefix + relativeClasspathRef.replaceAll("\\.\\./", ""); // InputStream templateBodyInputStream = GPhoto2Server.class.getResourceAsStream(templateClasspathRef); // String templateBodyString = IOUtils.toString(templateBodyInputStream, "UTF-8"); // repo.putStringResource(registeredName, templateBodyString); // } // // private Properties getConfigurationAsProperties() { // Properties result = new Properties(); // // result.setProperty(RuntimeConstants.RESOURCE_LOADER, "string"); // result.setProperty(RuntimeConstants.VM_LIBRARY_AUTORELOAD, "false"); // result.setProperty(RuntimeConstants.VM_LIBRARY, RuntimeConstants.VM_LIBRARY_DEFAULT); // result.setProperty("string.resource.loader.class", StringResourceLoader.class.getName()); // result.setProperty("string.resource.loader.modificationCheckInterval", "0"); // result.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS, SystemLogChute.class.getName()); // // return result; // } // // public void renderTemplate(String tempalteName, String encoding, Context context, Writer output) { // StaticToolsHelper.populateTools(context); // engine.mergeTemplate(tempalteName, encoding, context, output); // } // } // // Path: src/main/java/x/mvmn/lang/util/Provider.java // public interface Provider<T> { // // public T provide(); // } // // Path: src/main/java/x/mvmn/log/api/Logger.java // public interface Logger { // // public static enum LogLevel { // TRACE, DEBUG, INFO, WARN, ERROR, SEVERE, FATAL // } // // public Logger setLevel(LogLevel level); // // public LogLevel getLevel(); // // public boolean shouldLog(LogLevel logLevel); // // public Logger log(LogLevel level, String text); // // public Logger log(LogLevel level, String text, Throwable t); // // public Logger log(LogLevel level, Throwable t); // // public Logger trace(String text); // // public Logger trace(String text, Throwable t); // // public Logger trace(Throwable t); // // public Logger debug(String text); // // public Logger debug(String text, Throwable t); // // public Logger debug(Throwable t); // // public Logger info(String text); // // public Logger info(String text, Throwable t); // // public Logger info(Throwable t); // // public Logger warn(String text); // // public Logger warn(String text, Throwable t); // // public Logger warn(Throwable t); // // public Logger error(String text); // // public Logger error(String text, Throwable t); // // public Logger error(Throwable t); // // public Logger severe(String text); // // public Logger severe(String text, Throwable t); // // public Logger severe(Throwable t); // // public Logger fatal(String text); // // public Logger fatal(String text, Throwable t); // // public Logger fatal(Throwable t); // } // Path: src/main/java/x/mvmn/gp2srv/web/servlets/AbstractErrorHandlingServlet.java import java.io.IOException; import java.io.Writer; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.velocity.VelocityContext; import x.mvmn.gp2srv.web.service.velocity.TemplateEngine; import x.mvmn.lang.util.Provider; import x.mvmn.log.api.Logger; package x.mvmn.gp2srv.web.servlets; public abstract class AbstractErrorHandlingServlet extends HttpServletWithTemplates { private static final long serialVersionUID = 8638499002251355635L; protected final Logger logger;
public AbstractErrorHandlingServlet(final Provider<TemplateEngine> templateEngineProvider, final Logger logger) {
mvmn/gp2srv
src/main/java/x/mvmn/gp2srv/mock/service/impl/MockCameraServiceImpl.java
// Path: src/main/java/x/mvmn/gp2srv/camera/CameraProvider.java // public interface CameraProvider { // // public GP2Camera getCamera(); // // public boolean hasCamera(); // // public void setCamera(GP2Camera camera); // } // // Path: src/main/java/x/mvmn/gp2srv/camera/CameraService.java // public interface CameraService { // public void close(); // // public byte[] capturePreview(); // // public CameraService releaseCamera(); // // public CameraFileSystemEntryBean capture(); // // public CameraFileSystemEntryBean capture(GP2CameraCaptureType captureType); // // public String getSummary(); // // public GP2CameraEventType waitForSpecificEvent(int timeout, GP2CameraEventType expectedEventType); // // public GP2CameraEventType waitForEvent(int timeout); // // public List<CameraConfigEntryBean> getConfig(); // // public Map<String, CameraConfigEntryBean> getConfigAsMap(); // // public CameraService setConfig(CameraConfigEntryBean configEntry); // // public List<CameraFileSystemEntryBean> filesList(final String path, boolean includeFiles, boolean includeFolders, boolean recursive); // // public CameraService fileDelete(final String filePath, final String fileName); // // public byte[] fileGetContents(final String filePath, final String fileName); // // public byte[] fileGetThumb(final String filePath, final String fileName); // // public String downloadFile(final String cameraFilePath, final String cameraFileName, final File downloadFolder); // // public CameraProvider getCameraProvider(); // }
import java.awt.Dimension; import java.awt.Rectangle; import java.awt.Robot; import java.awt.Toolkit; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.File; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.TreeMap; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicInteger; import javax.imageio.ImageIO; import org.apache.commons.io.IOUtils; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import x.mvmn.gp2srv.camera.CameraProvider; import x.mvmn.gp2srv.camera.CameraService; import x.mvmn.gphoto2.jna.Gphoto2Library; import x.mvmn.jlibgphoto2.api.CameraConfigEntryBean; import x.mvmn.jlibgphoto2.api.CameraFileSystemEntryBean; import x.mvmn.jlibgphoto2.api.GP2Camera; import x.mvmn.jlibgphoto2.api.GP2Camera.GP2CameraCaptureType; import x.mvmn.jlibgphoto2.api.GP2Camera.GP2CameraEventType; import x.mvmn.jlibgphoto2.exception.GP2Exception;
package x.mvmn.gp2srv.mock.service.impl; public class MockCameraServiceImpl implements CameraService { protected volatile boolean closed = false; protected final Map<String, CameraConfigEntryBean> initialConfig; protected final Map<String, CameraConfigEntryBean> config = new ConcurrentHashMap<String, CameraConfigEntryBean>(); protected final Map<String, CameraFileSystemEntryBean> fsEntries = new ConcurrentHashMap<String, CameraFileSystemEntryBean>(); protected final AtomicInteger counter = new AtomicInteger(0); protected final byte[] mockPicture;
// Path: src/main/java/x/mvmn/gp2srv/camera/CameraProvider.java // public interface CameraProvider { // // public GP2Camera getCamera(); // // public boolean hasCamera(); // // public void setCamera(GP2Camera camera); // } // // Path: src/main/java/x/mvmn/gp2srv/camera/CameraService.java // public interface CameraService { // public void close(); // // public byte[] capturePreview(); // // public CameraService releaseCamera(); // // public CameraFileSystemEntryBean capture(); // // public CameraFileSystemEntryBean capture(GP2CameraCaptureType captureType); // // public String getSummary(); // // public GP2CameraEventType waitForSpecificEvent(int timeout, GP2CameraEventType expectedEventType); // // public GP2CameraEventType waitForEvent(int timeout); // // public List<CameraConfigEntryBean> getConfig(); // // public Map<String, CameraConfigEntryBean> getConfigAsMap(); // // public CameraService setConfig(CameraConfigEntryBean configEntry); // // public List<CameraFileSystemEntryBean> filesList(final String path, boolean includeFiles, boolean includeFolders, boolean recursive); // // public CameraService fileDelete(final String filePath, final String fileName); // // public byte[] fileGetContents(final String filePath, final String fileName); // // public byte[] fileGetThumb(final String filePath, final String fileName); // // public String downloadFile(final String cameraFilePath, final String cameraFileName, final File downloadFolder); // // public CameraProvider getCameraProvider(); // } // Path: src/main/java/x/mvmn/gp2srv/mock/service/impl/MockCameraServiceImpl.java import java.awt.Dimension; import java.awt.Rectangle; import java.awt.Robot; import java.awt.Toolkit; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.File; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.TreeMap; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicInteger; import javax.imageio.ImageIO; import org.apache.commons.io.IOUtils; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import x.mvmn.gp2srv.camera.CameraProvider; import x.mvmn.gp2srv.camera.CameraService; import x.mvmn.gphoto2.jna.Gphoto2Library; import x.mvmn.jlibgphoto2.api.CameraConfigEntryBean; import x.mvmn.jlibgphoto2.api.CameraFileSystemEntryBean; import x.mvmn.jlibgphoto2.api.GP2Camera; import x.mvmn.jlibgphoto2.api.GP2Camera.GP2CameraCaptureType; import x.mvmn.jlibgphoto2.api.GP2Camera.GP2CameraEventType; import x.mvmn.jlibgphoto2.exception.GP2Exception; package x.mvmn.gp2srv.mock.service.impl; public class MockCameraServiceImpl implements CameraService { protected volatile boolean closed = false; protected final Map<String, CameraConfigEntryBean> initialConfig; protected final Map<String, CameraConfigEntryBean> config = new ConcurrentHashMap<String, CameraConfigEntryBean>(); protected final Map<String, CameraFileSystemEntryBean> fsEntries = new ConcurrentHashMap<String, CameraFileSystemEntryBean>(); protected final AtomicInteger counter = new AtomicInteger(0); protected final byte[] mockPicture;
protected final CameraProvider cameraProviderMock;
mvmn/gp2srv
src/main/java/x/mvmn/gp2srv/web/servlets/ScriptExecutionReportingWebSocketServlet.java
// Path: src/main/java/x/mvmn/gp2srv/scripting/service/impl/ScriptExecutionServiceImpl.java // public class ScriptExecutionServiceImpl implements ScriptExecutionFinishListener { // // protected AtomicReference<ScriptExecution> currentExecution = new AtomicReference<ScriptExecution>(); // protected AtomicReference<ScriptExecution> latestFinishedExecution = new AtomicReference<ScriptExecution>(); // protected final JexlEngine engine = new JexlBuilder().create(); // // public static interface ScriptExecutionObserver { // public void onStart(ScriptExecution execution); // // public void preStep(ScriptExecution execution); // // public void postStep(ScriptExecution execution); // // public void onStop(ScriptExecution execution); // } // // public ScriptExecutionServiceImpl(Logger logger) { // } // // public ScriptExecution execute(final CameraService cameraService, final File imgDownloadPath, final Logger logger, final String scriptName, // final List<ScriptStep> script, final ScriptExecutionObserver scriptExecutionObserver) { // final ScriptExecution scriptExecution = new ScriptExecution(cameraService, imgDownloadPath, logger, scriptName, script, engine, scriptExecutionObserver, // this); // if (currentExecution.compareAndSet(null, scriptExecution)) { // new Thread(scriptExecution).start(); // return scriptExecution; // } else { // return null; // } // } // // public ScriptExecution getCurrentExecution() { // return currentExecution.get(); // } // // public ScriptExecution getLatestFinishedExecution() { // return latestFinishedExecution.get(); // } // // public void onFinish(ScriptExecution execution) { // currentExecution.set(null); // latestFinishedExecution.set(execution); // } // } // // Path: src/main/java/x/mvmn/log/api/Logger.java // public interface Logger { // // public static enum LogLevel { // TRACE, DEBUG, INFO, WARN, ERROR, SEVERE, FATAL // } // // public Logger setLevel(LogLevel level); // // public LogLevel getLevel(); // // public boolean shouldLog(LogLevel logLevel); // // public Logger log(LogLevel level, String text); // // public Logger log(LogLevel level, String text, Throwable t); // // public Logger log(LogLevel level, Throwable t); // // public Logger trace(String text); // // public Logger trace(String text, Throwable t); // // public Logger trace(Throwable t); // // public Logger debug(String text); // // public Logger debug(String text, Throwable t); // // public Logger debug(Throwable t); // // public Logger info(String text); // // public Logger info(String text, Throwable t); // // public Logger info(Throwable t); // // public Logger warn(String text); // // public Logger warn(String text, Throwable t); // // public Logger warn(Throwable t); // // public Logger error(String text); // // public Logger error(String text, Throwable t); // // public Logger error(Throwable t); // // public Logger severe(String text); // // public Logger severe(String text, Throwable t); // // public Logger severe(Throwable t); // // public Logger fatal(String text); // // public Logger fatal(String text, Throwable t); // // public Logger fatal(Throwable t); // } // // Path: src/main/java/x/mvmn/log/api/Logger.java // public static enum LogLevel { // TRACE, DEBUG, INFO, WARN, ERROR, SEVERE, FATAL // }
import org.eclipse.jetty.util.ConcurrentHashSet; import org.eclipse.jetty.websocket.api.Session; import org.eclipse.jetty.websocket.api.WebSocketListener; import org.eclipse.jetty.websocket.servlet.ServletUpgradeRequest; import org.eclipse.jetty.websocket.servlet.ServletUpgradeResponse; import org.eclipse.jetty.websocket.servlet.WebSocketCreator; import org.eclipse.jetty.websocket.servlet.WebSocketServlet; import org.eclipse.jetty.websocket.servlet.WebSocketServletFactory; import x.mvmn.gp2srv.scripting.service.impl.ScriptExecutionServiceImpl; import x.mvmn.log.api.Logger; import x.mvmn.log.api.Logger.LogLevel;
package x.mvmn.gp2srv.web.servlets; public class ScriptExecutionReportingWebSocketServlet extends WebSocketServlet { private static final long serialVersionUID = -373710150672137029L; protected static final ConcurrentHashSet<Session> WEB_SOCKET_SESSIONS = new ConcurrentHashSet<Session>(); public static void registerSession(Session session) { WEB_SOCKET_SESSIONS.add(session); } public static void deregisterSession(Session session) { WEB_SOCKET_SESSIONS.remove(session); }
// Path: src/main/java/x/mvmn/gp2srv/scripting/service/impl/ScriptExecutionServiceImpl.java // public class ScriptExecutionServiceImpl implements ScriptExecutionFinishListener { // // protected AtomicReference<ScriptExecution> currentExecution = new AtomicReference<ScriptExecution>(); // protected AtomicReference<ScriptExecution> latestFinishedExecution = new AtomicReference<ScriptExecution>(); // protected final JexlEngine engine = new JexlBuilder().create(); // // public static interface ScriptExecutionObserver { // public void onStart(ScriptExecution execution); // // public void preStep(ScriptExecution execution); // // public void postStep(ScriptExecution execution); // // public void onStop(ScriptExecution execution); // } // // public ScriptExecutionServiceImpl(Logger logger) { // } // // public ScriptExecution execute(final CameraService cameraService, final File imgDownloadPath, final Logger logger, final String scriptName, // final List<ScriptStep> script, final ScriptExecutionObserver scriptExecutionObserver) { // final ScriptExecution scriptExecution = new ScriptExecution(cameraService, imgDownloadPath, logger, scriptName, script, engine, scriptExecutionObserver, // this); // if (currentExecution.compareAndSet(null, scriptExecution)) { // new Thread(scriptExecution).start(); // return scriptExecution; // } else { // return null; // } // } // // public ScriptExecution getCurrentExecution() { // return currentExecution.get(); // } // // public ScriptExecution getLatestFinishedExecution() { // return latestFinishedExecution.get(); // } // // public void onFinish(ScriptExecution execution) { // currentExecution.set(null); // latestFinishedExecution.set(execution); // } // } // // Path: src/main/java/x/mvmn/log/api/Logger.java // public interface Logger { // // public static enum LogLevel { // TRACE, DEBUG, INFO, WARN, ERROR, SEVERE, FATAL // } // // public Logger setLevel(LogLevel level); // // public LogLevel getLevel(); // // public boolean shouldLog(LogLevel logLevel); // // public Logger log(LogLevel level, String text); // // public Logger log(LogLevel level, String text, Throwable t); // // public Logger log(LogLevel level, Throwable t); // // public Logger trace(String text); // // public Logger trace(String text, Throwable t); // // public Logger trace(Throwable t); // // public Logger debug(String text); // // public Logger debug(String text, Throwable t); // // public Logger debug(Throwable t); // // public Logger info(String text); // // public Logger info(String text, Throwable t); // // public Logger info(Throwable t); // // public Logger warn(String text); // // public Logger warn(String text, Throwable t); // // public Logger warn(Throwable t); // // public Logger error(String text); // // public Logger error(String text, Throwable t); // // public Logger error(Throwable t); // // public Logger severe(String text); // // public Logger severe(String text, Throwable t); // // public Logger severe(Throwable t); // // public Logger fatal(String text); // // public Logger fatal(String text, Throwable t); // // public Logger fatal(Throwable t); // } // // Path: src/main/java/x/mvmn/log/api/Logger.java // public static enum LogLevel { // TRACE, DEBUG, INFO, WARN, ERROR, SEVERE, FATAL // } // Path: src/main/java/x/mvmn/gp2srv/web/servlets/ScriptExecutionReportingWebSocketServlet.java import org.eclipse.jetty.util.ConcurrentHashSet; import org.eclipse.jetty.websocket.api.Session; import org.eclipse.jetty.websocket.api.WebSocketListener; import org.eclipse.jetty.websocket.servlet.ServletUpgradeRequest; import org.eclipse.jetty.websocket.servlet.ServletUpgradeResponse; import org.eclipse.jetty.websocket.servlet.WebSocketCreator; import org.eclipse.jetty.websocket.servlet.WebSocketServlet; import org.eclipse.jetty.websocket.servlet.WebSocketServletFactory; import x.mvmn.gp2srv.scripting.service.impl.ScriptExecutionServiceImpl; import x.mvmn.log.api.Logger; import x.mvmn.log.api.Logger.LogLevel; package x.mvmn.gp2srv.web.servlets; public class ScriptExecutionReportingWebSocketServlet extends WebSocketServlet { private static final long serialVersionUID = -373710150672137029L; protected static final ConcurrentHashSet<Session> WEB_SOCKET_SESSIONS = new ConcurrentHashSet<Session>(); public static void registerSession(Session session) { WEB_SOCKET_SESSIONS.add(session); } public static void deregisterSession(Session session) { WEB_SOCKET_SESSIONS.remove(session); }
private final Logger logger;
mvmn/gp2srv
src/main/java/x/mvmn/gp2srv/web/servlets/ScriptExecutionReportingWebSocketServlet.java
// Path: src/main/java/x/mvmn/gp2srv/scripting/service/impl/ScriptExecutionServiceImpl.java // public class ScriptExecutionServiceImpl implements ScriptExecutionFinishListener { // // protected AtomicReference<ScriptExecution> currentExecution = new AtomicReference<ScriptExecution>(); // protected AtomicReference<ScriptExecution> latestFinishedExecution = new AtomicReference<ScriptExecution>(); // protected final JexlEngine engine = new JexlBuilder().create(); // // public static interface ScriptExecutionObserver { // public void onStart(ScriptExecution execution); // // public void preStep(ScriptExecution execution); // // public void postStep(ScriptExecution execution); // // public void onStop(ScriptExecution execution); // } // // public ScriptExecutionServiceImpl(Logger logger) { // } // // public ScriptExecution execute(final CameraService cameraService, final File imgDownloadPath, final Logger logger, final String scriptName, // final List<ScriptStep> script, final ScriptExecutionObserver scriptExecutionObserver) { // final ScriptExecution scriptExecution = new ScriptExecution(cameraService, imgDownloadPath, logger, scriptName, script, engine, scriptExecutionObserver, // this); // if (currentExecution.compareAndSet(null, scriptExecution)) { // new Thread(scriptExecution).start(); // return scriptExecution; // } else { // return null; // } // } // // public ScriptExecution getCurrentExecution() { // return currentExecution.get(); // } // // public ScriptExecution getLatestFinishedExecution() { // return latestFinishedExecution.get(); // } // // public void onFinish(ScriptExecution execution) { // currentExecution.set(null); // latestFinishedExecution.set(execution); // } // } // // Path: src/main/java/x/mvmn/log/api/Logger.java // public interface Logger { // // public static enum LogLevel { // TRACE, DEBUG, INFO, WARN, ERROR, SEVERE, FATAL // } // // public Logger setLevel(LogLevel level); // // public LogLevel getLevel(); // // public boolean shouldLog(LogLevel logLevel); // // public Logger log(LogLevel level, String text); // // public Logger log(LogLevel level, String text, Throwable t); // // public Logger log(LogLevel level, Throwable t); // // public Logger trace(String text); // // public Logger trace(String text, Throwable t); // // public Logger trace(Throwable t); // // public Logger debug(String text); // // public Logger debug(String text, Throwable t); // // public Logger debug(Throwable t); // // public Logger info(String text); // // public Logger info(String text, Throwable t); // // public Logger info(Throwable t); // // public Logger warn(String text); // // public Logger warn(String text, Throwable t); // // public Logger warn(Throwable t); // // public Logger error(String text); // // public Logger error(String text, Throwable t); // // public Logger error(Throwable t); // // public Logger severe(String text); // // public Logger severe(String text, Throwable t); // // public Logger severe(Throwable t); // // public Logger fatal(String text); // // public Logger fatal(String text, Throwable t); // // public Logger fatal(Throwable t); // } // // Path: src/main/java/x/mvmn/log/api/Logger.java // public static enum LogLevel { // TRACE, DEBUG, INFO, WARN, ERROR, SEVERE, FATAL // }
import org.eclipse.jetty.util.ConcurrentHashSet; import org.eclipse.jetty.websocket.api.Session; import org.eclipse.jetty.websocket.api.WebSocketListener; import org.eclipse.jetty.websocket.servlet.ServletUpgradeRequest; import org.eclipse.jetty.websocket.servlet.ServletUpgradeResponse; import org.eclipse.jetty.websocket.servlet.WebSocketCreator; import org.eclipse.jetty.websocket.servlet.WebSocketServlet; import org.eclipse.jetty.websocket.servlet.WebSocketServletFactory; import x.mvmn.gp2srv.scripting.service.impl.ScriptExecutionServiceImpl; import x.mvmn.log.api.Logger; import x.mvmn.log.api.Logger.LogLevel;
package x.mvmn.gp2srv.web.servlets; public class ScriptExecutionReportingWebSocketServlet extends WebSocketServlet { private static final long serialVersionUID = -373710150672137029L; protected static final ConcurrentHashSet<Session> WEB_SOCKET_SESSIONS = new ConcurrentHashSet<Session>(); public static void registerSession(Session session) { WEB_SOCKET_SESSIONS.add(session); } public static void deregisterSession(Session session) { WEB_SOCKET_SESSIONS.remove(session); } private final Logger logger;
// Path: src/main/java/x/mvmn/gp2srv/scripting/service/impl/ScriptExecutionServiceImpl.java // public class ScriptExecutionServiceImpl implements ScriptExecutionFinishListener { // // protected AtomicReference<ScriptExecution> currentExecution = new AtomicReference<ScriptExecution>(); // protected AtomicReference<ScriptExecution> latestFinishedExecution = new AtomicReference<ScriptExecution>(); // protected final JexlEngine engine = new JexlBuilder().create(); // // public static interface ScriptExecutionObserver { // public void onStart(ScriptExecution execution); // // public void preStep(ScriptExecution execution); // // public void postStep(ScriptExecution execution); // // public void onStop(ScriptExecution execution); // } // // public ScriptExecutionServiceImpl(Logger logger) { // } // // public ScriptExecution execute(final CameraService cameraService, final File imgDownloadPath, final Logger logger, final String scriptName, // final List<ScriptStep> script, final ScriptExecutionObserver scriptExecutionObserver) { // final ScriptExecution scriptExecution = new ScriptExecution(cameraService, imgDownloadPath, logger, scriptName, script, engine, scriptExecutionObserver, // this); // if (currentExecution.compareAndSet(null, scriptExecution)) { // new Thread(scriptExecution).start(); // return scriptExecution; // } else { // return null; // } // } // // public ScriptExecution getCurrentExecution() { // return currentExecution.get(); // } // // public ScriptExecution getLatestFinishedExecution() { // return latestFinishedExecution.get(); // } // // public void onFinish(ScriptExecution execution) { // currentExecution.set(null); // latestFinishedExecution.set(execution); // } // } // // Path: src/main/java/x/mvmn/log/api/Logger.java // public interface Logger { // // public static enum LogLevel { // TRACE, DEBUG, INFO, WARN, ERROR, SEVERE, FATAL // } // // public Logger setLevel(LogLevel level); // // public LogLevel getLevel(); // // public boolean shouldLog(LogLevel logLevel); // // public Logger log(LogLevel level, String text); // // public Logger log(LogLevel level, String text, Throwable t); // // public Logger log(LogLevel level, Throwable t); // // public Logger trace(String text); // // public Logger trace(String text, Throwable t); // // public Logger trace(Throwable t); // // public Logger debug(String text); // // public Logger debug(String text, Throwable t); // // public Logger debug(Throwable t); // // public Logger info(String text); // // public Logger info(String text, Throwable t); // // public Logger info(Throwable t); // // public Logger warn(String text); // // public Logger warn(String text, Throwable t); // // public Logger warn(Throwable t); // // public Logger error(String text); // // public Logger error(String text, Throwable t); // // public Logger error(Throwable t); // // public Logger severe(String text); // // public Logger severe(String text, Throwable t); // // public Logger severe(Throwable t); // // public Logger fatal(String text); // // public Logger fatal(String text, Throwable t); // // public Logger fatal(Throwable t); // } // // Path: src/main/java/x/mvmn/log/api/Logger.java // public static enum LogLevel { // TRACE, DEBUG, INFO, WARN, ERROR, SEVERE, FATAL // } // Path: src/main/java/x/mvmn/gp2srv/web/servlets/ScriptExecutionReportingWebSocketServlet.java import org.eclipse.jetty.util.ConcurrentHashSet; import org.eclipse.jetty.websocket.api.Session; import org.eclipse.jetty.websocket.api.WebSocketListener; import org.eclipse.jetty.websocket.servlet.ServletUpgradeRequest; import org.eclipse.jetty.websocket.servlet.ServletUpgradeResponse; import org.eclipse.jetty.websocket.servlet.WebSocketCreator; import org.eclipse.jetty.websocket.servlet.WebSocketServlet; import org.eclipse.jetty.websocket.servlet.WebSocketServletFactory; import x.mvmn.gp2srv.scripting.service.impl.ScriptExecutionServiceImpl; import x.mvmn.log.api.Logger; import x.mvmn.log.api.Logger.LogLevel; package x.mvmn.gp2srv.web.servlets; public class ScriptExecutionReportingWebSocketServlet extends WebSocketServlet { private static final long serialVersionUID = -373710150672137029L; protected static final ConcurrentHashSet<Session> WEB_SOCKET_SESSIONS = new ConcurrentHashSet<Session>(); public static void registerSession(Session session) { WEB_SOCKET_SESSIONS.add(session); } public static void deregisterSession(Session session) { WEB_SOCKET_SESSIONS.remove(session); } private final Logger logger;
public ScriptExecutionReportingWebSocketServlet(ScriptExecutionServiceImpl scriptExecService, Logger logger) {
mvmn/gp2srv
src/main/java/x/mvmn/gp2srv/web/servlets/ScriptExecutionReportingWebSocketServlet.java
// Path: src/main/java/x/mvmn/gp2srv/scripting/service/impl/ScriptExecutionServiceImpl.java // public class ScriptExecutionServiceImpl implements ScriptExecutionFinishListener { // // protected AtomicReference<ScriptExecution> currentExecution = new AtomicReference<ScriptExecution>(); // protected AtomicReference<ScriptExecution> latestFinishedExecution = new AtomicReference<ScriptExecution>(); // protected final JexlEngine engine = new JexlBuilder().create(); // // public static interface ScriptExecutionObserver { // public void onStart(ScriptExecution execution); // // public void preStep(ScriptExecution execution); // // public void postStep(ScriptExecution execution); // // public void onStop(ScriptExecution execution); // } // // public ScriptExecutionServiceImpl(Logger logger) { // } // // public ScriptExecution execute(final CameraService cameraService, final File imgDownloadPath, final Logger logger, final String scriptName, // final List<ScriptStep> script, final ScriptExecutionObserver scriptExecutionObserver) { // final ScriptExecution scriptExecution = new ScriptExecution(cameraService, imgDownloadPath, logger, scriptName, script, engine, scriptExecutionObserver, // this); // if (currentExecution.compareAndSet(null, scriptExecution)) { // new Thread(scriptExecution).start(); // return scriptExecution; // } else { // return null; // } // } // // public ScriptExecution getCurrentExecution() { // return currentExecution.get(); // } // // public ScriptExecution getLatestFinishedExecution() { // return latestFinishedExecution.get(); // } // // public void onFinish(ScriptExecution execution) { // currentExecution.set(null); // latestFinishedExecution.set(execution); // } // } // // Path: src/main/java/x/mvmn/log/api/Logger.java // public interface Logger { // // public static enum LogLevel { // TRACE, DEBUG, INFO, WARN, ERROR, SEVERE, FATAL // } // // public Logger setLevel(LogLevel level); // // public LogLevel getLevel(); // // public boolean shouldLog(LogLevel logLevel); // // public Logger log(LogLevel level, String text); // // public Logger log(LogLevel level, String text, Throwable t); // // public Logger log(LogLevel level, Throwable t); // // public Logger trace(String text); // // public Logger trace(String text, Throwable t); // // public Logger trace(Throwable t); // // public Logger debug(String text); // // public Logger debug(String text, Throwable t); // // public Logger debug(Throwable t); // // public Logger info(String text); // // public Logger info(String text, Throwable t); // // public Logger info(Throwable t); // // public Logger warn(String text); // // public Logger warn(String text, Throwable t); // // public Logger warn(Throwable t); // // public Logger error(String text); // // public Logger error(String text, Throwable t); // // public Logger error(Throwable t); // // public Logger severe(String text); // // public Logger severe(String text, Throwable t); // // public Logger severe(Throwable t); // // public Logger fatal(String text); // // public Logger fatal(String text, Throwable t); // // public Logger fatal(Throwable t); // } // // Path: src/main/java/x/mvmn/log/api/Logger.java // public static enum LogLevel { // TRACE, DEBUG, INFO, WARN, ERROR, SEVERE, FATAL // }
import org.eclipse.jetty.util.ConcurrentHashSet; import org.eclipse.jetty.websocket.api.Session; import org.eclipse.jetty.websocket.api.WebSocketListener; import org.eclipse.jetty.websocket.servlet.ServletUpgradeRequest; import org.eclipse.jetty.websocket.servlet.ServletUpgradeResponse; import org.eclipse.jetty.websocket.servlet.WebSocketCreator; import org.eclipse.jetty.websocket.servlet.WebSocketServlet; import org.eclipse.jetty.websocket.servlet.WebSocketServletFactory; import x.mvmn.gp2srv.scripting.service.impl.ScriptExecutionServiceImpl; import x.mvmn.log.api.Logger; import x.mvmn.log.api.Logger.LogLevel;
@Override public void configure(WebSocketServletFactory factory) { factory.setCreator(new WebSocketCreator() { public Object createWebSocket(ServletUpgradeRequest req, ServletUpgradeResponse resp) { return new ScriptExecutionReportingWebSocket(logger); } }); } public static class ScriptExecutionReportingWebSocket implements WebSocketListener { private Session outbound; private final Logger logger; public ScriptExecutionReportingWebSocket(Logger logger) { this.logger = logger; } public void onWebSocketClose(int statusCode, String reason) { ScriptExecutionReportingWebSocketServlet.deregisterSession(outbound); this.outbound = null; } public void onWebSocketConnect(Session session) { this.outbound = session; ScriptExecutionReportingWebSocketServlet.registerSession(session); } public void onWebSocketError(Throwable cause) {
// Path: src/main/java/x/mvmn/gp2srv/scripting/service/impl/ScriptExecutionServiceImpl.java // public class ScriptExecutionServiceImpl implements ScriptExecutionFinishListener { // // protected AtomicReference<ScriptExecution> currentExecution = new AtomicReference<ScriptExecution>(); // protected AtomicReference<ScriptExecution> latestFinishedExecution = new AtomicReference<ScriptExecution>(); // protected final JexlEngine engine = new JexlBuilder().create(); // // public static interface ScriptExecutionObserver { // public void onStart(ScriptExecution execution); // // public void preStep(ScriptExecution execution); // // public void postStep(ScriptExecution execution); // // public void onStop(ScriptExecution execution); // } // // public ScriptExecutionServiceImpl(Logger logger) { // } // // public ScriptExecution execute(final CameraService cameraService, final File imgDownloadPath, final Logger logger, final String scriptName, // final List<ScriptStep> script, final ScriptExecutionObserver scriptExecutionObserver) { // final ScriptExecution scriptExecution = new ScriptExecution(cameraService, imgDownloadPath, logger, scriptName, script, engine, scriptExecutionObserver, // this); // if (currentExecution.compareAndSet(null, scriptExecution)) { // new Thread(scriptExecution).start(); // return scriptExecution; // } else { // return null; // } // } // // public ScriptExecution getCurrentExecution() { // return currentExecution.get(); // } // // public ScriptExecution getLatestFinishedExecution() { // return latestFinishedExecution.get(); // } // // public void onFinish(ScriptExecution execution) { // currentExecution.set(null); // latestFinishedExecution.set(execution); // } // } // // Path: src/main/java/x/mvmn/log/api/Logger.java // public interface Logger { // // public static enum LogLevel { // TRACE, DEBUG, INFO, WARN, ERROR, SEVERE, FATAL // } // // public Logger setLevel(LogLevel level); // // public LogLevel getLevel(); // // public boolean shouldLog(LogLevel logLevel); // // public Logger log(LogLevel level, String text); // // public Logger log(LogLevel level, String text, Throwable t); // // public Logger log(LogLevel level, Throwable t); // // public Logger trace(String text); // // public Logger trace(String text, Throwable t); // // public Logger trace(Throwable t); // // public Logger debug(String text); // // public Logger debug(String text, Throwable t); // // public Logger debug(Throwable t); // // public Logger info(String text); // // public Logger info(String text, Throwable t); // // public Logger info(Throwable t); // // public Logger warn(String text); // // public Logger warn(String text, Throwable t); // // public Logger warn(Throwable t); // // public Logger error(String text); // // public Logger error(String text, Throwable t); // // public Logger error(Throwable t); // // public Logger severe(String text); // // public Logger severe(String text, Throwable t); // // public Logger severe(Throwable t); // // public Logger fatal(String text); // // public Logger fatal(String text, Throwable t); // // public Logger fatal(Throwable t); // } // // Path: src/main/java/x/mvmn/log/api/Logger.java // public static enum LogLevel { // TRACE, DEBUG, INFO, WARN, ERROR, SEVERE, FATAL // } // Path: src/main/java/x/mvmn/gp2srv/web/servlets/ScriptExecutionReportingWebSocketServlet.java import org.eclipse.jetty.util.ConcurrentHashSet; import org.eclipse.jetty.websocket.api.Session; import org.eclipse.jetty.websocket.api.WebSocketListener; import org.eclipse.jetty.websocket.servlet.ServletUpgradeRequest; import org.eclipse.jetty.websocket.servlet.ServletUpgradeResponse; import org.eclipse.jetty.websocket.servlet.WebSocketCreator; import org.eclipse.jetty.websocket.servlet.WebSocketServlet; import org.eclipse.jetty.websocket.servlet.WebSocketServletFactory; import x.mvmn.gp2srv.scripting.service.impl.ScriptExecutionServiceImpl; import x.mvmn.log.api.Logger; import x.mvmn.log.api.Logger.LogLevel; @Override public void configure(WebSocketServletFactory factory) { factory.setCreator(new WebSocketCreator() { public Object createWebSocket(ServletUpgradeRequest req, ServletUpgradeResponse resp) { return new ScriptExecutionReportingWebSocket(logger); } }); } public static class ScriptExecutionReportingWebSocket implements WebSocketListener { private Session outbound; private final Logger logger; public ScriptExecutionReportingWebSocket(Logger logger) { this.logger = logger; } public void onWebSocketClose(int statusCode, String reason) { ScriptExecutionReportingWebSocketServlet.deregisterSession(outbound); this.outbound = null; } public void onWebSocketConnect(Session session) { this.outbound = session; ScriptExecutionReportingWebSocketServlet.registerSession(session); } public void onWebSocketError(Throwable cause) {
logger.log(LogLevel.ERROR, "WebSocket error occurred", cause);
mvmn/gp2srv
src/main/java/x/mvmn/gp2srv/web/servlets/HttpServletWithTemplates.java
// Path: src/main/java/x/mvmn/gp2srv/web/service/velocity/TemplateEngine.java // public class TemplateEngine { // // public static final String DEFAULT_TEMPLATES_CLASSPATH_PREFIX = "/x/mvmn/gp2srv/web/templates/"; // // private final VelocityEngine engine; // private final String templatesClasspathPrefix; // // protected static class StaticToolsHelper { // // private static final Class<?> TOOLS[] = new Class<?>[] { DateHelper.class }; // // public static void populateTools(final Context context) { // for (final Class<?> toolClass : TOOLS) { // context.put("tool" + toolClass.getSimpleName(), toolClass); // } // } // } // // public TemplateEngine(Map<String, String> pathToTempalteMapping) { // this(DEFAULT_TEMPLATES_CLASSPATH_PREFIX, pathToTempalteMapping); // } // // public TemplateEngine(String templatesClasspathPrefix, Map<String, String> pathToTempalteMapping) { // this.templatesClasspathPrefix = templatesClasspathPrefix; // try { // initStringResourceRepository(pathToTempalteMapping); // engine = new VelocityEngine(getConfigurationAsProperties()); // } catch (Exception e) { // throw new RuntimeException("Failed in initialize Template Engine", e); // } // } // // private StringResourceRepository initStringResourceRepository(Map<String, String> pathToTempalteMapping) throws IOException { // StringResourceRepository result = new StringResourceRepositoryImpl(); // StringResourceLoader.setRepository(StringResourceLoader.REPOSITORY_NAME_DEFAULT, result); // registerResource(result, RuntimeConstants.VM_LIBRARY_DEFAULT, RuntimeConstants.VM_LIBRARY_DEFAULT); // for (Map.Entry<String, String> pathToTempalteMappingItem : pathToTempalteMapping.entrySet()) { // registerResource(result, pathToTempalteMappingItem.getKey(), pathToTempalteMappingItem.getValue()); // } // return result; // } // // private void registerResource(StringResourceRepository repo, String registeredName, String relativeClasspathRef) throws IOException { // String templateClasspathRef = templatesClasspathPrefix + relativeClasspathRef.replaceAll("\\.\\./", ""); // InputStream templateBodyInputStream = GPhoto2Server.class.getResourceAsStream(templateClasspathRef); // String templateBodyString = IOUtils.toString(templateBodyInputStream, "UTF-8"); // repo.putStringResource(registeredName, templateBodyString); // } // // private Properties getConfigurationAsProperties() { // Properties result = new Properties(); // // result.setProperty(RuntimeConstants.RESOURCE_LOADER, "string"); // result.setProperty(RuntimeConstants.VM_LIBRARY_AUTORELOAD, "false"); // result.setProperty(RuntimeConstants.VM_LIBRARY, RuntimeConstants.VM_LIBRARY_DEFAULT); // result.setProperty("string.resource.loader.class", StringResourceLoader.class.getName()); // result.setProperty("string.resource.loader.modificationCheckInterval", "0"); // result.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS, SystemLogChute.class.getName()); // // return result; // } // // public void renderTemplate(String tempalteName, String encoding, Context context, Writer output) { // StaticToolsHelper.populateTools(context); // engine.mergeTemplate(tempalteName, encoding, context, output); // } // } // // Path: src/main/java/x/mvmn/lang/util/Provider.java // public interface Provider<T> { // // public T provide(); // } // // Path: src/main/java/x/mvmn/log/api/Logger.java // public interface Logger { // // public static enum LogLevel { // TRACE, DEBUG, INFO, WARN, ERROR, SEVERE, FATAL // } // // public Logger setLevel(LogLevel level); // // public LogLevel getLevel(); // // public boolean shouldLog(LogLevel logLevel); // // public Logger log(LogLevel level, String text); // // public Logger log(LogLevel level, String text, Throwable t); // // public Logger log(LogLevel level, Throwable t); // // public Logger trace(String text); // // public Logger trace(String text, Throwable t); // // public Logger trace(Throwable t); // // public Logger debug(String text); // // public Logger debug(String text, Throwable t); // // public Logger debug(Throwable t); // // public Logger info(String text); // // public Logger info(String text, Throwable t); // // public Logger info(Throwable t); // // public Logger warn(String text); // // public Logger warn(String text, Throwable t); // // public Logger warn(Throwable t); // // public Logger error(String text); // // public Logger error(String text, Throwable t); // // public Logger error(Throwable t); // // public Logger severe(String text); // // public Logger severe(String text, Throwable t); // // public Logger severe(Throwable t); // // public Logger fatal(String text); // // public Logger fatal(String text, Throwable t); // // public Logger fatal(Throwable t); // }
import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Writer; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.io.IOUtils; import org.apache.velocity.VelocityContext; import org.apache.velocity.context.Context; import com.google.gson.Gson; import x.mvmn.gp2srv.web.service.velocity.TemplateEngine; import x.mvmn.lang.util.Provider; import x.mvmn.log.api.Logger;
package x.mvmn.gp2srv.web.servlets; public abstract class HttpServletWithTemplates extends HttpServlet { private static final long serialVersionUID = -6614624652923805723L; protected static final Gson GSON = new Gson();
// Path: src/main/java/x/mvmn/gp2srv/web/service/velocity/TemplateEngine.java // public class TemplateEngine { // // public static final String DEFAULT_TEMPLATES_CLASSPATH_PREFIX = "/x/mvmn/gp2srv/web/templates/"; // // private final VelocityEngine engine; // private final String templatesClasspathPrefix; // // protected static class StaticToolsHelper { // // private static final Class<?> TOOLS[] = new Class<?>[] { DateHelper.class }; // // public static void populateTools(final Context context) { // for (final Class<?> toolClass : TOOLS) { // context.put("tool" + toolClass.getSimpleName(), toolClass); // } // } // } // // public TemplateEngine(Map<String, String> pathToTempalteMapping) { // this(DEFAULT_TEMPLATES_CLASSPATH_PREFIX, pathToTempalteMapping); // } // // public TemplateEngine(String templatesClasspathPrefix, Map<String, String> pathToTempalteMapping) { // this.templatesClasspathPrefix = templatesClasspathPrefix; // try { // initStringResourceRepository(pathToTempalteMapping); // engine = new VelocityEngine(getConfigurationAsProperties()); // } catch (Exception e) { // throw new RuntimeException("Failed in initialize Template Engine", e); // } // } // // private StringResourceRepository initStringResourceRepository(Map<String, String> pathToTempalteMapping) throws IOException { // StringResourceRepository result = new StringResourceRepositoryImpl(); // StringResourceLoader.setRepository(StringResourceLoader.REPOSITORY_NAME_DEFAULT, result); // registerResource(result, RuntimeConstants.VM_LIBRARY_DEFAULT, RuntimeConstants.VM_LIBRARY_DEFAULT); // for (Map.Entry<String, String> pathToTempalteMappingItem : pathToTempalteMapping.entrySet()) { // registerResource(result, pathToTempalteMappingItem.getKey(), pathToTempalteMappingItem.getValue()); // } // return result; // } // // private void registerResource(StringResourceRepository repo, String registeredName, String relativeClasspathRef) throws IOException { // String templateClasspathRef = templatesClasspathPrefix + relativeClasspathRef.replaceAll("\\.\\./", ""); // InputStream templateBodyInputStream = GPhoto2Server.class.getResourceAsStream(templateClasspathRef); // String templateBodyString = IOUtils.toString(templateBodyInputStream, "UTF-8"); // repo.putStringResource(registeredName, templateBodyString); // } // // private Properties getConfigurationAsProperties() { // Properties result = new Properties(); // // result.setProperty(RuntimeConstants.RESOURCE_LOADER, "string"); // result.setProperty(RuntimeConstants.VM_LIBRARY_AUTORELOAD, "false"); // result.setProperty(RuntimeConstants.VM_LIBRARY, RuntimeConstants.VM_LIBRARY_DEFAULT); // result.setProperty("string.resource.loader.class", StringResourceLoader.class.getName()); // result.setProperty("string.resource.loader.modificationCheckInterval", "0"); // result.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS, SystemLogChute.class.getName()); // // return result; // } // // public void renderTemplate(String tempalteName, String encoding, Context context, Writer output) { // StaticToolsHelper.populateTools(context); // engine.mergeTemplate(tempalteName, encoding, context, output); // } // } // // Path: src/main/java/x/mvmn/lang/util/Provider.java // public interface Provider<T> { // // public T provide(); // } // // Path: src/main/java/x/mvmn/log/api/Logger.java // public interface Logger { // // public static enum LogLevel { // TRACE, DEBUG, INFO, WARN, ERROR, SEVERE, FATAL // } // // public Logger setLevel(LogLevel level); // // public LogLevel getLevel(); // // public boolean shouldLog(LogLevel logLevel); // // public Logger log(LogLevel level, String text); // // public Logger log(LogLevel level, String text, Throwable t); // // public Logger log(LogLevel level, Throwable t); // // public Logger trace(String text); // // public Logger trace(String text, Throwable t); // // public Logger trace(Throwable t); // // public Logger debug(String text); // // public Logger debug(String text, Throwable t); // // public Logger debug(Throwable t); // // public Logger info(String text); // // public Logger info(String text, Throwable t); // // public Logger info(Throwable t); // // public Logger warn(String text); // // public Logger warn(String text, Throwable t); // // public Logger warn(Throwable t); // // public Logger error(String text); // // public Logger error(String text, Throwable t); // // public Logger error(Throwable t); // // public Logger severe(String text); // // public Logger severe(String text, Throwable t); // // public Logger severe(Throwable t); // // public Logger fatal(String text); // // public Logger fatal(String text, Throwable t); // // public Logger fatal(Throwable t); // } // Path: src/main/java/x/mvmn/gp2srv/web/servlets/HttpServletWithTemplates.java import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Writer; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.io.IOUtils; import org.apache.velocity.VelocityContext; import org.apache.velocity.context.Context; import com.google.gson.Gson; import x.mvmn.gp2srv.web.service.velocity.TemplateEngine; import x.mvmn.lang.util.Provider; import x.mvmn.log.api.Logger; package x.mvmn.gp2srv.web.servlets; public abstract class HttpServletWithTemplates extends HttpServlet { private static final long serialVersionUID = -6614624652923805723L; protected static final Gson GSON = new Gson();
protected final Provider<TemplateEngine> templateEngineProvider;
mvmn/gp2srv
src/main/java/x/mvmn/gp2srv/web/servlets/HttpServletWithTemplates.java
// Path: src/main/java/x/mvmn/gp2srv/web/service/velocity/TemplateEngine.java // public class TemplateEngine { // // public static final String DEFAULT_TEMPLATES_CLASSPATH_PREFIX = "/x/mvmn/gp2srv/web/templates/"; // // private final VelocityEngine engine; // private final String templatesClasspathPrefix; // // protected static class StaticToolsHelper { // // private static final Class<?> TOOLS[] = new Class<?>[] { DateHelper.class }; // // public static void populateTools(final Context context) { // for (final Class<?> toolClass : TOOLS) { // context.put("tool" + toolClass.getSimpleName(), toolClass); // } // } // } // // public TemplateEngine(Map<String, String> pathToTempalteMapping) { // this(DEFAULT_TEMPLATES_CLASSPATH_PREFIX, pathToTempalteMapping); // } // // public TemplateEngine(String templatesClasspathPrefix, Map<String, String> pathToTempalteMapping) { // this.templatesClasspathPrefix = templatesClasspathPrefix; // try { // initStringResourceRepository(pathToTempalteMapping); // engine = new VelocityEngine(getConfigurationAsProperties()); // } catch (Exception e) { // throw new RuntimeException("Failed in initialize Template Engine", e); // } // } // // private StringResourceRepository initStringResourceRepository(Map<String, String> pathToTempalteMapping) throws IOException { // StringResourceRepository result = new StringResourceRepositoryImpl(); // StringResourceLoader.setRepository(StringResourceLoader.REPOSITORY_NAME_DEFAULT, result); // registerResource(result, RuntimeConstants.VM_LIBRARY_DEFAULT, RuntimeConstants.VM_LIBRARY_DEFAULT); // for (Map.Entry<String, String> pathToTempalteMappingItem : pathToTempalteMapping.entrySet()) { // registerResource(result, pathToTempalteMappingItem.getKey(), pathToTempalteMappingItem.getValue()); // } // return result; // } // // private void registerResource(StringResourceRepository repo, String registeredName, String relativeClasspathRef) throws IOException { // String templateClasspathRef = templatesClasspathPrefix + relativeClasspathRef.replaceAll("\\.\\./", ""); // InputStream templateBodyInputStream = GPhoto2Server.class.getResourceAsStream(templateClasspathRef); // String templateBodyString = IOUtils.toString(templateBodyInputStream, "UTF-8"); // repo.putStringResource(registeredName, templateBodyString); // } // // private Properties getConfigurationAsProperties() { // Properties result = new Properties(); // // result.setProperty(RuntimeConstants.RESOURCE_LOADER, "string"); // result.setProperty(RuntimeConstants.VM_LIBRARY_AUTORELOAD, "false"); // result.setProperty(RuntimeConstants.VM_LIBRARY, RuntimeConstants.VM_LIBRARY_DEFAULT); // result.setProperty("string.resource.loader.class", StringResourceLoader.class.getName()); // result.setProperty("string.resource.loader.modificationCheckInterval", "0"); // result.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS, SystemLogChute.class.getName()); // // return result; // } // // public void renderTemplate(String tempalteName, String encoding, Context context, Writer output) { // StaticToolsHelper.populateTools(context); // engine.mergeTemplate(tempalteName, encoding, context, output); // } // } // // Path: src/main/java/x/mvmn/lang/util/Provider.java // public interface Provider<T> { // // public T provide(); // } // // Path: src/main/java/x/mvmn/log/api/Logger.java // public interface Logger { // // public static enum LogLevel { // TRACE, DEBUG, INFO, WARN, ERROR, SEVERE, FATAL // } // // public Logger setLevel(LogLevel level); // // public LogLevel getLevel(); // // public boolean shouldLog(LogLevel logLevel); // // public Logger log(LogLevel level, String text); // // public Logger log(LogLevel level, String text, Throwable t); // // public Logger log(LogLevel level, Throwable t); // // public Logger trace(String text); // // public Logger trace(String text, Throwable t); // // public Logger trace(Throwable t); // // public Logger debug(String text); // // public Logger debug(String text, Throwable t); // // public Logger debug(Throwable t); // // public Logger info(String text); // // public Logger info(String text, Throwable t); // // public Logger info(Throwable t); // // public Logger warn(String text); // // public Logger warn(String text, Throwable t); // // public Logger warn(Throwable t); // // public Logger error(String text); // // public Logger error(String text, Throwable t); // // public Logger error(Throwable t); // // public Logger severe(String text); // // public Logger severe(String text, Throwable t); // // public Logger severe(Throwable t); // // public Logger fatal(String text); // // public Logger fatal(String text, Throwable t); // // public Logger fatal(Throwable t); // }
import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Writer; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.io.IOUtils; import org.apache.velocity.VelocityContext; import org.apache.velocity.context.Context; import com.google.gson.Gson; import x.mvmn.gp2srv.web.service.velocity.TemplateEngine; import x.mvmn.lang.util.Provider; import x.mvmn.log.api.Logger;
package x.mvmn.gp2srv.web.servlets; public abstract class HttpServletWithTemplates extends HttpServlet { private static final long serialVersionUID = -6614624652923805723L; protected static final Gson GSON = new Gson();
// Path: src/main/java/x/mvmn/gp2srv/web/service/velocity/TemplateEngine.java // public class TemplateEngine { // // public static final String DEFAULT_TEMPLATES_CLASSPATH_PREFIX = "/x/mvmn/gp2srv/web/templates/"; // // private final VelocityEngine engine; // private final String templatesClasspathPrefix; // // protected static class StaticToolsHelper { // // private static final Class<?> TOOLS[] = new Class<?>[] { DateHelper.class }; // // public static void populateTools(final Context context) { // for (final Class<?> toolClass : TOOLS) { // context.put("tool" + toolClass.getSimpleName(), toolClass); // } // } // } // // public TemplateEngine(Map<String, String> pathToTempalteMapping) { // this(DEFAULT_TEMPLATES_CLASSPATH_PREFIX, pathToTempalteMapping); // } // // public TemplateEngine(String templatesClasspathPrefix, Map<String, String> pathToTempalteMapping) { // this.templatesClasspathPrefix = templatesClasspathPrefix; // try { // initStringResourceRepository(pathToTempalteMapping); // engine = new VelocityEngine(getConfigurationAsProperties()); // } catch (Exception e) { // throw new RuntimeException("Failed in initialize Template Engine", e); // } // } // // private StringResourceRepository initStringResourceRepository(Map<String, String> pathToTempalteMapping) throws IOException { // StringResourceRepository result = new StringResourceRepositoryImpl(); // StringResourceLoader.setRepository(StringResourceLoader.REPOSITORY_NAME_DEFAULT, result); // registerResource(result, RuntimeConstants.VM_LIBRARY_DEFAULT, RuntimeConstants.VM_LIBRARY_DEFAULT); // for (Map.Entry<String, String> pathToTempalteMappingItem : pathToTempalteMapping.entrySet()) { // registerResource(result, pathToTempalteMappingItem.getKey(), pathToTempalteMappingItem.getValue()); // } // return result; // } // // private void registerResource(StringResourceRepository repo, String registeredName, String relativeClasspathRef) throws IOException { // String templateClasspathRef = templatesClasspathPrefix + relativeClasspathRef.replaceAll("\\.\\./", ""); // InputStream templateBodyInputStream = GPhoto2Server.class.getResourceAsStream(templateClasspathRef); // String templateBodyString = IOUtils.toString(templateBodyInputStream, "UTF-8"); // repo.putStringResource(registeredName, templateBodyString); // } // // private Properties getConfigurationAsProperties() { // Properties result = new Properties(); // // result.setProperty(RuntimeConstants.RESOURCE_LOADER, "string"); // result.setProperty(RuntimeConstants.VM_LIBRARY_AUTORELOAD, "false"); // result.setProperty(RuntimeConstants.VM_LIBRARY, RuntimeConstants.VM_LIBRARY_DEFAULT); // result.setProperty("string.resource.loader.class", StringResourceLoader.class.getName()); // result.setProperty("string.resource.loader.modificationCheckInterval", "0"); // result.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS, SystemLogChute.class.getName()); // // return result; // } // // public void renderTemplate(String tempalteName, String encoding, Context context, Writer output) { // StaticToolsHelper.populateTools(context); // engine.mergeTemplate(tempalteName, encoding, context, output); // } // } // // Path: src/main/java/x/mvmn/lang/util/Provider.java // public interface Provider<T> { // // public T provide(); // } // // Path: src/main/java/x/mvmn/log/api/Logger.java // public interface Logger { // // public static enum LogLevel { // TRACE, DEBUG, INFO, WARN, ERROR, SEVERE, FATAL // } // // public Logger setLevel(LogLevel level); // // public LogLevel getLevel(); // // public boolean shouldLog(LogLevel logLevel); // // public Logger log(LogLevel level, String text); // // public Logger log(LogLevel level, String text, Throwable t); // // public Logger log(LogLevel level, Throwable t); // // public Logger trace(String text); // // public Logger trace(String text, Throwable t); // // public Logger trace(Throwable t); // // public Logger debug(String text); // // public Logger debug(String text, Throwable t); // // public Logger debug(Throwable t); // // public Logger info(String text); // // public Logger info(String text, Throwable t); // // public Logger info(Throwable t); // // public Logger warn(String text); // // public Logger warn(String text, Throwable t); // // public Logger warn(Throwable t); // // public Logger error(String text); // // public Logger error(String text, Throwable t); // // public Logger error(Throwable t); // // public Logger severe(String text); // // public Logger severe(String text, Throwable t); // // public Logger severe(Throwable t); // // public Logger fatal(String text); // // public Logger fatal(String text, Throwable t); // // public Logger fatal(Throwable t); // } // Path: src/main/java/x/mvmn/gp2srv/web/servlets/HttpServletWithTemplates.java import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Writer; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.io.IOUtils; import org.apache.velocity.VelocityContext; import org.apache.velocity.context.Context; import com.google.gson.Gson; import x.mvmn.gp2srv.web.service.velocity.TemplateEngine; import x.mvmn.lang.util.Provider; import x.mvmn.log.api.Logger; package x.mvmn.gp2srv.web.servlets; public abstract class HttpServletWithTemplates extends HttpServlet { private static final long serialVersionUID = -6614624652923805723L; protected static final Gson GSON = new Gson();
protected final Provider<TemplateEngine> templateEngineProvider;
MatejTymes/JavaFixes
src/test/java/javafixes/math/DecimalConstantsTest.java
// Path: src/main/java/javafixes/math/Decimal.java // public static Decimal d(long unscaledValue, int scale) throws ArithmeticException { // return decimal(unscaledValue, scale); // }
import org.junit.Test; import static javafixes.math.Decimal.d; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertThat;
package javafixes.math; public class DecimalConstantsTest { @Test public void shouldHaveCorrectConstants() {
// Path: src/main/java/javafixes/math/Decimal.java // public static Decimal d(long unscaledValue, int scale) throws ArithmeticException { // return decimal(unscaledValue, scale); // } // Path: src/test/java/javafixes/math/DecimalConstantsTest.java import org.junit.Test; import static javafixes.math.Decimal.d; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertThat; package javafixes.math; public class DecimalConstantsTest { @Test public void shouldHaveCorrectConstants() {
assertThat(Decimal.ZERO, equalTo(d("0")));
MatejTymes/JavaFixes
src/test/java/javafixes/math/PrecisionTest.java
// Path: src/main/java/javafixes/collection/CollectionUtil.java // @SafeVarargs // public static <T> ArrayList<T> newList(T... values) { // ArrayList<T> list = new ArrayList<T>(values.length); // Collections.addAll(list, values); // return list; // } // // Path: src/test/java/javafixes/test/Condition.java // @FunctionalInterface // public interface Condition<T> extends Function<T, Boolean> { // // BigInteger MIN_LONG_AS_BIG_INTEGER = BigInteger.valueOf(Long.MIN_VALUE); // BigInteger MAX_LONG_AS_BIG_INTEGER = BigInteger.valueOf(Long.MAX_VALUE); // // @SafeVarargs // static <T> Condition<T> otherThan(T... values) { // Set<T> exclusions = newSet(values); // return value -> !exclusions.contains(value); // } // // static <T extends Number> Condition<T> notDivisibleBy10() { // return value -> mod(value, 10) != 0; // } // // static <T extends Number> Condition<T> notZero() { // return value -> signum(value) != 0; // } // // static <T extends Number> Condition<T> positive() { // return value -> signum(value) == 1; // } // // static <T extends Number> Condition<T> negative() { // return value -> signum(value) == -1; // } // // static Condition<BigInteger> fitsIntoLong() { // return value -> value.compareTo(MIN_LONG_AS_BIG_INTEGER) >= 0 && value.compareTo(MAX_LONG_AS_BIG_INTEGER) <= 0; // } // // static Condition<BigInteger> notFitIntoLong() { // return value -> value.compareTo(MIN_LONG_AS_BIG_INTEGER) < 0 || value.compareTo(MIN_LONG_AS_BIG_INTEGER) > 0; // } // // static int signum(Number value) { // if (value instanceof Integer) { // return Integer.signum((Integer) value); // } else if (value instanceof Long) { // return Long.signum((Long) value); // } else if (value instanceof BigInteger) { // return ((BigInteger) value).signum(); // } else if (value instanceof BigDecimal) { // return ((BigDecimal) value).signum(); // } else { // throw new IllegalArgumentException("Unsupported number type: " + value.getClass()); // } // } // // static int mod(Number value, int divisor) { // if (value instanceof Integer) { // return ((Integer) value) % divisor; // } else if (value instanceof Long) { // return (int) (((Long) value) % divisor); // } else if (value instanceof BigInteger) { // return ((BigInteger) value).mod(BigInteger.valueOf(divisor)).intValue(); // } else { // throw new IllegalArgumentException("Unsupported number type: " + value.getClass()); // } // // } // } // // Path: src/test/java/javafixes/test/Random.java // @SafeVarargs // public static int randomInt(int from, int to, Function<Integer, Boolean>... validityConditions) { // return generateValidValue( // // typecast it to long as otherwise we could get int overflow // () -> (int) ((long) (Math.random() * ((long) to - (long) from + 1L)) + (long) from), // validityConditions // ); // }
import org.junit.Test; import static javafixes.collection.CollectionUtil.newList; import static javafixes.test.Condition.*; import static javafixes.test.Random.randomInt; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.not; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail;
package javafixes.math; public class PrecisionTest { @Test public void shouldCreatePrecisionWithPositiveValue() { assertThat(Precision.of(1).value, equalTo(1)); assertThat(Precision.precision(1).value, equalTo(1)); assertThat(Precision.of(Integer.MAX_VALUE).value, equalTo(Integer.MAX_VALUE)); assertThat(Precision.precision(Integer.MAX_VALUE).value, equalTo(Integer.MAX_VALUE));
// Path: src/main/java/javafixes/collection/CollectionUtil.java // @SafeVarargs // public static <T> ArrayList<T> newList(T... values) { // ArrayList<T> list = new ArrayList<T>(values.length); // Collections.addAll(list, values); // return list; // } // // Path: src/test/java/javafixes/test/Condition.java // @FunctionalInterface // public interface Condition<T> extends Function<T, Boolean> { // // BigInteger MIN_LONG_AS_BIG_INTEGER = BigInteger.valueOf(Long.MIN_VALUE); // BigInteger MAX_LONG_AS_BIG_INTEGER = BigInteger.valueOf(Long.MAX_VALUE); // // @SafeVarargs // static <T> Condition<T> otherThan(T... values) { // Set<T> exclusions = newSet(values); // return value -> !exclusions.contains(value); // } // // static <T extends Number> Condition<T> notDivisibleBy10() { // return value -> mod(value, 10) != 0; // } // // static <T extends Number> Condition<T> notZero() { // return value -> signum(value) != 0; // } // // static <T extends Number> Condition<T> positive() { // return value -> signum(value) == 1; // } // // static <T extends Number> Condition<T> negative() { // return value -> signum(value) == -1; // } // // static Condition<BigInteger> fitsIntoLong() { // return value -> value.compareTo(MIN_LONG_AS_BIG_INTEGER) >= 0 && value.compareTo(MAX_LONG_AS_BIG_INTEGER) <= 0; // } // // static Condition<BigInteger> notFitIntoLong() { // return value -> value.compareTo(MIN_LONG_AS_BIG_INTEGER) < 0 || value.compareTo(MIN_LONG_AS_BIG_INTEGER) > 0; // } // // static int signum(Number value) { // if (value instanceof Integer) { // return Integer.signum((Integer) value); // } else if (value instanceof Long) { // return Long.signum((Long) value); // } else if (value instanceof BigInteger) { // return ((BigInteger) value).signum(); // } else if (value instanceof BigDecimal) { // return ((BigDecimal) value).signum(); // } else { // throw new IllegalArgumentException("Unsupported number type: " + value.getClass()); // } // } // // static int mod(Number value, int divisor) { // if (value instanceof Integer) { // return ((Integer) value) % divisor; // } else if (value instanceof Long) { // return (int) (((Long) value) % divisor); // } else if (value instanceof BigInteger) { // return ((BigInteger) value).mod(BigInteger.valueOf(divisor)).intValue(); // } else { // throw new IllegalArgumentException("Unsupported number type: " + value.getClass()); // } // // } // } // // Path: src/test/java/javafixes/test/Random.java // @SafeVarargs // public static int randomInt(int from, int to, Function<Integer, Boolean>... validityConditions) { // return generateValidValue( // // typecast it to long as otherwise we could get int overflow // () -> (int) ((long) (Math.random() * ((long) to - (long) from + 1L)) + (long) from), // validityConditions // ); // } // Path: src/test/java/javafixes/math/PrecisionTest.java import org.junit.Test; import static javafixes.collection.CollectionUtil.newList; import static javafixes.test.Condition.*; import static javafixes.test.Random.randomInt; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.not; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; package javafixes.math; public class PrecisionTest { @Test public void shouldCreatePrecisionWithPositiveValue() { assertThat(Precision.of(1).value, equalTo(1)); assertThat(Precision.precision(1).value, equalTo(1)); assertThat(Precision.of(Integer.MAX_VALUE).value, equalTo(Integer.MAX_VALUE)); assertThat(Precision.precision(Integer.MAX_VALUE).value, equalTo(Integer.MAX_VALUE));
int positiveValue = randomInt(2, Integer.MAX_VALUE - 1);
MatejTymes/JavaFixes
src/test/java/javafixes/math/PrecisionTest.java
// Path: src/main/java/javafixes/collection/CollectionUtil.java // @SafeVarargs // public static <T> ArrayList<T> newList(T... values) { // ArrayList<T> list = new ArrayList<T>(values.length); // Collections.addAll(list, values); // return list; // } // // Path: src/test/java/javafixes/test/Condition.java // @FunctionalInterface // public interface Condition<T> extends Function<T, Boolean> { // // BigInteger MIN_LONG_AS_BIG_INTEGER = BigInteger.valueOf(Long.MIN_VALUE); // BigInteger MAX_LONG_AS_BIG_INTEGER = BigInteger.valueOf(Long.MAX_VALUE); // // @SafeVarargs // static <T> Condition<T> otherThan(T... values) { // Set<T> exclusions = newSet(values); // return value -> !exclusions.contains(value); // } // // static <T extends Number> Condition<T> notDivisibleBy10() { // return value -> mod(value, 10) != 0; // } // // static <T extends Number> Condition<T> notZero() { // return value -> signum(value) != 0; // } // // static <T extends Number> Condition<T> positive() { // return value -> signum(value) == 1; // } // // static <T extends Number> Condition<T> negative() { // return value -> signum(value) == -1; // } // // static Condition<BigInteger> fitsIntoLong() { // return value -> value.compareTo(MIN_LONG_AS_BIG_INTEGER) >= 0 && value.compareTo(MAX_LONG_AS_BIG_INTEGER) <= 0; // } // // static Condition<BigInteger> notFitIntoLong() { // return value -> value.compareTo(MIN_LONG_AS_BIG_INTEGER) < 0 || value.compareTo(MIN_LONG_AS_BIG_INTEGER) > 0; // } // // static int signum(Number value) { // if (value instanceof Integer) { // return Integer.signum((Integer) value); // } else if (value instanceof Long) { // return Long.signum((Long) value); // } else if (value instanceof BigInteger) { // return ((BigInteger) value).signum(); // } else if (value instanceof BigDecimal) { // return ((BigDecimal) value).signum(); // } else { // throw new IllegalArgumentException("Unsupported number type: " + value.getClass()); // } // } // // static int mod(Number value, int divisor) { // if (value instanceof Integer) { // return ((Integer) value) % divisor; // } else if (value instanceof Long) { // return (int) (((Long) value) % divisor); // } else if (value instanceof BigInteger) { // return ((BigInteger) value).mod(BigInteger.valueOf(divisor)).intValue(); // } else { // throw new IllegalArgumentException("Unsupported number type: " + value.getClass()); // } // // } // } // // Path: src/test/java/javafixes/test/Random.java // @SafeVarargs // public static int randomInt(int from, int to, Function<Integer, Boolean>... validityConditions) { // return generateValidValue( // // typecast it to long as otherwise we could get int overflow // () -> (int) ((long) (Math.random() * ((long) to - (long) from + 1L)) + (long) from), // validityConditions // ); // }
import org.junit.Test; import static javafixes.collection.CollectionUtil.newList; import static javafixes.test.Condition.*; import static javafixes.test.Random.randomInt; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.not; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail;
package javafixes.math; public class PrecisionTest { @Test public void shouldCreatePrecisionWithPositiveValue() { assertThat(Precision.of(1).value, equalTo(1)); assertThat(Precision.precision(1).value, equalTo(1)); assertThat(Precision.of(Integer.MAX_VALUE).value, equalTo(Integer.MAX_VALUE)); assertThat(Precision.precision(Integer.MAX_VALUE).value, equalTo(Integer.MAX_VALUE)); int positiveValue = randomInt(2, Integer.MAX_VALUE - 1); assertThat(Precision.of(positiveValue).value, equalTo(positiveValue)); assertThat(Precision.precision(positiveValue).value, equalTo(positiveValue)); } @Test public void shouldFailWhenCreatingZeroDigitPrecision() { try { Precision.of(0); fail("zero precision should fail with IllegalArgumentException"); } catch (IllegalArgumentException expected) { // expected } try { Precision.precision(0); fail("zero precision should fail with IllegalArgumentException"); } catch (IllegalArgumentException expected) { // expected } } @Test public void shouldFailWhenCreatingNegativeDigitPrecision() {
// Path: src/main/java/javafixes/collection/CollectionUtil.java // @SafeVarargs // public static <T> ArrayList<T> newList(T... values) { // ArrayList<T> list = new ArrayList<T>(values.length); // Collections.addAll(list, values); // return list; // } // // Path: src/test/java/javafixes/test/Condition.java // @FunctionalInterface // public interface Condition<T> extends Function<T, Boolean> { // // BigInteger MIN_LONG_AS_BIG_INTEGER = BigInteger.valueOf(Long.MIN_VALUE); // BigInteger MAX_LONG_AS_BIG_INTEGER = BigInteger.valueOf(Long.MAX_VALUE); // // @SafeVarargs // static <T> Condition<T> otherThan(T... values) { // Set<T> exclusions = newSet(values); // return value -> !exclusions.contains(value); // } // // static <T extends Number> Condition<T> notDivisibleBy10() { // return value -> mod(value, 10) != 0; // } // // static <T extends Number> Condition<T> notZero() { // return value -> signum(value) != 0; // } // // static <T extends Number> Condition<T> positive() { // return value -> signum(value) == 1; // } // // static <T extends Number> Condition<T> negative() { // return value -> signum(value) == -1; // } // // static Condition<BigInteger> fitsIntoLong() { // return value -> value.compareTo(MIN_LONG_AS_BIG_INTEGER) >= 0 && value.compareTo(MAX_LONG_AS_BIG_INTEGER) <= 0; // } // // static Condition<BigInteger> notFitIntoLong() { // return value -> value.compareTo(MIN_LONG_AS_BIG_INTEGER) < 0 || value.compareTo(MIN_LONG_AS_BIG_INTEGER) > 0; // } // // static int signum(Number value) { // if (value instanceof Integer) { // return Integer.signum((Integer) value); // } else if (value instanceof Long) { // return Long.signum((Long) value); // } else if (value instanceof BigInteger) { // return ((BigInteger) value).signum(); // } else if (value instanceof BigDecimal) { // return ((BigDecimal) value).signum(); // } else { // throw new IllegalArgumentException("Unsupported number type: " + value.getClass()); // } // } // // static int mod(Number value, int divisor) { // if (value instanceof Integer) { // return ((Integer) value) % divisor; // } else if (value instanceof Long) { // return (int) (((Long) value) % divisor); // } else if (value instanceof BigInteger) { // return ((BigInteger) value).mod(BigInteger.valueOf(divisor)).intValue(); // } else { // throw new IllegalArgumentException("Unsupported number type: " + value.getClass()); // } // // } // } // // Path: src/test/java/javafixes/test/Random.java // @SafeVarargs // public static int randomInt(int from, int to, Function<Integer, Boolean>... validityConditions) { // return generateValidValue( // // typecast it to long as otherwise we could get int overflow // () -> (int) ((long) (Math.random() * ((long) to - (long) from + 1L)) + (long) from), // validityConditions // ); // } // Path: src/test/java/javafixes/math/PrecisionTest.java import org.junit.Test; import static javafixes.collection.CollectionUtil.newList; import static javafixes.test.Condition.*; import static javafixes.test.Random.randomInt; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.not; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; package javafixes.math; public class PrecisionTest { @Test public void shouldCreatePrecisionWithPositiveValue() { assertThat(Precision.of(1).value, equalTo(1)); assertThat(Precision.precision(1).value, equalTo(1)); assertThat(Precision.of(Integer.MAX_VALUE).value, equalTo(Integer.MAX_VALUE)); assertThat(Precision.precision(Integer.MAX_VALUE).value, equalTo(Integer.MAX_VALUE)); int positiveValue = randomInt(2, Integer.MAX_VALUE - 1); assertThat(Precision.of(positiveValue).value, equalTo(positiveValue)); assertThat(Precision.precision(positiveValue).value, equalTo(positiveValue)); } @Test public void shouldFailWhenCreatingZeroDigitPrecision() { try { Precision.of(0); fail("zero precision should fail with IllegalArgumentException"); } catch (IllegalArgumentException expected) { // expected } try { Precision.precision(0); fail("zero precision should fail with IllegalArgumentException"); } catch (IllegalArgumentException expected) { // expected } } @Test public void shouldFailWhenCreatingNegativeDigitPrecision() {
for (int value : newList(-1, Integer.MIN_VALUE, randomInt(Integer.MIN_VALUE + 1, -2))) {
MatejTymes/JavaFixes
src/test/java/javafixes/math/LongUtilTest.java
// Path: src/test/java/javafixes/test/Random.java // @SafeVarargs // public static long randomLong(long from, long to, Function<Long, Boolean>... validityConditions) { // return generateValidValue( // // () -> new RandomDataGenerator().nextLong(from, to), // () -> ThreadLocalRandom.current().nextLong(from, to) + (long) randomInt(0, 1), // validityConditions // ); // }
import org.junit.Test; import static javafixes.test.Random.randomLong; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat;
package javafixes.math; public class LongUtilTest { @Test public void shouldFindOutLongCanFitIntoInt() { assertThat(LongUtil.canFitIntoInt((long) Integer.MIN_VALUE), is(true)); assertThat(LongUtil.canFitIntoInt((long) Integer.MAX_VALUE), is(true)); assertThat(LongUtil.canFitIntoInt(-1L), is(true)); assertThat(LongUtil.canFitIntoInt(0L), is(true)); assertThat(LongUtil.canFitIntoInt(1L), is(true));
// Path: src/test/java/javafixes/test/Random.java // @SafeVarargs // public static long randomLong(long from, long to, Function<Long, Boolean>... validityConditions) { // return generateValidValue( // // () -> new RandomDataGenerator().nextLong(from, to), // () -> ThreadLocalRandom.current().nextLong(from, to) + (long) randomInt(0, 1), // validityConditions // ); // } // Path: src/test/java/javafixes/math/LongUtilTest.java import org.junit.Test; import static javafixes.test.Random.randomLong; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; package javafixes.math; public class LongUtilTest { @Test public void shouldFindOutLongCanFitIntoInt() { assertThat(LongUtil.canFitIntoInt((long) Integer.MIN_VALUE), is(true)); assertThat(LongUtil.canFitIntoInt((long) Integer.MAX_VALUE), is(true)); assertThat(LongUtil.canFitIntoInt(-1L), is(true)); assertThat(LongUtil.canFitIntoInt(0L), is(true)); assertThat(LongUtil.canFitIntoInt(1L), is(true));
assertThat(LongUtil.canFitIntoInt(randomLong(Integer.MIN_VALUE + 1, -2)), is(true));
MatejTymes/JavaFixes
src/main/java/javafixes/concurrency/MonitoringTaskSubmitter.java
// Path: src/main/java/javafixes/common/function/Task.java // @FunctionalInterface // public interface Task { // // /** // * Executes a task or throws an exception if unable to do so. // * // * @throws Exception if unable to execute task // * @see Runner // * @see MonitoringTaskSubmitter // */ // void run() throws Exception; // }
import javafixes.common.function.Task; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicInteger;
package javafixes.concurrency; /** * A wrapper around {@link java.util.concurrent.ScheduledExecutorService ScheduledExecutorService} * that allows you to monitor the number of submitted, failed and succeeded task, plus has the * ability to wait until all tasks scheduled trough {@code MonitoringTaskSubmitter} are completed * = there are no scheduled or running tasks. * * @author mtymes * @since 10/22/14 10:41 PM */ public class MonitoringTaskSubmitter { protected final Logger logger = LoggerFactory.getLogger(this.getClass()); private final AtomicInteger failedToSubmit = new AtomicInteger(0); private final AtomicInteger succeeded = new AtomicInteger(0); private final AtomicInteger failed = new AtomicInteger(0); protected final ReusableCountLatch latch = new ReusableCountLatch(); protected final ScheduledExecutorService executor; /** * @param executor executor that will be used to execute tasks */ public MonitoringTaskSubmitter(ScheduledExecutorService executor) { this.executor = executor; } /** * Schedules a {@link Callable} for immediate execution. * It might be executed later though if the {@link ScheduledExecutorService} has no available threads * or more tasks are queued for execution before this task. * * @param callable {@link Callable} to be executed * @param <T> type of return value * @return {@link Future} referring to the state of submitted {@link Callable} */ public <T> Future<T> run(Callable<T> callable) { return submit(asMonitoredCallable(callable)); } /** * Schedules a {@link Task} for immediate execution * It might be executed later though if the {@link ScheduledExecutorService} has no available threads * or more tasks are queued for execution before this task. * * @param task {@link Task} to be executed * @return {@link Future} referring to the state of submitted {@link Task} */
// Path: src/main/java/javafixes/common/function/Task.java // @FunctionalInterface // public interface Task { // // /** // * Executes a task or throws an exception if unable to do so. // * // * @throws Exception if unable to execute task // * @see Runner // * @see MonitoringTaskSubmitter // */ // void run() throws Exception; // } // Path: src/main/java/javafixes/concurrency/MonitoringTaskSubmitter.java import javafixes.common.function.Task; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicInteger; package javafixes.concurrency; /** * A wrapper around {@link java.util.concurrent.ScheduledExecutorService ScheduledExecutorService} * that allows you to monitor the number of submitted, failed and succeeded task, plus has the * ability to wait until all tasks scheduled trough {@code MonitoringTaskSubmitter} are completed * = there are no scheduled or running tasks. * * @author mtymes * @since 10/22/14 10:41 PM */ public class MonitoringTaskSubmitter { protected final Logger logger = LoggerFactory.getLogger(this.getClass()); private final AtomicInteger failedToSubmit = new AtomicInteger(0); private final AtomicInteger succeeded = new AtomicInteger(0); private final AtomicInteger failed = new AtomicInteger(0); protected final ReusableCountLatch latch = new ReusableCountLatch(); protected final ScheduledExecutorService executor; /** * @param executor executor that will be used to execute tasks */ public MonitoringTaskSubmitter(ScheduledExecutorService executor) { this.executor = executor; } /** * Schedules a {@link Callable} for immediate execution. * It might be executed later though if the {@link ScheduledExecutorService} has no available threads * or more tasks are queued for execution before this task. * * @param callable {@link Callable} to be executed * @param <T> type of return value * @return {@link Future} referring to the state of submitted {@link Callable} */ public <T> Future<T> run(Callable<T> callable) { return submit(asMonitoredCallable(callable)); } /** * Schedules a {@link Task} for immediate execution * It might be executed later though if the {@link ScheduledExecutorService} has no available threads * or more tasks are queued for execution before this task. * * @param task {@link Task} to be executed * @return {@link Future} referring to the state of submitted {@link Task} */
public Future<Void> run(Task task) {
MatejTymes/JavaFixes
src/test/java/javafixes/math/BigIntegerUtilTest.java
// Path: src/main/java/javafixes/math/BigIntegerUtil.java // static boolean canConvertToLong(BigInteger unscaledValue) { // return unscaledValue.compareTo(MAX_LONG_AS_BIG_INTEGER) <= 0 && unscaledValue.compareTo(MIN_LONG_AS_BIG_INTEGER) >= 0; // } // // Path: src/test/java/javafixes/test/Random.java // @SafeVarargs // public static long randomLong(long from, long to, Function<Long, Boolean>... validityConditions) { // return generateValidValue( // // () -> new RandomDataGenerator().nextLong(from, to), // () -> ThreadLocalRandom.current().nextLong(from, to) + (long) randomInt(0, 1), // validityConditions // ); // }
import org.junit.Test; import java.math.BigInteger; import static javafixes.math.BigIntegerUtil.canConvertToLong; import static javafixes.test.Random.randomLong; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat;
package javafixes.math; public class BigIntegerUtilTest { @Test public void shouldFindIfCanConvertBigIntegerToLong() {
// Path: src/main/java/javafixes/math/BigIntegerUtil.java // static boolean canConvertToLong(BigInteger unscaledValue) { // return unscaledValue.compareTo(MAX_LONG_AS_BIG_INTEGER) <= 0 && unscaledValue.compareTo(MIN_LONG_AS_BIG_INTEGER) >= 0; // } // // Path: src/test/java/javafixes/test/Random.java // @SafeVarargs // public static long randomLong(long from, long to, Function<Long, Boolean>... validityConditions) { // return generateValidValue( // // () -> new RandomDataGenerator().nextLong(from, to), // () -> ThreadLocalRandom.current().nextLong(from, to) + (long) randomInt(0, 1), // validityConditions // ); // } // Path: src/test/java/javafixes/math/BigIntegerUtilTest.java import org.junit.Test; import java.math.BigInteger; import static javafixes.math.BigIntegerUtil.canConvertToLong; import static javafixes.test.Random.randomLong; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; package javafixes.math; public class BigIntegerUtilTest { @Test public void shouldFindIfCanConvertBigIntegerToLong() {
assertThat(canConvertToLong(BigInteger.valueOf(Long.MAX_VALUE)), is(true));
MatejTymes/JavaFixes
src/test/java/javafixes/math/BigIntegerUtilTest.java
// Path: src/main/java/javafixes/math/BigIntegerUtil.java // static boolean canConvertToLong(BigInteger unscaledValue) { // return unscaledValue.compareTo(MAX_LONG_AS_BIG_INTEGER) <= 0 && unscaledValue.compareTo(MIN_LONG_AS_BIG_INTEGER) >= 0; // } // // Path: src/test/java/javafixes/test/Random.java // @SafeVarargs // public static long randomLong(long from, long to, Function<Long, Boolean>... validityConditions) { // return generateValidValue( // // () -> new RandomDataGenerator().nextLong(from, to), // () -> ThreadLocalRandom.current().nextLong(from, to) + (long) randomInt(0, 1), // validityConditions // ); // }
import org.junit.Test; import java.math.BigInteger; import static javafixes.math.BigIntegerUtil.canConvertToLong; import static javafixes.test.Random.randomLong; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat;
package javafixes.math; public class BigIntegerUtilTest { @Test public void shouldFindIfCanConvertBigIntegerToLong() { assertThat(canConvertToLong(BigInteger.valueOf(Long.MAX_VALUE)), is(true)); assertThat(canConvertToLong(BigInteger.valueOf(Long.MIN_VALUE)), is(true));
// Path: src/main/java/javafixes/math/BigIntegerUtil.java // static boolean canConvertToLong(BigInteger unscaledValue) { // return unscaledValue.compareTo(MAX_LONG_AS_BIG_INTEGER) <= 0 && unscaledValue.compareTo(MIN_LONG_AS_BIG_INTEGER) >= 0; // } // // Path: src/test/java/javafixes/test/Random.java // @SafeVarargs // public static long randomLong(long from, long to, Function<Long, Boolean>... validityConditions) { // return generateValidValue( // // () -> new RandomDataGenerator().nextLong(from, to), // () -> ThreadLocalRandom.current().nextLong(from, to) + (long) randomInt(0, 1), // validityConditions // ); // } // Path: src/test/java/javafixes/math/BigIntegerUtilTest.java import org.junit.Test; import java.math.BigInteger; import static javafixes.math.BigIntegerUtil.canConvertToLong; import static javafixes.test.Random.randomLong; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; package javafixes.math; public class BigIntegerUtilTest { @Test public void shouldFindIfCanConvertBigIntegerToLong() { assertThat(canConvertToLong(BigInteger.valueOf(Long.MAX_VALUE)), is(true)); assertThat(canConvertToLong(BigInteger.valueOf(Long.MIN_VALUE)), is(true));
assertThat(canConvertToLong(BigInteger.valueOf(randomLong())), is(true));
MatejTymes/JavaFixes
src/test/java/javafixes/math/DecimalNumberConversionTest.java
// Path: src/main/java/javafixes/collection/CollectionUtil.java // @SafeVarargs // public static <T> ArrayList<T> newList(T... values) { // ArrayList<T> list = new ArrayList<T>(values.length); // Collections.addAll(list, values); // return list; // } // // Path: src/test/java/javafixes/test/Condition.java // @FunctionalInterface // public interface Condition<T> extends Function<T, Boolean> { // // BigInteger MIN_LONG_AS_BIG_INTEGER = BigInteger.valueOf(Long.MIN_VALUE); // BigInteger MAX_LONG_AS_BIG_INTEGER = BigInteger.valueOf(Long.MAX_VALUE); // // @SafeVarargs // static <T> Condition<T> otherThan(T... values) { // Set<T> exclusions = newSet(values); // return value -> !exclusions.contains(value); // } // // static <T extends Number> Condition<T> notDivisibleBy10() { // return value -> mod(value, 10) != 0; // } // // static <T extends Number> Condition<T> notZero() { // return value -> signum(value) != 0; // } // // static <T extends Number> Condition<T> positive() { // return value -> signum(value) == 1; // } // // static <T extends Number> Condition<T> negative() { // return value -> signum(value) == -1; // } // // static Condition<BigInteger> fitsIntoLong() { // return value -> value.compareTo(MIN_LONG_AS_BIG_INTEGER) >= 0 && value.compareTo(MAX_LONG_AS_BIG_INTEGER) <= 0; // } // // static Condition<BigInteger> notFitIntoLong() { // return value -> value.compareTo(MIN_LONG_AS_BIG_INTEGER) < 0 || value.compareTo(MIN_LONG_AS_BIG_INTEGER) > 0; // } // // static int signum(Number value) { // if (value instanceof Integer) { // return Integer.signum((Integer) value); // } else if (value instanceof Long) { // return Long.signum((Long) value); // } else if (value instanceof BigInteger) { // return ((BigInteger) value).signum(); // } else if (value instanceof BigDecimal) { // return ((BigDecimal) value).signum(); // } else { // throw new IllegalArgumentException("Unsupported number type: " + value.getClass()); // } // } // // static int mod(Number value, int divisor) { // if (value instanceof Integer) { // return ((Integer) value) % divisor; // } else if (value instanceof Long) { // return (int) (((Long) value) % divisor); // } else if (value instanceof BigInteger) { // return ((BigInteger) value).mod(BigInteger.valueOf(divisor)).intValue(); // } else { // throw new IllegalArgumentException("Unsupported number type: " + value.getClass()); // } // // } // } // // Path: src/test/java/javafixes/test/Random.java // public static BigInteger randomBigInteger() { // boolean positive = randomBoolean(); // return (positive ? BIG_PLUS_INTEGER : BIG_MINUS_INTEGER) // .multiply(BigInteger.valueOf(randomLong(0, 100))) // .add(BigInteger.valueOf(positive ? randomLong(0, Long.MAX_VALUE) : randomLong(Long.MIN_VALUE + 1, 0))); // } // // Path: src/test/java/javafixes/test/Random.java // @SafeVarargs // public static long randomLong(long from, long to, Function<Long, Boolean>... validityConditions) { // return generateValidValue( // // () -> new RandomDataGenerator().nextLong(from, to), // () -> ThreadLocalRandom.current().nextLong(from, to) + (long) randomInt(0, 1), // validityConditions // ); // }
import org.junit.Test; import java.math.BigDecimal; import java.math.BigInteger; import java.util.List; import static javafixes.collection.CollectionUtil.newList; import static javafixes.test.Condition.*; import static javafixes.test.Random.randomBigInteger; import static javafixes.test.Random.randomLong; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertThat;
package javafixes.math; public class DecimalNumberConversionTest { @Test public void shouldTransformDecimalIntoPrimitiveType() {
// Path: src/main/java/javafixes/collection/CollectionUtil.java // @SafeVarargs // public static <T> ArrayList<T> newList(T... values) { // ArrayList<T> list = new ArrayList<T>(values.length); // Collections.addAll(list, values); // return list; // } // // Path: src/test/java/javafixes/test/Condition.java // @FunctionalInterface // public interface Condition<T> extends Function<T, Boolean> { // // BigInteger MIN_LONG_AS_BIG_INTEGER = BigInteger.valueOf(Long.MIN_VALUE); // BigInteger MAX_LONG_AS_BIG_INTEGER = BigInteger.valueOf(Long.MAX_VALUE); // // @SafeVarargs // static <T> Condition<T> otherThan(T... values) { // Set<T> exclusions = newSet(values); // return value -> !exclusions.contains(value); // } // // static <T extends Number> Condition<T> notDivisibleBy10() { // return value -> mod(value, 10) != 0; // } // // static <T extends Number> Condition<T> notZero() { // return value -> signum(value) != 0; // } // // static <T extends Number> Condition<T> positive() { // return value -> signum(value) == 1; // } // // static <T extends Number> Condition<T> negative() { // return value -> signum(value) == -1; // } // // static Condition<BigInteger> fitsIntoLong() { // return value -> value.compareTo(MIN_LONG_AS_BIG_INTEGER) >= 0 && value.compareTo(MAX_LONG_AS_BIG_INTEGER) <= 0; // } // // static Condition<BigInteger> notFitIntoLong() { // return value -> value.compareTo(MIN_LONG_AS_BIG_INTEGER) < 0 || value.compareTo(MIN_LONG_AS_BIG_INTEGER) > 0; // } // // static int signum(Number value) { // if (value instanceof Integer) { // return Integer.signum((Integer) value); // } else if (value instanceof Long) { // return Long.signum((Long) value); // } else if (value instanceof BigInteger) { // return ((BigInteger) value).signum(); // } else if (value instanceof BigDecimal) { // return ((BigDecimal) value).signum(); // } else { // throw new IllegalArgumentException("Unsupported number type: " + value.getClass()); // } // } // // static int mod(Number value, int divisor) { // if (value instanceof Integer) { // return ((Integer) value) % divisor; // } else if (value instanceof Long) { // return (int) (((Long) value) % divisor); // } else if (value instanceof BigInteger) { // return ((BigInteger) value).mod(BigInteger.valueOf(divisor)).intValue(); // } else { // throw new IllegalArgumentException("Unsupported number type: " + value.getClass()); // } // // } // } // // Path: src/test/java/javafixes/test/Random.java // public static BigInteger randomBigInteger() { // boolean positive = randomBoolean(); // return (positive ? BIG_PLUS_INTEGER : BIG_MINUS_INTEGER) // .multiply(BigInteger.valueOf(randomLong(0, 100))) // .add(BigInteger.valueOf(positive ? randomLong(0, Long.MAX_VALUE) : randomLong(Long.MIN_VALUE + 1, 0))); // } // // Path: src/test/java/javafixes/test/Random.java // @SafeVarargs // public static long randomLong(long from, long to, Function<Long, Boolean>... validityConditions) { // return generateValidValue( // // () -> new RandomDataGenerator().nextLong(from, to), // () -> ThreadLocalRandom.current().nextLong(from, to) + (long) randomInt(0, 1), // validityConditions // ); // } // Path: src/test/java/javafixes/math/DecimalNumberConversionTest.java import org.junit.Test; import java.math.BigDecimal; import java.math.BigInteger; import java.util.List; import static javafixes.collection.CollectionUtil.newList; import static javafixes.test.Condition.*; import static javafixes.test.Random.randomBigInteger; import static javafixes.test.Random.randomLong; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertThat; package javafixes.math; public class DecimalNumberConversionTest { @Test public void shouldTransformDecimalIntoPrimitiveType() {
List<BigInteger> unscaledValues = newList(
MatejTymes/JavaFixes
src/test/java/javafixes/math/DecimalNumberConversionTest.java
// Path: src/main/java/javafixes/collection/CollectionUtil.java // @SafeVarargs // public static <T> ArrayList<T> newList(T... values) { // ArrayList<T> list = new ArrayList<T>(values.length); // Collections.addAll(list, values); // return list; // } // // Path: src/test/java/javafixes/test/Condition.java // @FunctionalInterface // public interface Condition<T> extends Function<T, Boolean> { // // BigInteger MIN_LONG_AS_BIG_INTEGER = BigInteger.valueOf(Long.MIN_VALUE); // BigInteger MAX_LONG_AS_BIG_INTEGER = BigInteger.valueOf(Long.MAX_VALUE); // // @SafeVarargs // static <T> Condition<T> otherThan(T... values) { // Set<T> exclusions = newSet(values); // return value -> !exclusions.contains(value); // } // // static <T extends Number> Condition<T> notDivisibleBy10() { // return value -> mod(value, 10) != 0; // } // // static <T extends Number> Condition<T> notZero() { // return value -> signum(value) != 0; // } // // static <T extends Number> Condition<T> positive() { // return value -> signum(value) == 1; // } // // static <T extends Number> Condition<T> negative() { // return value -> signum(value) == -1; // } // // static Condition<BigInteger> fitsIntoLong() { // return value -> value.compareTo(MIN_LONG_AS_BIG_INTEGER) >= 0 && value.compareTo(MAX_LONG_AS_BIG_INTEGER) <= 0; // } // // static Condition<BigInteger> notFitIntoLong() { // return value -> value.compareTo(MIN_LONG_AS_BIG_INTEGER) < 0 || value.compareTo(MIN_LONG_AS_BIG_INTEGER) > 0; // } // // static int signum(Number value) { // if (value instanceof Integer) { // return Integer.signum((Integer) value); // } else if (value instanceof Long) { // return Long.signum((Long) value); // } else if (value instanceof BigInteger) { // return ((BigInteger) value).signum(); // } else if (value instanceof BigDecimal) { // return ((BigDecimal) value).signum(); // } else { // throw new IllegalArgumentException("Unsupported number type: " + value.getClass()); // } // } // // static int mod(Number value, int divisor) { // if (value instanceof Integer) { // return ((Integer) value) % divisor; // } else if (value instanceof Long) { // return (int) (((Long) value) % divisor); // } else if (value instanceof BigInteger) { // return ((BigInteger) value).mod(BigInteger.valueOf(divisor)).intValue(); // } else { // throw new IllegalArgumentException("Unsupported number type: " + value.getClass()); // } // // } // } // // Path: src/test/java/javafixes/test/Random.java // public static BigInteger randomBigInteger() { // boolean positive = randomBoolean(); // return (positive ? BIG_PLUS_INTEGER : BIG_MINUS_INTEGER) // .multiply(BigInteger.valueOf(randomLong(0, 100))) // .add(BigInteger.valueOf(positive ? randomLong(0, Long.MAX_VALUE) : randomLong(Long.MIN_VALUE + 1, 0))); // } // // Path: src/test/java/javafixes/test/Random.java // @SafeVarargs // public static long randomLong(long from, long to, Function<Long, Boolean>... validityConditions) { // return generateValidValue( // // () -> new RandomDataGenerator().nextLong(from, to), // () -> ThreadLocalRandom.current().nextLong(from, to) + (long) randomInt(0, 1), // validityConditions // ); // }
import org.junit.Test; import java.math.BigDecimal; import java.math.BigInteger; import java.util.List; import static javafixes.collection.CollectionUtil.newList; import static javafixes.test.Condition.*; import static javafixes.test.Random.randomBigInteger; import static javafixes.test.Random.randomLong; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertThat;
package javafixes.math; public class DecimalNumberConversionTest { @Test public void shouldTransformDecimalIntoPrimitiveType() { List<BigInteger> unscaledValues = newList( bi(0L), bi(-1L), bi(1L), bi(Long.MIN_VALUE), bi(Long.MAX_VALUE),
// Path: src/main/java/javafixes/collection/CollectionUtil.java // @SafeVarargs // public static <T> ArrayList<T> newList(T... values) { // ArrayList<T> list = new ArrayList<T>(values.length); // Collections.addAll(list, values); // return list; // } // // Path: src/test/java/javafixes/test/Condition.java // @FunctionalInterface // public interface Condition<T> extends Function<T, Boolean> { // // BigInteger MIN_LONG_AS_BIG_INTEGER = BigInteger.valueOf(Long.MIN_VALUE); // BigInteger MAX_LONG_AS_BIG_INTEGER = BigInteger.valueOf(Long.MAX_VALUE); // // @SafeVarargs // static <T> Condition<T> otherThan(T... values) { // Set<T> exclusions = newSet(values); // return value -> !exclusions.contains(value); // } // // static <T extends Number> Condition<T> notDivisibleBy10() { // return value -> mod(value, 10) != 0; // } // // static <T extends Number> Condition<T> notZero() { // return value -> signum(value) != 0; // } // // static <T extends Number> Condition<T> positive() { // return value -> signum(value) == 1; // } // // static <T extends Number> Condition<T> negative() { // return value -> signum(value) == -1; // } // // static Condition<BigInteger> fitsIntoLong() { // return value -> value.compareTo(MIN_LONG_AS_BIG_INTEGER) >= 0 && value.compareTo(MAX_LONG_AS_BIG_INTEGER) <= 0; // } // // static Condition<BigInteger> notFitIntoLong() { // return value -> value.compareTo(MIN_LONG_AS_BIG_INTEGER) < 0 || value.compareTo(MIN_LONG_AS_BIG_INTEGER) > 0; // } // // static int signum(Number value) { // if (value instanceof Integer) { // return Integer.signum((Integer) value); // } else if (value instanceof Long) { // return Long.signum((Long) value); // } else if (value instanceof BigInteger) { // return ((BigInteger) value).signum(); // } else if (value instanceof BigDecimal) { // return ((BigDecimal) value).signum(); // } else { // throw new IllegalArgumentException("Unsupported number type: " + value.getClass()); // } // } // // static int mod(Number value, int divisor) { // if (value instanceof Integer) { // return ((Integer) value) % divisor; // } else if (value instanceof Long) { // return (int) (((Long) value) % divisor); // } else if (value instanceof BigInteger) { // return ((BigInteger) value).mod(BigInteger.valueOf(divisor)).intValue(); // } else { // throw new IllegalArgumentException("Unsupported number type: " + value.getClass()); // } // // } // } // // Path: src/test/java/javafixes/test/Random.java // public static BigInteger randomBigInteger() { // boolean positive = randomBoolean(); // return (positive ? BIG_PLUS_INTEGER : BIG_MINUS_INTEGER) // .multiply(BigInteger.valueOf(randomLong(0, 100))) // .add(BigInteger.valueOf(positive ? randomLong(0, Long.MAX_VALUE) : randomLong(Long.MIN_VALUE + 1, 0))); // } // // Path: src/test/java/javafixes/test/Random.java // @SafeVarargs // public static long randomLong(long from, long to, Function<Long, Boolean>... validityConditions) { // return generateValidValue( // // () -> new RandomDataGenerator().nextLong(from, to), // () -> ThreadLocalRandom.current().nextLong(from, to) + (long) randomInt(0, 1), // validityConditions // ); // } // Path: src/test/java/javafixes/math/DecimalNumberConversionTest.java import org.junit.Test; import java.math.BigDecimal; import java.math.BigInteger; import java.util.List; import static javafixes.collection.CollectionUtil.newList; import static javafixes.test.Condition.*; import static javafixes.test.Random.randomBigInteger; import static javafixes.test.Random.randomLong; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertThat; package javafixes.math; public class DecimalNumberConversionTest { @Test public void shouldTransformDecimalIntoPrimitiveType() { List<BigInteger> unscaledValues = newList( bi(0L), bi(-1L), bi(1L), bi(Long.MIN_VALUE), bi(Long.MAX_VALUE),
bi(randomLong(Long.MIN_VALUE + 1, -2L, notDivisibleBy10())),
MatejTymes/JavaFixes
src/test/java/javafixes/math/DecimalNumberConversionTest.java
// Path: src/main/java/javafixes/collection/CollectionUtil.java // @SafeVarargs // public static <T> ArrayList<T> newList(T... values) { // ArrayList<T> list = new ArrayList<T>(values.length); // Collections.addAll(list, values); // return list; // } // // Path: src/test/java/javafixes/test/Condition.java // @FunctionalInterface // public interface Condition<T> extends Function<T, Boolean> { // // BigInteger MIN_LONG_AS_BIG_INTEGER = BigInteger.valueOf(Long.MIN_VALUE); // BigInteger MAX_LONG_AS_BIG_INTEGER = BigInteger.valueOf(Long.MAX_VALUE); // // @SafeVarargs // static <T> Condition<T> otherThan(T... values) { // Set<T> exclusions = newSet(values); // return value -> !exclusions.contains(value); // } // // static <T extends Number> Condition<T> notDivisibleBy10() { // return value -> mod(value, 10) != 0; // } // // static <T extends Number> Condition<T> notZero() { // return value -> signum(value) != 0; // } // // static <T extends Number> Condition<T> positive() { // return value -> signum(value) == 1; // } // // static <T extends Number> Condition<T> negative() { // return value -> signum(value) == -1; // } // // static Condition<BigInteger> fitsIntoLong() { // return value -> value.compareTo(MIN_LONG_AS_BIG_INTEGER) >= 0 && value.compareTo(MAX_LONG_AS_BIG_INTEGER) <= 0; // } // // static Condition<BigInteger> notFitIntoLong() { // return value -> value.compareTo(MIN_LONG_AS_BIG_INTEGER) < 0 || value.compareTo(MIN_LONG_AS_BIG_INTEGER) > 0; // } // // static int signum(Number value) { // if (value instanceof Integer) { // return Integer.signum((Integer) value); // } else if (value instanceof Long) { // return Long.signum((Long) value); // } else if (value instanceof BigInteger) { // return ((BigInteger) value).signum(); // } else if (value instanceof BigDecimal) { // return ((BigDecimal) value).signum(); // } else { // throw new IllegalArgumentException("Unsupported number type: " + value.getClass()); // } // } // // static int mod(Number value, int divisor) { // if (value instanceof Integer) { // return ((Integer) value) % divisor; // } else if (value instanceof Long) { // return (int) (((Long) value) % divisor); // } else if (value instanceof BigInteger) { // return ((BigInteger) value).mod(BigInteger.valueOf(divisor)).intValue(); // } else { // throw new IllegalArgumentException("Unsupported number type: " + value.getClass()); // } // // } // } // // Path: src/test/java/javafixes/test/Random.java // public static BigInteger randomBigInteger() { // boolean positive = randomBoolean(); // return (positive ? BIG_PLUS_INTEGER : BIG_MINUS_INTEGER) // .multiply(BigInteger.valueOf(randomLong(0, 100))) // .add(BigInteger.valueOf(positive ? randomLong(0, Long.MAX_VALUE) : randomLong(Long.MIN_VALUE + 1, 0))); // } // // Path: src/test/java/javafixes/test/Random.java // @SafeVarargs // public static long randomLong(long from, long to, Function<Long, Boolean>... validityConditions) { // return generateValidValue( // // () -> new RandomDataGenerator().nextLong(from, to), // () -> ThreadLocalRandom.current().nextLong(from, to) + (long) randomInt(0, 1), // validityConditions // ); // }
import org.junit.Test; import java.math.BigDecimal; import java.math.BigInteger; import java.util.List; import static javafixes.collection.CollectionUtil.newList; import static javafixes.test.Condition.*; import static javafixes.test.Random.randomBigInteger; import static javafixes.test.Random.randomLong; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertThat;
package javafixes.math; public class DecimalNumberConversionTest { @Test public void shouldTransformDecimalIntoPrimitiveType() { List<BigInteger> unscaledValues = newList( bi(0L), bi(-1L), bi(1L), bi(Long.MIN_VALUE), bi(Long.MAX_VALUE), bi(randomLong(Long.MIN_VALUE + 1, -2L, notDivisibleBy10())), bi(randomLong(2L, Long.MAX_VALUE -1L, notDivisibleBy10())),
// Path: src/main/java/javafixes/collection/CollectionUtil.java // @SafeVarargs // public static <T> ArrayList<T> newList(T... values) { // ArrayList<T> list = new ArrayList<T>(values.length); // Collections.addAll(list, values); // return list; // } // // Path: src/test/java/javafixes/test/Condition.java // @FunctionalInterface // public interface Condition<T> extends Function<T, Boolean> { // // BigInteger MIN_LONG_AS_BIG_INTEGER = BigInteger.valueOf(Long.MIN_VALUE); // BigInteger MAX_LONG_AS_BIG_INTEGER = BigInteger.valueOf(Long.MAX_VALUE); // // @SafeVarargs // static <T> Condition<T> otherThan(T... values) { // Set<T> exclusions = newSet(values); // return value -> !exclusions.contains(value); // } // // static <T extends Number> Condition<T> notDivisibleBy10() { // return value -> mod(value, 10) != 0; // } // // static <T extends Number> Condition<T> notZero() { // return value -> signum(value) != 0; // } // // static <T extends Number> Condition<T> positive() { // return value -> signum(value) == 1; // } // // static <T extends Number> Condition<T> negative() { // return value -> signum(value) == -1; // } // // static Condition<BigInteger> fitsIntoLong() { // return value -> value.compareTo(MIN_LONG_AS_BIG_INTEGER) >= 0 && value.compareTo(MAX_LONG_AS_BIG_INTEGER) <= 0; // } // // static Condition<BigInteger> notFitIntoLong() { // return value -> value.compareTo(MIN_LONG_AS_BIG_INTEGER) < 0 || value.compareTo(MIN_LONG_AS_BIG_INTEGER) > 0; // } // // static int signum(Number value) { // if (value instanceof Integer) { // return Integer.signum((Integer) value); // } else if (value instanceof Long) { // return Long.signum((Long) value); // } else if (value instanceof BigInteger) { // return ((BigInteger) value).signum(); // } else if (value instanceof BigDecimal) { // return ((BigDecimal) value).signum(); // } else { // throw new IllegalArgumentException("Unsupported number type: " + value.getClass()); // } // } // // static int mod(Number value, int divisor) { // if (value instanceof Integer) { // return ((Integer) value) % divisor; // } else if (value instanceof Long) { // return (int) (((Long) value) % divisor); // } else if (value instanceof BigInteger) { // return ((BigInteger) value).mod(BigInteger.valueOf(divisor)).intValue(); // } else { // throw new IllegalArgumentException("Unsupported number type: " + value.getClass()); // } // // } // } // // Path: src/test/java/javafixes/test/Random.java // public static BigInteger randomBigInteger() { // boolean positive = randomBoolean(); // return (positive ? BIG_PLUS_INTEGER : BIG_MINUS_INTEGER) // .multiply(BigInteger.valueOf(randomLong(0, 100))) // .add(BigInteger.valueOf(positive ? randomLong(0, Long.MAX_VALUE) : randomLong(Long.MIN_VALUE + 1, 0))); // } // // Path: src/test/java/javafixes/test/Random.java // @SafeVarargs // public static long randomLong(long from, long to, Function<Long, Boolean>... validityConditions) { // return generateValidValue( // // () -> new RandomDataGenerator().nextLong(from, to), // () -> ThreadLocalRandom.current().nextLong(from, to) + (long) randomInt(0, 1), // validityConditions // ); // } // Path: src/test/java/javafixes/math/DecimalNumberConversionTest.java import org.junit.Test; import java.math.BigDecimal; import java.math.BigInteger; import java.util.List; import static javafixes.collection.CollectionUtil.newList; import static javafixes.test.Condition.*; import static javafixes.test.Random.randomBigInteger; import static javafixes.test.Random.randomLong; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertThat; package javafixes.math; public class DecimalNumberConversionTest { @Test public void shouldTransformDecimalIntoPrimitiveType() { List<BigInteger> unscaledValues = newList( bi(0L), bi(-1L), bi(1L), bi(Long.MIN_VALUE), bi(Long.MAX_VALUE), bi(randomLong(Long.MIN_VALUE + 1, -2L, notDivisibleBy10())), bi(randomLong(2L, Long.MAX_VALUE -1L, notDivisibleBy10())),
randomBigInteger(positive(), notFitIntoLong(), notDivisibleBy10()),
MatejTymes/JavaFixes
src/test/java/javafixes/io/InputStreamUtilTest.java
// Path: src/main/java/javafixes/common/StreamUtil.java // public class StreamUtil { // // public static <T> Stream<T> toStream(Iterable<T> iterable) { // return StreamSupport.stream(iterable.spliterator(), false); // } // // public static <T> Stream<T> toStream(Iterator<T> iterator) { // return toStream(() -> iterator); // } // } // // Path: src/main/java/javafixes/collection/CollectionUtil.java // @SafeVarargs // public static <T> ArrayList<T> newList(T... values) { // ArrayList<T> list = new ArrayList<T>(values.length); // Collections.addAll(list, values); // return list; // }
import javafixes.common.StreamUtil; import org.junit.Test; import java.util.Iterator; import java.util.stream.Stream; import static java.util.stream.Collectors.toList; import static javafixes.collection.CollectionUtil.newList; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertThat;
package javafixes.io; public class InputStreamUtilTest { @Test public void shouldCreateStreamFromIterable() {
// Path: src/main/java/javafixes/common/StreamUtil.java // public class StreamUtil { // // public static <T> Stream<T> toStream(Iterable<T> iterable) { // return StreamSupport.stream(iterable.spliterator(), false); // } // // public static <T> Stream<T> toStream(Iterator<T> iterator) { // return toStream(() -> iterator); // } // } // // Path: src/main/java/javafixes/collection/CollectionUtil.java // @SafeVarargs // public static <T> ArrayList<T> newList(T... values) { // ArrayList<T> list = new ArrayList<T>(values.length); // Collections.addAll(list, values); // return list; // } // Path: src/test/java/javafixes/io/InputStreamUtilTest.java import javafixes.common.StreamUtil; import org.junit.Test; import java.util.Iterator; import java.util.stream.Stream; import static java.util.stream.Collectors.toList; import static javafixes.collection.CollectionUtil.newList; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertThat; package javafixes.io; public class InputStreamUtilTest { @Test public void shouldCreateStreamFromIterable() {
Iterable<String> iterable = newList("Hello", "World", "!");
MatejTymes/JavaFixes
src/test/java/javafixes/io/InputStreamUtilTest.java
// Path: src/main/java/javafixes/common/StreamUtil.java // public class StreamUtil { // // public static <T> Stream<T> toStream(Iterable<T> iterable) { // return StreamSupport.stream(iterable.spliterator(), false); // } // // public static <T> Stream<T> toStream(Iterator<T> iterator) { // return toStream(() -> iterator); // } // } // // Path: src/main/java/javafixes/collection/CollectionUtil.java // @SafeVarargs // public static <T> ArrayList<T> newList(T... values) { // ArrayList<T> list = new ArrayList<T>(values.length); // Collections.addAll(list, values); // return list; // }
import javafixes.common.StreamUtil; import org.junit.Test; import java.util.Iterator; import java.util.stream.Stream; import static java.util.stream.Collectors.toList; import static javafixes.collection.CollectionUtil.newList; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertThat;
package javafixes.io; public class InputStreamUtilTest { @Test public void shouldCreateStreamFromIterable() { Iterable<String> iterable = newList("Hello", "World", "!");
// Path: src/main/java/javafixes/common/StreamUtil.java // public class StreamUtil { // // public static <T> Stream<T> toStream(Iterable<T> iterable) { // return StreamSupport.stream(iterable.spliterator(), false); // } // // public static <T> Stream<T> toStream(Iterator<T> iterator) { // return toStream(() -> iterator); // } // } // // Path: src/main/java/javafixes/collection/CollectionUtil.java // @SafeVarargs // public static <T> ArrayList<T> newList(T... values) { // ArrayList<T> list = new ArrayList<T>(values.length); // Collections.addAll(list, values); // return list; // } // Path: src/test/java/javafixes/io/InputStreamUtilTest.java import javafixes.common.StreamUtil; import org.junit.Test; import java.util.Iterator; import java.util.stream.Stream; import static java.util.stream.Collectors.toList; import static javafixes.collection.CollectionUtil.newList; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertThat; package javafixes.io; public class InputStreamUtilTest { @Test public void shouldCreateStreamFromIterable() { Iterable<String> iterable = newList("Hello", "World", "!");
Stream<String> stream = StreamUtil.toStream(iterable);
MatejTymes/JavaFixes
src/test/java/javafixes/object/EitherTest.java
// Path: src/main/java/javafixes/object/Either.java // public static <L, R> Either<L, R> left(L value) { // return new Either.Left<>(value); // } // // Path: src/main/java/javafixes/object/Either.java // public static <L, R> Either<L, R> right(R value) { // return new Either.Right<>(value); // } // // Path: src/test/java/javafixes/test/Random.java // @SafeVarargs // public static int randomInt(int from, int to, Function<Integer, Boolean>... validityConditions) { // return generateValidValue( // // typecast it to long as otherwise we could get int overflow // () -> (int) ((long) (Math.random() * ((long) to - (long) from + 1L)) + (long) from), // validityConditions // ); // }
import org.junit.Test; import java.math.BigDecimal; import java.util.NoSuchElementException; import java.util.UUID; import java.util.concurrent.atomic.AtomicInteger; import static java.util.UUID.randomUUID; import static javafixes.object.Either.left; import static javafixes.object.Either.right; import static javafixes.test.Random.randomInt; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail;
package javafixes.object; public class EitherTest { private final Throwable expectedThrowable = new Throwable("Failed with a Throwable"); private final Exception expectedException = new Exception("Failed with another Exception"); private final RuntimeException expectedRuntimeException = new RuntimeException("Failed with yet another Exception"); private final AtomicInteger leftCallCount = new AtomicInteger(0); private final AtomicInteger rightCallCount = new AtomicInteger(0); @Test public void shouldHandleLeft() throws Throwable { UUID value = randomUUID();
// Path: src/main/java/javafixes/object/Either.java // public static <L, R> Either<L, R> left(L value) { // return new Either.Left<>(value); // } // // Path: src/main/java/javafixes/object/Either.java // public static <L, R> Either<L, R> right(R value) { // return new Either.Right<>(value); // } // // Path: src/test/java/javafixes/test/Random.java // @SafeVarargs // public static int randomInt(int from, int to, Function<Integer, Boolean>... validityConditions) { // return generateValidValue( // // typecast it to long as otherwise we could get int overflow // () -> (int) ((long) (Math.random() * ((long) to - (long) from + 1L)) + (long) from), // validityConditions // ); // } // Path: src/test/java/javafixes/object/EitherTest.java import org.junit.Test; import java.math.BigDecimal; import java.util.NoSuchElementException; import java.util.UUID; import java.util.concurrent.atomic.AtomicInteger; import static java.util.UUID.randomUUID; import static javafixes.object.Either.left; import static javafixes.object.Either.right; import static javafixes.test.Random.randomInt; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; package javafixes.object; public class EitherTest { private final Throwable expectedThrowable = new Throwable("Failed with a Throwable"); private final Exception expectedException = new Exception("Failed with another Exception"); private final RuntimeException expectedRuntimeException = new RuntimeException("Failed with yet another Exception"); private final AtomicInteger leftCallCount = new AtomicInteger(0); private final AtomicInteger rightCallCount = new AtomicInteger(0); @Test public void shouldHandleLeft() throws Throwable { UUID value = randomUUID();
Either<UUID, Integer> either = Either.left(value);
MatejTymes/JavaFixes
src/test/java/javafixes/object/EitherTest.java
// Path: src/main/java/javafixes/object/Either.java // public static <L, R> Either<L, R> left(L value) { // return new Either.Left<>(value); // } // // Path: src/main/java/javafixes/object/Either.java // public static <L, R> Either<L, R> right(R value) { // return new Either.Right<>(value); // } // // Path: src/test/java/javafixes/test/Random.java // @SafeVarargs // public static int randomInt(int from, int to, Function<Integer, Boolean>... validityConditions) { // return generateValidValue( // // typecast it to long as otherwise we could get int overflow // () -> (int) ((long) (Math.random() * ((long) to - (long) from + 1L)) + (long) from), // validityConditions // ); // }
import org.junit.Test; import java.math.BigDecimal; import java.util.NoSuchElementException; import java.util.UUID; import java.util.concurrent.atomic.AtomicInteger; import static java.util.UUID.randomUUID; import static javafixes.object.Either.left; import static javafixes.object.Either.right; import static javafixes.test.Random.randomInt; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail;
} ); assertThat(mappedEither, equalTo(left(value + "-" + value))); assertThat(leftCallCount.get(), is(1)); assertThat(rightCallCount.get(), is(0)); // mapLeft leftCallCount.set(0); Either<String, Integer> leftMappedEither = either.mapLeft(leftValue -> { leftCallCount.incrementAndGet(); return leftValue + "-" + leftValue; }); assertThat(leftMappedEither, equalTo(left(value + "-" + value))); assertThat(leftCallCount.get(), is(1)); // mapRight rightCallCount.set(0); Either<UUID, BigDecimal> rightMappedEither = either.mapRight(rightValue -> { rightCallCount.incrementAndGet(); return BigDecimal.valueOf(rightValue + 5); }); assertThat(rightMappedEither, equalTo(left(value))); assertThat(rightCallCount.get(), is(0)); // fold leftCallCount.set(0); rightCallCount.set(0);
// Path: src/main/java/javafixes/object/Either.java // public static <L, R> Either<L, R> left(L value) { // return new Either.Left<>(value); // } // // Path: src/main/java/javafixes/object/Either.java // public static <L, R> Either<L, R> right(R value) { // return new Either.Right<>(value); // } // // Path: src/test/java/javafixes/test/Random.java // @SafeVarargs // public static int randomInt(int from, int to, Function<Integer, Boolean>... validityConditions) { // return generateValidValue( // // typecast it to long as otherwise we could get int overflow // () -> (int) ((long) (Math.random() * ((long) to - (long) from + 1L)) + (long) from), // validityConditions // ); // } // Path: src/test/java/javafixes/object/EitherTest.java import org.junit.Test; import java.math.BigDecimal; import java.util.NoSuchElementException; import java.util.UUID; import java.util.concurrent.atomic.AtomicInteger; import static java.util.UUID.randomUUID; import static javafixes.object.Either.left; import static javafixes.object.Either.right; import static javafixes.test.Random.randomInt; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; } ); assertThat(mappedEither, equalTo(left(value + "-" + value))); assertThat(leftCallCount.get(), is(1)); assertThat(rightCallCount.get(), is(0)); // mapLeft leftCallCount.set(0); Either<String, Integer> leftMappedEither = either.mapLeft(leftValue -> { leftCallCount.incrementAndGet(); return leftValue + "-" + leftValue; }); assertThat(leftMappedEither, equalTo(left(value + "-" + value))); assertThat(leftCallCount.get(), is(1)); // mapRight rightCallCount.set(0); Either<UUID, BigDecimal> rightMappedEither = either.mapRight(rightValue -> { rightCallCount.incrementAndGet(); return BigDecimal.valueOf(rightValue + 5); }); assertThat(rightMappedEither, equalTo(left(value))); assertThat(rightCallCount.get(), is(0)); // fold leftCallCount.set(0); rightCallCount.set(0);
int randomIncrement = randomInt(-100, 100);
MatejTymes/JavaFixes
src/test/java/javafixes/object/EitherTest.java
// Path: src/main/java/javafixes/object/Either.java // public static <L, R> Either<L, R> left(L value) { // return new Either.Left<>(value); // } // // Path: src/main/java/javafixes/object/Either.java // public static <L, R> Either<L, R> right(R value) { // return new Either.Right<>(value); // } // // Path: src/test/java/javafixes/test/Random.java // @SafeVarargs // public static int randomInt(int from, int to, Function<Integer, Boolean>... validityConditions) { // return generateValidValue( // // typecast it to long as otherwise we could get int overflow // () -> (int) ((long) (Math.random() * ((long) to - (long) from + 1L)) + (long) from), // validityConditions // ); // }
import org.junit.Test; import java.math.BigDecimal; import java.util.NoSuchElementException; import java.util.UUID; import java.util.concurrent.atomic.AtomicInteger; import static java.util.UUID.randomUUID; import static javafixes.object.Either.left; import static javafixes.object.Either.right; import static javafixes.test.Random.randomInt; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail;
// fold leftCallCount.set(0); rightCallCount.set(0); int randomIncrement = randomInt(-100, 100); Integer foldedValue = either.fold( leftValue -> { leftCallCount.incrementAndGet(); return leftValue.hashCode() + randomIncrement; }, rightValue -> { rightCallCount.incrementAndGet(); return rightValue + randomIncrement; } ); assertThat(foldedValue, equalTo(value.hashCode() + randomIncrement)); assertThat(leftCallCount.get(), is(1)); assertThat(rightCallCount.get(), is(0)); // handleLeft leftCallCount.set(0); assertThat(either.handleLeft(leftValue -> leftCallCount.incrementAndGet()), equalTo(left(value))); assertThat(leftCallCount.get(), is(1)); leftCallCount.set(0); try { assertThat(either.handleLeft(leftValue -> { leftCallCount.incrementAndGet(); throw expectedThrowable;
// Path: src/main/java/javafixes/object/Either.java // public static <L, R> Either<L, R> left(L value) { // return new Either.Left<>(value); // } // // Path: src/main/java/javafixes/object/Either.java // public static <L, R> Either<L, R> right(R value) { // return new Either.Right<>(value); // } // // Path: src/test/java/javafixes/test/Random.java // @SafeVarargs // public static int randomInt(int from, int to, Function<Integer, Boolean>... validityConditions) { // return generateValidValue( // // typecast it to long as otherwise we could get int overflow // () -> (int) ((long) (Math.random() * ((long) to - (long) from + 1L)) + (long) from), // validityConditions // ); // } // Path: src/test/java/javafixes/object/EitherTest.java import org.junit.Test; import java.math.BigDecimal; import java.util.NoSuchElementException; import java.util.UUID; import java.util.concurrent.atomic.AtomicInteger; import static java.util.UUID.randomUUID; import static javafixes.object.Either.left; import static javafixes.object.Either.right; import static javafixes.test.Random.randomInt; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; // fold leftCallCount.set(0); rightCallCount.set(0); int randomIncrement = randomInt(-100, 100); Integer foldedValue = either.fold( leftValue -> { leftCallCount.incrementAndGet(); return leftValue.hashCode() + randomIncrement; }, rightValue -> { rightCallCount.incrementAndGet(); return rightValue + randomIncrement; } ); assertThat(foldedValue, equalTo(value.hashCode() + randomIncrement)); assertThat(leftCallCount.get(), is(1)); assertThat(rightCallCount.get(), is(0)); // handleLeft leftCallCount.set(0); assertThat(either.handleLeft(leftValue -> leftCallCount.incrementAndGet()), equalTo(left(value))); assertThat(leftCallCount.get(), is(1)); leftCallCount.set(0); try { assertThat(either.handleLeft(leftValue -> { leftCallCount.incrementAndGet(); throw expectedThrowable;
}), equalTo(right(value)));
MatejTymes/JavaFixes
src/test/java/javafixes/object/changing/ChangingValueTest.java
// Path: src/main/java/javafixes/object/changing/ChangingValue.java // static <T1, T2> DerivedValue<Tuple<T1, T2>, ?> join(ChangingValue<T1> value1, ChangingValue<T2> value2) { // return ((ChangingValue<List<Object>>) new DerivedMultiValue(newList(value1, value2))) // .map(values -> tuple( // (T1) values.get(0), // (T2) values.get(1) // )); // } // // Path: src/main/java/javafixes/object/changing/MutableValue.java // public static <T> MutableValue<T> mutableValue(T initialValue) { // return new MutableValue<>( // Optional.empty(), // right(initialValue), // Optional.empty(), // Optional.empty()); // } // // Path: src/test/java/javafixes/test/Random.java // public static boolean randomBoolean() { // return pickRandomValue(true, false); // }
import org.junit.Test; import static javafixes.object.changing.ChangingValue.join; import static javafixes.object.changing.MutableValue.mutableValue; import static javafixes.test.Random.randomBoolean;
package javafixes.object.changing; public class ChangingValueTest { @Test public void shouldBeAbleToUseIt() {
// Path: src/main/java/javafixes/object/changing/ChangingValue.java // static <T1, T2> DerivedValue<Tuple<T1, T2>, ?> join(ChangingValue<T1> value1, ChangingValue<T2> value2) { // return ((ChangingValue<List<Object>>) new DerivedMultiValue(newList(value1, value2))) // .map(values -> tuple( // (T1) values.get(0), // (T2) values.get(1) // )); // } // // Path: src/main/java/javafixes/object/changing/MutableValue.java // public static <T> MutableValue<T> mutableValue(T initialValue) { // return new MutableValue<>( // Optional.empty(), // right(initialValue), // Optional.empty(), // Optional.empty()); // } // // Path: src/test/java/javafixes/test/Random.java // public static boolean randomBoolean() { // return pickRandomValue(true, false); // } // Path: src/test/java/javafixes/object/changing/ChangingValueTest.java import org.junit.Test; import static javafixes.object.changing.ChangingValue.join; import static javafixes.object.changing.MutableValue.mutableValue; import static javafixes.test.Random.randomBoolean; package javafixes.object.changing; public class ChangingValueTest { @Test public void shouldBeAbleToUseIt() {
MutableValue<String> hostAndPort = mutableValue("host123:8080")
MatejTymes/JavaFixes
src/test/java/javafixes/object/changing/ChangingValueTest.java
// Path: src/main/java/javafixes/object/changing/ChangingValue.java // static <T1, T2> DerivedValue<Tuple<T1, T2>, ?> join(ChangingValue<T1> value1, ChangingValue<T2> value2) { // return ((ChangingValue<List<Object>>) new DerivedMultiValue(newList(value1, value2))) // .map(values -> tuple( // (T1) values.get(0), // (T2) values.get(1) // )); // } // // Path: src/main/java/javafixes/object/changing/MutableValue.java // public static <T> MutableValue<T> mutableValue(T initialValue) { // return new MutableValue<>( // Optional.empty(), // right(initialValue), // Optional.empty(), // Optional.empty()); // } // // Path: src/test/java/javafixes/test/Random.java // public static boolean randomBoolean() { // return pickRandomValue(true, false); // }
import org.junit.Test; import static javafixes.object.changing.ChangingValue.join; import static javafixes.object.changing.MutableValue.mutableValue; import static javafixes.test.Random.randomBoolean;
package javafixes.object.changing; public class ChangingValueTest { @Test public void shouldBeAbleToUseIt() { MutableValue<String> hostAndPort = mutableValue("host123:8080") .withOnValueChangedFunction( value -> System.out.println("host = " + value), true );
// Path: src/main/java/javafixes/object/changing/ChangingValue.java // static <T1, T2> DerivedValue<Tuple<T1, T2>, ?> join(ChangingValue<T1> value1, ChangingValue<T2> value2) { // return ((ChangingValue<List<Object>>) new DerivedMultiValue(newList(value1, value2))) // .map(values -> tuple( // (T1) values.get(0), // (T2) values.get(1) // )); // } // // Path: src/main/java/javafixes/object/changing/MutableValue.java // public static <T> MutableValue<T> mutableValue(T initialValue) { // return new MutableValue<>( // Optional.empty(), // right(initialValue), // Optional.empty(), // Optional.empty()); // } // // Path: src/test/java/javafixes/test/Random.java // public static boolean randomBoolean() { // return pickRandomValue(true, false); // } // Path: src/test/java/javafixes/object/changing/ChangingValueTest.java import org.junit.Test; import static javafixes.object.changing.ChangingValue.join; import static javafixes.object.changing.MutableValue.mutableValue; import static javafixes.test.Random.randomBoolean; package javafixes.object.changing; public class ChangingValueTest { @Test public void shouldBeAbleToUseIt() { MutableValue<String> hostAndPort = mutableValue("host123:8080") .withOnValueChangedFunction( value -> System.out.println("host = " + value), true );
ChangingValue<Boolean> isConnected = hostAndPort.map(value -> randomBoolean())
MatejTymes/JavaFixes
src/test/java/javafixes/object/changing/ChangingValueTest.java
// Path: src/main/java/javafixes/object/changing/ChangingValue.java // static <T1, T2> DerivedValue<Tuple<T1, T2>, ?> join(ChangingValue<T1> value1, ChangingValue<T2> value2) { // return ((ChangingValue<List<Object>>) new DerivedMultiValue(newList(value1, value2))) // .map(values -> tuple( // (T1) values.get(0), // (T2) values.get(1) // )); // } // // Path: src/main/java/javafixes/object/changing/MutableValue.java // public static <T> MutableValue<T> mutableValue(T initialValue) { // return new MutableValue<>( // Optional.empty(), // right(initialValue), // Optional.empty(), // Optional.empty()); // } // // Path: src/test/java/javafixes/test/Random.java // public static boolean randomBoolean() { // return pickRandomValue(true, false); // }
import org.junit.Test; import static javafixes.object.changing.ChangingValue.join; import static javafixes.object.changing.MutableValue.mutableValue; import static javafixes.test.Random.randomBoolean;
package javafixes.object.changing; public class ChangingValueTest { @Test public void shouldBeAbleToUseIt() { MutableValue<String> hostAndPort = mutableValue("host123:8080") .withOnValueChangedFunction( value -> System.out.println("host = " + value), true ); ChangingValue<Boolean> isConnected = hostAndPort.map(value -> randomBoolean()) .withOnValueChangedFunction( value -> System.out.println("is connected = " + value), true );
// Path: src/main/java/javafixes/object/changing/ChangingValue.java // static <T1, T2> DerivedValue<Tuple<T1, T2>, ?> join(ChangingValue<T1> value1, ChangingValue<T2> value2) { // return ((ChangingValue<List<Object>>) new DerivedMultiValue(newList(value1, value2))) // .map(values -> tuple( // (T1) values.get(0), // (T2) values.get(1) // )); // } // // Path: src/main/java/javafixes/object/changing/MutableValue.java // public static <T> MutableValue<T> mutableValue(T initialValue) { // return new MutableValue<>( // Optional.empty(), // right(initialValue), // Optional.empty(), // Optional.empty()); // } // // Path: src/test/java/javafixes/test/Random.java // public static boolean randomBoolean() { // return pickRandomValue(true, false); // } // Path: src/test/java/javafixes/object/changing/ChangingValueTest.java import org.junit.Test; import static javafixes.object.changing.ChangingValue.join; import static javafixes.object.changing.MutableValue.mutableValue; import static javafixes.test.Random.randomBoolean; package javafixes.object.changing; public class ChangingValueTest { @Test public void shouldBeAbleToUseIt() { MutableValue<String> hostAndPort = mutableValue("host123:8080") .withOnValueChangedFunction( value -> System.out.println("host = " + value), true ); ChangingValue<Boolean> isConnected = hostAndPort.map(value -> randomBoolean()) .withOnValueChangedFunction( value -> System.out.println("is connected = " + value), true );
ChangingValue<String> nodeInfo = join(hostAndPort, isConnected).map(tuple -> {
MatejTymes/JavaFixes
src/main/java/javafixes/object/Triple.java
// Path: src/main/java/javafixes/common/function/TriFunction.java // @FunctionalInterface // public interface TriFunction<A, B, C, D> { // // /** // * Applies this function to the given arguments. // * // * @param a the first function argument // * @param b the second function argument // * @param c the third function argument // * @return the function result // */ // D apply(A a, B b, C c); // }
import javafixes.common.function.TriFunction;
*/ public A a() { return a; } /** * Returns second value * * @return second value */ public B b() { return b; } /** * Returns third value * * @return third value */ public C c() { return c; } /** * Maps wrapped values using a provided {@code TriFunction} * * @param mapper function to map wrapped values * @param <D> the type of generated value * @return value generated via the mapping function */
// Path: src/main/java/javafixes/common/function/TriFunction.java // @FunctionalInterface // public interface TriFunction<A, B, C, D> { // // /** // * Applies this function to the given arguments. // * // * @param a the first function argument // * @param b the second function argument // * @param c the third function argument // * @return the function result // */ // D apply(A a, B b, C c); // } // Path: src/main/java/javafixes/object/Triple.java import javafixes.common.function.TriFunction; */ public A a() { return a; } /** * Returns second value * * @return second value */ public B b() { return b; } /** * Returns third value * * @return third value */ public C c() { return c; } /** * Maps wrapped values using a provided {@code TriFunction} * * @param mapper function to map wrapped values * @param <D> the type of generated value * @return value generated via the mapping function */
public <D> D map(TriFunction<? super A, ? super B, ? super C, ? extends D> mapper) {
MatejTymes/JavaFixes
src/test/java/javafixes/concurrency/ReusableCountLatchTest.java
// Path: src/test/java/javafixes/test/Condition.java // static <T extends Number> Condition<T> negative() { // return value -> signum(value) == -1; // } // // Path: src/test/java/javafixes/test/Condition.java // static <T extends Number> Condition<T> positive() { // return value -> signum(value) == 1; // } // // Path: src/test/java/javafixes/test/Random.java // public static boolean randomBoolean() { // return pickRandomValue(true, false); // } // // Path: src/test/java/javafixes/test/Random.java // @SafeVarargs // public static int randomInt(int from, int to, Function<Integer, Boolean>... validityConditions) { // return generateValidValue( // // typecast it to long as otherwise we could get int overflow // () -> (int) ((long) (Math.random() * ((long) to - (long) from + 1L)) + (long) from), // validityConditions // ); // }
import org.junit.Test; import java.util.concurrent.ScheduledExecutorService; import static java.util.concurrent.Executors.newScheduledThreadPool; import static java.util.concurrent.TimeUnit.MILLISECONDS; import static javafixes.test.Condition.negative; import static javafixes.test.Condition.positive; import static javafixes.test.Random.randomBoolean; import static javafixes.test.Random.randomInt; import static org.hamcrest.Matchers.*; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail;
package javafixes.concurrency; public class ReusableCountLatchTest { @Test public void shouldReflectInitialValue() {
// Path: src/test/java/javafixes/test/Condition.java // static <T extends Number> Condition<T> negative() { // return value -> signum(value) == -1; // } // // Path: src/test/java/javafixes/test/Condition.java // static <T extends Number> Condition<T> positive() { // return value -> signum(value) == 1; // } // // Path: src/test/java/javafixes/test/Random.java // public static boolean randomBoolean() { // return pickRandomValue(true, false); // } // // Path: src/test/java/javafixes/test/Random.java // @SafeVarargs // public static int randomInt(int from, int to, Function<Integer, Boolean>... validityConditions) { // return generateValidValue( // // typecast it to long as otherwise we could get int overflow // () -> (int) ((long) (Math.random() * ((long) to - (long) from + 1L)) + (long) from), // validityConditions // ); // } // Path: src/test/java/javafixes/concurrency/ReusableCountLatchTest.java import org.junit.Test; import java.util.concurrent.ScheduledExecutorService; import static java.util.concurrent.Executors.newScheduledThreadPool; import static java.util.concurrent.TimeUnit.MILLISECONDS; import static javafixes.test.Condition.negative; import static javafixes.test.Condition.positive; import static javafixes.test.Random.randomBoolean; import static javafixes.test.Random.randomInt; import static org.hamcrest.Matchers.*; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; package javafixes.concurrency; public class ReusableCountLatchTest { @Test public void shouldReflectInitialValue() {
int positiveCount = randomInt(positive());
MatejTymes/JavaFixes
src/test/java/javafixes/concurrency/ReusableCountLatchTest.java
// Path: src/test/java/javafixes/test/Condition.java // static <T extends Number> Condition<T> negative() { // return value -> signum(value) == -1; // } // // Path: src/test/java/javafixes/test/Condition.java // static <T extends Number> Condition<T> positive() { // return value -> signum(value) == 1; // } // // Path: src/test/java/javafixes/test/Random.java // public static boolean randomBoolean() { // return pickRandomValue(true, false); // } // // Path: src/test/java/javafixes/test/Random.java // @SafeVarargs // public static int randomInt(int from, int to, Function<Integer, Boolean>... validityConditions) { // return generateValidValue( // // typecast it to long as otherwise we could get int overflow // () -> (int) ((long) (Math.random() * ((long) to - (long) from + 1L)) + (long) from), // validityConditions // ); // }
import org.junit.Test; import java.util.concurrent.ScheduledExecutorService; import static java.util.concurrent.Executors.newScheduledThreadPool; import static java.util.concurrent.TimeUnit.MILLISECONDS; import static javafixes.test.Condition.negative; import static javafixes.test.Condition.positive; import static javafixes.test.Random.randomBoolean; import static javafixes.test.Random.randomInt; import static org.hamcrest.Matchers.*; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail;
package javafixes.concurrency; public class ReusableCountLatchTest { @Test public void shouldReflectInitialValue() {
// Path: src/test/java/javafixes/test/Condition.java // static <T extends Number> Condition<T> negative() { // return value -> signum(value) == -1; // } // // Path: src/test/java/javafixes/test/Condition.java // static <T extends Number> Condition<T> positive() { // return value -> signum(value) == 1; // } // // Path: src/test/java/javafixes/test/Random.java // public static boolean randomBoolean() { // return pickRandomValue(true, false); // } // // Path: src/test/java/javafixes/test/Random.java // @SafeVarargs // public static int randomInt(int from, int to, Function<Integer, Boolean>... validityConditions) { // return generateValidValue( // // typecast it to long as otherwise we could get int overflow // () -> (int) ((long) (Math.random() * ((long) to - (long) from + 1L)) + (long) from), // validityConditions // ); // } // Path: src/test/java/javafixes/concurrency/ReusableCountLatchTest.java import org.junit.Test; import java.util.concurrent.ScheduledExecutorService; import static java.util.concurrent.Executors.newScheduledThreadPool; import static java.util.concurrent.TimeUnit.MILLISECONDS; import static javafixes.test.Condition.negative; import static javafixes.test.Condition.positive; import static javafixes.test.Random.randomBoolean; import static javafixes.test.Random.randomInt; import static org.hamcrest.Matchers.*; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; package javafixes.concurrency; public class ReusableCountLatchTest { @Test public void shouldReflectInitialValue() {
int positiveCount = randomInt(positive());
MatejTymes/JavaFixes
src/test/java/javafixes/concurrency/ReusableCountLatchTest.java
// Path: src/test/java/javafixes/test/Condition.java // static <T extends Number> Condition<T> negative() { // return value -> signum(value) == -1; // } // // Path: src/test/java/javafixes/test/Condition.java // static <T extends Number> Condition<T> positive() { // return value -> signum(value) == 1; // } // // Path: src/test/java/javafixes/test/Random.java // public static boolean randomBoolean() { // return pickRandomValue(true, false); // } // // Path: src/test/java/javafixes/test/Random.java // @SafeVarargs // public static int randomInt(int from, int to, Function<Integer, Boolean>... validityConditions) { // return generateValidValue( // // typecast it to long as otherwise we could get int overflow // () -> (int) ((long) (Math.random() * ((long) to - (long) from + 1L)) + (long) from), // validityConditions // ); // }
import org.junit.Test; import java.util.concurrent.ScheduledExecutorService; import static java.util.concurrent.Executors.newScheduledThreadPool; import static java.util.concurrent.TimeUnit.MILLISECONDS; import static javafixes.test.Condition.negative; import static javafixes.test.Condition.positive; import static javafixes.test.Random.randomBoolean; import static javafixes.test.Random.randomInt; import static org.hamcrest.Matchers.*; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail;
package javafixes.concurrency; public class ReusableCountLatchTest { @Test public void shouldReflectInitialValue() { int positiveCount = randomInt(positive()); assertThat(new ReusableCountLatch(positiveCount).getCount(), equalTo(positiveCount)); assertThat(new ReusableCountLatch().getCount(), equalTo(0)); } @Test public void shouldFailOnNegativeInitialCount() { try {
// Path: src/test/java/javafixes/test/Condition.java // static <T extends Number> Condition<T> negative() { // return value -> signum(value) == -1; // } // // Path: src/test/java/javafixes/test/Condition.java // static <T extends Number> Condition<T> positive() { // return value -> signum(value) == 1; // } // // Path: src/test/java/javafixes/test/Random.java // public static boolean randomBoolean() { // return pickRandomValue(true, false); // } // // Path: src/test/java/javafixes/test/Random.java // @SafeVarargs // public static int randomInt(int from, int to, Function<Integer, Boolean>... validityConditions) { // return generateValidValue( // // typecast it to long as otherwise we could get int overflow // () -> (int) ((long) (Math.random() * ((long) to - (long) from + 1L)) + (long) from), // validityConditions // ); // } // Path: src/test/java/javafixes/concurrency/ReusableCountLatchTest.java import org.junit.Test; import java.util.concurrent.ScheduledExecutorService; import static java.util.concurrent.Executors.newScheduledThreadPool; import static java.util.concurrent.TimeUnit.MILLISECONDS; import static javafixes.test.Condition.negative; import static javafixes.test.Condition.positive; import static javafixes.test.Random.randomBoolean; import static javafixes.test.Random.randomInt; import static org.hamcrest.Matchers.*; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; package javafixes.concurrency; public class ReusableCountLatchTest { @Test public void shouldReflectInitialValue() { int positiveCount = randomInt(positive()); assertThat(new ReusableCountLatch(positiveCount).getCount(), equalTo(positiveCount)); assertThat(new ReusableCountLatch().getCount(), equalTo(0)); } @Test public void shouldFailOnNegativeInitialCount() { try {
int negativeCount = randomInt(negative());
MatejTymes/JavaFixes
src/test/java/javafixes/concurrency/ReusableCountLatchTest.java
// Path: src/test/java/javafixes/test/Condition.java // static <T extends Number> Condition<T> negative() { // return value -> signum(value) == -1; // } // // Path: src/test/java/javafixes/test/Condition.java // static <T extends Number> Condition<T> positive() { // return value -> signum(value) == 1; // } // // Path: src/test/java/javafixes/test/Random.java // public static boolean randomBoolean() { // return pickRandomValue(true, false); // } // // Path: src/test/java/javafixes/test/Random.java // @SafeVarargs // public static int randomInt(int from, int to, Function<Integer, Boolean>... validityConditions) { // return generateValidValue( // // typecast it to long as otherwise we could get int overflow // () -> (int) ((long) (Math.random() * ((long) to - (long) from + 1L)) + (long) from), // validityConditions // ); // }
import org.junit.Test; import java.util.concurrent.ScheduledExecutorService; import static java.util.concurrent.Executors.newScheduledThreadPool; import static java.util.concurrent.TimeUnit.MILLISECONDS; import static javafixes.test.Condition.negative; import static javafixes.test.Condition.positive; import static javafixes.test.Random.randomBoolean; import static javafixes.test.Random.randomInt; import static org.hamcrest.Matchers.*; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail;
package javafixes.concurrency; public class ReusableCountLatchTest { @Test public void shouldReflectInitialValue() { int positiveCount = randomInt(positive()); assertThat(new ReusableCountLatch(positiveCount).getCount(), equalTo(positiveCount)); assertThat(new ReusableCountLatch().getCount(), equalTo(0)); } @Test public void shouldFailOnNegativeInitialCount() { try { int negativeCount = randomInt(negative()); new ReusableCountLatch(negativeCount).getCount(); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { // expected } } @Test public void shouldCount() { ReusableCountLatch latch = new ReusableCountLatch(0); int expectedCount = 0; for (int iteration = 0; iteration < 10_000; iteration++) {
// Path: src/test/java/javafixes/test/Condition.java // static <T extends Number> Condition<T> negative() { // return value -> signum(value) == -1; // } // // Path: src/test/java/javafixes/test/Condition.java // static <T extends Number> Condition<T> positive() { // return value -> signum(value) == 1; // } // // Path: src/test/java/javafixes/test/Random.java // public static boolean randomBoolean() { // return pickRandomValue(true, false); // } // // Path: src/test/java/javafixes/test/Random.java // @SafeVarargs // public static int randomInt(int from, int to, Function<Integer, Boolean>... validityConditions) { // return generateValidValue( // // typecast it to long as otherwise we could get int overflow // () -> (int) ((long) (Math.random() * ((long) to - (long) from + 1L)) + (long) from), // validityConditions // ); // } // Path: src/test/java/javafixes/concurrency/ReusableCountLatchTest.java import org.junit.Test; import java.util.concurrent.ScheduledExecutorService; import static java.util.concurrent.Executors.newScheduledThreadPool; import static java.util.concurrent.TimeUnit.MILLISECONDS; import static javafixes.test.Condition.negative; import static javafixes.test.Condition.positive; import static javafixes.test.Random.randomBoolean; import static javafixes.test.Random.randomInt; import static org.hamcrest.Matchers.*; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; package javafixes.concurrency; public class ReusableCountLatchTest { @Test public void shouldReflectInitialValue() { int positiveCount = randomInt(positive()); assertThat(new ReusableCountLatch(positiveCount).getCount(), equalTo(positiveCount)); assertThat(new ReusableCountLatch().getCount(), equalTo(0)); } @Test public void shouldFailOnNegativeInitialCount() { try { int negativeCount = randomInt(negative()); new ReusableCountLatch(negativeCount).getCount(); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { // expected } } @Test public void shouldCount() { ReusableCountLatch latch = new ReusableCountLatch(0); int expectedCount = 0; for (int iteration = 0; iteration < 10_000; iteration++) {
if (randomBoolean()) {
MatejTymes/JavaFixes
src/test/java/javafixes/math/OverflowUtilTest.java
// Path: src/main/java/javafixes/math/OverflowUtil.java // class OverflowUtil { // // static boolean willNegationOverflow(long value) { // return value == Long.MIN_VALUE; // } // // static boolean didOverflowOnLongAddition(long result, long valueA, long valueB) { // // HD 2-12 Overflow iff both arguments have the opposite sign of the result // return ((valueA ^ result) & (valueB ^ result)) < 0; // } // // static boolean didOverflowOnMultiplication(long result, long valueA, long valueB) { // long absA = Math.abs(valueA); // long absB = Math.abs(valueB); // // if (((absA | absB) >>> 31 != 0)) { // // Some bits greater than 2^31 that might cause overflow // // Check the result using the divide operator // // and check for the special case of Long.MIN_VALUE * -1 // if (((valueB != 0) && (result / valueB != valueA)) || (valueA == Long.MIN_VALUE && valueB == -1)) { // return true; // } // } // return false; // } // } // // Path: src/test/java/javafixes/test/Random.java // @SafeVarargs // public static long randomLong(long from, long to, Function<Long, Boolean>... validityConditions) { // return generateValidValue( // // () -> new RandomDataGenerator().nextLong(from, to), // () -> ThreadLocalRandom.current().nextLong(from, to) + (long) randomInt(0, 1), // validityConditions // ); // }
import org.junit.Test; import static javafixes.math.OverflowUtil.*; import static javafixes.test.Random.randomLong; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat;
package javafixes.math; public class OverflowUtilTest { @Test public void shouldFindIfNegationWillOverflow() { assertThat(willNegationOverflow(Long.MIN_VALUE), is(true)); assertThat(willNegationOverflow(Long.MIN_VALUE + 1), is(false)); assertThat(willNegationOverflow(Long.MAX_VALUE), is(false)); assertThat(willNegationOverflow(1L), is(false)); assertThat(willNegationOverflow(-1L), is(false)); assertThat(willNegationOverflow(0L), is(false));
// Path: src/main/java/javafixes/math/OverflowUtil.java // class OverflowUtil { // // static boolean willNegationOverflow(long value) { // return value == Long.MIN_VALUE; // } // // static boolean didOverflowOnLongAddition(long result, long valueA, long valueB) { // // HD 2-12 Overflow iff both arguments have the opposite sign of the result // return ((valueA ^ result) & (valueB ^ result)) < 0; // } // // static boolean didOverflowOnMultiplication(long result, long valueA, long valueB) { // long absA = Math.abs(valueA); // long absB = Math.abs(valueB); // // if (((absA | absB) >>> 31 != 0)) { // // Some bits greater than 2^31 that might cause overflow // // Check the result using the divide operator // // and check for the special case of Long.MIN_VALUE * -1 // if (((valueB != 0) && (result / valueB != valueA)) || (valueA == Long.MIN_VALUE && valueB == -1)) { // return true; // } // } // return false; // } // } // // Path: src/test/java/javafixes/test/Random.java // @SafeVarargs // public static long randomLong(long from, long to, Function<Long, Boolean>... validityConditions) { // return generateValidValue( // // () -> new RandomDataGenerator().nextLong(from, to), // () -> ThreadLocalRandom.current().nextLong(from, to) + (long) randomInt(0, 1), // validityConditions // ); // } // Path: src/test/java/javafixes/math/OverflowUtilTest.java import org.junit.Test; import static javafixes.math.OverflowUtil.*; import static javafixes.test.Random.randomLong; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; package javafixes.math; public class OverflowUtilTest { @Test public void shouldFindIfNegationWillOverflow() { assertThat(willNegationOverflow(Long.MIN_VALUE), is(true)); assertThat(willNegationOverflow(Long.MIN_VALUE + 1), is(false)); assertThat(willNegationOverflow(Long.MAX_VALUE), is(false)); assertThat(willNegationOverflow(1L), is(false)); assertThat(willNegationOverflow(-1L), is(false)); assertThat(willNegationOverflow(0L), is(false));
assertThat(willNegationOverflow(randomLong(Long.MIN_VALUE + 1, Long.MAX_VALUE)), is(false));
MatejTymes/JavaFixes
src/main/java/javafixes/concurrency/Synchronizer.java
// Path: src/main/java/javafixes/common/function/Task.java // @FunctionalInterface // public interface Task { // // /** // * Executes a task or throws an exception if unable to do so. // * // * @throws Exception if unable to execute task // * @see Runner // * @see MonitoringTaskSubmitter // */ // void run() throws Exception; // } // // Path: src/main/java/javafixes/object/Tuple.java // public class Tuple<A, B> extends DataObject { // // public final A a; // public final B b; // // /** // * Constructor of {@code Tuple} with two values to wrap // * // * @param a first value // * @param b second value // */ // public Tuple(A a, B b) { // this.a = a; // this.b = b; // } // // /** // * Factory method to create {@code Tuple}. // * // * @param a first value // * @param b second value // * @param <A> first value type // * @param <B> second value type // * @return new {@code Tuple} // */ // public static <A, B> Tuple<A, B> tuple(A a, B b) { // return new Tuple<>(a, b); // } // // /** // * Returns first value // * // * @return first value // */ // public A getA() { // return a; // } // // /** // * Returns second value // * // * @return second value // */ // public B getB() { // return b; // } // // /** // * Returns first value // * // * @return first value // */ // public A a() { // return a; // } // // /** // * Returns second value // * // * @return second value // */ // public B b() { // return b; // } // // /** // * Maps wrapped values using a provided {@code BiFunction} // * // * @param mapper function to map wrapped values // * @param <C> the type of generated value // * @return value generated via the mapping function // */ // public <C> C map(BiFunction<? super A, ? super B, ? extends C> mapper) { // if (mapper == null) { // throw new IllegalArgumentException("Tuple mapper can't be null"); // } // return mapper.apply(a, b); // } // } // // Path: src/main/java/javafixes/object/Tuple.java // public static <A, B> Tuple<A, B> tuple(A a, B b) { // return new Tuple<>(a, b); // }
import javafixes.common.function.Task; import javafixes.object.Tuple; import java.util.Map; import java.util.concurrent.Callable; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.locks.StampedLock; import static javafixes.object.Tuple.tuple;
*/ public void synchronizeRunnableOn(K key, long time, TimeUnit unit, Runnable action) throws TimeoutException, InterruptedException, WrappedException { StampedLock lock = acquireLock(key); try { long stamp = lock.tryWriteLock(time, unit); if (stamp == 0) { throw new TimeoutException("Timed out while acquiring lock for key: " + key); } try { action.run(); } catch (Exception e) { throw new WrappedException("Failed to execute action", e); } finally { lock.unlock(stamp); } } finally { releaseLock(key); } } /** * Executes the provided {@link Task} while making sure that only one action * can be run for the provided {@code key} * * @param key value should be used for synchronization/locking purposes * @param action action that should be executed * * @throws WrappedException any exception thrown from the provided {@code action} is wrapped into a {@link WrappedException} */
// Path: src/main/java/javafixes/common/function/Task.java // @FunctionalInterface // public interface Task { // // /** // * Executes a task or throws an exception if unable to do so. // * // * @throws Exception if unable to execute task // * @see Runner // * @see MonitoringTaskSubmitter // */ // void run() throws Exception; // } // // Path: src/main/java/javafixes/object/Tuple.java // public class Tuple<A, B> extends DataObject { // // public final A a; // public final B b; // // /** // * Constructor of {@code Tuple} with two values to wrap // * // * @param a first value // * @param b second value // */ // public Tuple(A a, B b) { // this.a = a; // this.b = b; // } // // /** // * Factory method to create {@code Tuple}. // * // * @param a first value // * @param b second value // * @param <A> first value type // * @param <B> second value type // * @return new {@code Tuple} // */ // public static <A, B> Tuple<A, B> tuple(A a, B b) { // return new Tuple<>(a, b); // } // // /** // * Returns first value // * // * @return first value // */ // public A getA() { // return a; // } // // /** // * Returns second value // * // * @return second value // */ // public B getB() { // return b; // } // // /** // * Returns first value // * // * @return first value // */ // public A a() { // return a; // } // // /** // * Returns second value // * // * @return second value // */ // public B b() { // return b; // } // // /** // * Maps wrapped values using a provided {@code BiFunction} // * // * @param mapper function to map wrapped values // * @param <C> the type of generated value // * @return value generated via the mapping function // */ // public <C> C map(BiFunction<? super A, ? super B, ? extends C> mapper) { // if (mapper == null) { // throw new IllegalArgumentException("Tuple mapper can't be null"); // } // return mapper.apply(a, b); // } // } // // Path: src/main/java/javafixes/object/Tuple.java // public static <A, B> Tuple<A, B> tuple(A a, B b) { // return new Tuple<>(a, b); // } // Path: src/main/java/javafixes/concurrency/Synchronizer.java import javafixes.common.function.Task; import javafixes.object.Tuple; import java.util.Map; import java.util.concurrent.Callable; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.locks.StampedLock; import static javafixes.object.Tuple.tuple; */ public void synchronizeRunnableOn(K key, long time, TimeUnit unit, Runnable action) throws TimeoutException, InterruptedException, WrappedException { StampedLock lock = acquireLock(key); try { long stamp = lock.tryWriteLock(time, unit); if (stamp == 0) { throw new TimeoutException("Timed out while acquiring lock for key: " + key); } try { action.run(); } catch (Exception e) { throw new WrappedException("Failed to execute action", e); } finally { lock.unlock(stamp); } } finally { releaseLock(key); } } /** * Executes the provided {@link Task} while making sure that only one action * can be run for the provided {@code key} * * @param key value should be used for synchronization/locking purposes * @param action action that should be executed * * @throws WrappedException any exception thrown from the provided {@code action} is wrapped into a {@link WrappedException} */
public void synchronizeOn(K key, Task action) throws WrappedException {
MatejTymes/JavaFixes
src/main/java/javafixes/concurrency/Synchronizer.java
// Path: src/main/java/javafixes/common/function/Task.java // @FunctionalInterface // public interface Task { // // /** // * Executes a task or throws an exception if unable to do so. // * // * @throws Exception if unable to execute task // * @see Runner // * @see MonitoringTaskSubmitter // */ // void run() throws Exception; // } // // Path: src/main/java/javafixes/object/Tuple.java // public class Tuple<A, B> extends DataObject { // // public final A a; // public final B b; // // /** // * Constructor of {@code Tuple} with two values to wrap // * // * @param a first value // * @param b second value // */ // public Tuple(A a, B b) { // this.a = a; // this.b = b; // } // // /** // * Factory method to create {@code Tuple}. // * // * @param a first value // * @param b second value // * @param <A> first value type // * @param <B> second value type // * @return new {@code Tuple} // */ // public static <A, B> Tuple<A, B> tuple(A a, B b) { // return new Tuple<>(a, b); // } // // /** // * Returns first value // * // * @return first value // */ // public A getA() { // return a; // } // // /** // * Returns second value // * // * @return second value // */ // public B getB() { // return b; // } // // /** // * Returns first value // * // * @return first value // */ // public A a() { // return a; // } // // /** // * Returns second value // * // * @return second value // */ // public B b() { // return b; // } // // /** // * Maps wrapped values using a provided {@code BiFunction} // * // * @param mapper function to map wrapped values // * @param <C> the type of generated value // * @return value generated via the mapping function // */ // public <C> C map(BiFunction<? super A, ? super B, ? extends C> mapper) { // if (mapper == null) { // throw new IllegalArgumentException("Tuple mapper can't be null"); // } // return mapper.apply(a, b); // } // } // // Path: src/main/java/javafixes/object/Tuple.java // public static <A, B> Tuple<A, B> tuple(A a, B b) { // return new Tuple<>(a, b); // }
import javafixes.common.function.Task; import javafixes.object.Tuple; import java.util.Map; import java.util.concurrent.Callable; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.locks.StampedLock; import static javafixes.object.Tuple.tuple;
* @param action action that should be executed * * @throws TimeoutException if we can't acquire lock within the defined time * @throws InterruptedException if the current thread is interrupted before acquiring the lock * @throws WrappedException any exception thrown from the provided {@code action} is wrapped into a {@link WrappedException} */ public void synchronizeOn(K key, long time, TimeUnit unit, Task action) throws TimeoutException, InterruptedException, WrappedException { StampedLock lock = acquireLock(key); try { long stamp = lock.tryWriteLock(time, unit); if (stamp == 0) { throw new TimeoutException("Timed out while acquiring lock for key: " + key); } try { action.run(); } catch (Exception e) { throw new WrappedException("Failed to execute action", e); } finally { lock.unlock(stamp); } } finally { releaseLock(key); } } private StampedLock acquireLock(K key) { synchronized (counterWithLocks) { Tuple<AtomicInteger, StampedLock> counterWithLock = counterWithLocks.computeIfAbsent( key,
// Path: src/main/java/javafixes/common/function/Task.java // @FunctionalInterface // public interface Task { // // /** // * Executes a task or throws an exception if unable to do so. // * // * @throws Exception if unable to execute task // * @see Runner // * @see MonitoringTaskSubmitter // */ // void run() throws Exception; // } // // Path: src/main/java/javafixes/object/Tuple.java // public class Tuple<A, B> extends DataObject { // // public final A a; // public final B b; // // /** // * Constructor of {@code Tuple} with two values to wrap // * // * @param a first value // * @param b second value // */ // public Tuple(A a, B b) { // this.a = a; // this.b = b; // } // // /** // * Factory method to create {@code Tuple}. // * // * @param a first value // * @param b second value // * @param <A> first value type // * @param <B> second value type // * @return new {@code Tuple} // */ // public static <A, B> Tuple<A, B> tuple(A a, B b) { // return new Tuple<>(a, b); // } // // /** // * Returns first value // * // * @return first value // */ // public A getA() { // return a; // } // // /** // * Returns second value // * // * @return second value // */ // public B getB() { // return b; // } // // /** // * Returns first value // * // * @return first value // */ // public A a() { // return a; // } // // /** // * Returns second value // * // * @return second value // */ // public B b() { // return b; // } // // /** // * Maps wrapped values using a provided {@code BiFunction} // * // * @param mapper function to map wrapped values // * @param <C> the type of generated value // * @return value generated via the mapping function // */ // public <C> C map(BiFunction<? super A, ? super B, ? extends C> mapper) { // if (mapper == null) { // throw new IllegalArgumentException("Tuple mapper can't be null"); // } // return mapper.apply(a, b); // } // } // // Path: src/main/java/javafixes/object/Tuple.java // public static <A, B> Tuple<A, B> tuple(A a, B b) { // return new Tuple<>(a, b); // } // Path: src/main/java/javafixes/concurrency/Synchronizer.java import javafixes.common.function.Task; import javafixes.object.Tuple; import java.util.Map; import java.util.concurrent.Callable; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.locks.StampedLock; import static javafixes.object.Tuple.tuple; * @param action action that should be executed * * @throws TimeoutException if we can't acquire lock within the defined time * @throws InterruptedException if the current thread is interrupted before acquiring the lock * @throws WrappedException any exception thrown from the provided {@code action} is wrapped into a {@link WrappedException} */ public void synchronizeOn(K key, long time, TimeUnit unit, Task action) throws TimeoutException, InterruptedException, WrappedException { StampedLock lock = acquireLock(key); try { long stamp = lock.tryWriteLock(time, unit); if (stamp == 0) { throw new TimeoutException("Timed out while acquiring lock for key: " + key); } try { action.run(); } catch (Exception e) { throw new WrappedException("Failed to execute action", e); } finally { lock.unlock(stamp); } } finally { releaseLock(key); } } private StampedLock acquireLock(K key) { synchronized (counterWithLocks) { Tuple<AtomicInteger, StampedLock> counterWithLock = counterWithLocks.computeIfAbsent( key,
k -> tuple(new AtomicInteger(0), new StampedLock())
MatejTymes/JavaFixes
src/test/java/javafixes/test/Condition.java
// Path: src/main/java/javafixes/collection/CollectionUtil.java // @SafeVarargs // public static <T> HashSet<T> newSet(T... values) { // HashSet<T> set = new HashSet<T>(values.length); // Collections.addAll(set, values); // return set; // }
import java.math.BigDecimal; import java.math.BigInteger; import java.util.Set; import java.util.function.Function; import static javafixes.collection.CollectionUtil.newSet;
package javafixes.test; @FunctionalInterface public interface Condition<T> extends Function<T, Boolean> { BigInteger MIN_LONG_AS_BIG_INTEGER = BigInteger.valueOf(Long.MIN_VALUE); BigInteger MAX_LONG_AS_BIG_INTEGER = BigInteger.valueOf(Long.MAX_VALUE); @SafeVarargs static <T> Condition<T> otherThan(T... values) {
// Path: src/main/java/javafixes/collection/CollectionUtil.java // @SafeVarargs // public static <T> HashSet<T> newSet(T... values) { // HashSet<T> set = new HashSet<T>(values.length); // Collections.addAll(set, values); // return set; // } // Path: src/test/java/javafixes/test/Condition.java import java.math.BigDecimal; import java.math.BigInteger; import java.util.Set; import java.util.function.Function; import static javafixes.collection.CollectionUtil.newSet; package javafixes.test; @FunctionalInterface public interface Condition<T> extends Function<T, Boolean> { BigInteger MIN_LONG_AS_BIG_INTEGER = BigInteger.valueOf(Long.MIN_VALUE); BigInteger MAX_LONG_AS_BIG_INTEGER = BigInteger.valueOf(Long.MAX_VALUE); @SafeVarargs static <T> Condition<T> otherThan(T... values) {
Set<T> exclusions = newSet(values);
MatejTymes/JavaFixes
src/test/java/javafixes/math/ScaleTest.java
// Path: src/test/java/javafixes/test/Random.java // @SafeVarargs // public static int randomInt(int from, int to, Function<Integer, Boolean>... validityConditions) { // return generateValidValue( // // typecast it to long as otherwise we could get int overflow // () -> (int) ((long) (Math.random() * ((long) to - (long) from + 1L)) + (long) from), // validityConditions // ); // }
import org.junit.Test; import static javafixes.test.Random.randomInt; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertThat;
package javafixes.math; public class ScaleTest { @Test public void shouldBeAbleToCreateScale() { assertThat(Scale.of(Integer.MIN_VALUE).value, equalTo(Integer.MIN_VALUE)); assertThat(Scale.scale(Integer.MIN_VALUE).value, equalTo(Integer.MIN_VALUE)); assertThat(Scale.of(Integer.MAX_VALUE).value, equalTo(Integer.MAX_VALUE)); assertThat(Scale.scale(Integer.MAX_VALUE).value, equalTo(Integer.MAX_VALUE)); assertThat(Scale.of(0).value, equalTo(0)); assertThat(Scale.scale(0).value, equalTo(0)); assertThat(Scale.of(-1).value, equalTo(-1)); assertThat(Scale.scale(-1).value, equalTo(-1)); assertThat(Scale.of(1).value, equalTo(1)); assertThat(Scale.scale(1).value, equalTo(1));
// Path: src/test/java/javafixes/test/Random.java // @SafeVarargs // public static int randomInt(int from, int to, Function<Integer, Boolean>... validityConditions) { // return generateValidValue( // // typecast it to long as otherwise we could get int overflow // () -> (int) ((long) (Math.random() * ((long) to - (long) from + 1L)) + (long) from), // validityConditions // ); // } // Path: src/test/java/javafixes/math/ScaleTest.java import org.junit.Test; import static javafixes.test.Random.randomInt; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertThat; package javafixes.math; public class ScaleTest { @Test public void shouldBeAbleToCreateScale() { assertThat(Scale.of(Integer.MIN_VALUE).value, equalTo(Integer.MIN_VALUE)); assertThat(Scale.scale(Integer.MIN_VALUE).value, equalTo(Integer.MIN_VALUE)); assertThat(Scale.of(Integer.MAX_VALUE).value, equalTo(Integer.MAX_VALUE)); assertThat(Scale.scale(Integer.MAX_VALUE).value, equalTo(Integer.MAX_VALUE)); assertThat(Scale.of(0).value, equalTo(0)); assertThat(Scale.scale(0).value, equalTo(0)); assertThat(Scale.of(-1).value, equalTo(-1)); assertThat(Scale.scale(-1).value, equalTo(-1)); assertThat(Scale.of(1).value, equalTo(1)); assertThat(Scale.scale(1).value, equalTo(1));
int positiveValue = randomInt(2, Integer.MAX_VALUE - 1);
MatejTymes/JavaFixes
src/test/java/javafixes/io/ByteCollectingOutputStreamTest.java
// Path: src/test/java/javafixes/test/Random.java // @SafeVarargs // public static int randomInt(int from, int to, Function<Integer, Boolean>... validityConditions) { // return generateValidValue( // // typecast it to long as otherwise we could get int overflow // () -> (int) ((long) (Math.random() * ((long) to - (long) from + 1L)) + (long) from), // validityConditions // ); // }
import org.apache.commons.io.IOUtils; import org.junit.Test; import java.io.ByteArrayOutputStream; import java.io.IOException; import static java.util.UUID.randomUUID; import static javafixes.test.Random.randomInt; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo;
package javafixes.io; public class ByteCollectingOutputStreamTest { @Test public void shouldCollectBytes() throws IOException { String text = "This is a random string " + randomUUID() + " with some random " + randomUUID() + " values in it"; String charsetName = "UTF-8";
// Path: src/test/java/javafixes/test/Random.java // @SafeVarargs // public static int randomInt(int from, int to, Function<Integer, Boolean>... validityConditions) { // return generateValidValue( // // typecast it to long as otherwise we could get int overflow // () -> (int) ((long) (Math.random() * ((long) to - (long) from + 1L)) + (long) from), // validityConditions // ); // } // Path: src/test/java/javafixes/io/ByteCollectingOutputStreamTest.java import org.apache.commons.io.IOUtils; import org.junit.Test; import java.io.ByteArrayOutputStream; import java.io.IOException; import static java.util.UUID.randomUUID; import static javafixes.test.Random.randomInt; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; package javafixes.io; public class ByteCollectingOutputStreamTest { @Test public void shouldCollectBytes() throws IOException { String text = "This is a random string " + randomUUID() + " with some random " + randomUUID() + " values in it"; String charsetName = "UTF-8";
ByteCollectingOutputStream stream = new ByteCollectingOutputStream(randomInt(1, 20));
MatejTymes/JavaFixes
src/test/java/javafixes/math/DecimalPrecisionTest.java
// Path: src/main/java/javafixes/math/Decimal.java // public static Decimal decimal(long unscaledValue, int scale) throws ArithmeticException { // while (unscaledValue != 0 // && ((int) unscaledValue & 1) == 0 // && unscaledValue % 10 == 0) { // unscaledValue /= 10; // // if (scale == Integer.MIN_VALUE) { // throw new ArithmeticException(format("Scale underflow - can't set scale to less than '%d'", Integer.MIN_VALUE)); // } // scale--; // } // // return new LongDecimal(unscaledValue, scale); // } // // Path: src/test/java/javafixes/test/Random.java // @SafeVarargs // public static int randomInt(int from, int to, Function<Integer, Boolean>... validityConditions) { // return generateValidValue( // // typecast it to long as otherwise we could get int overflow // () -> (int) ((long) (Math.random() * ((long) to - (long) from + 1L)) + (long) from), // validityConditions // ); // }
import org.junit.Test; import java.math.BigInteger; import static javafixes.math.Decimal.decimal; import static javafixes.test.Random.randomInt; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertThat;
package javafixes.math; public class DecimalPrecisionTest { @Test public void shouldFindNumberOfLongDigits() {
// Path: src/main/java/javafixes/math/Decimal.java // public static Decimal decimal(long unscaledValue, int scale) throws ArithmeticException { // while (unscaledValue != 0 // && ((int) unscaledValue & 1) == 0 // && unscaledValue % 10 == 0) { // unscaledValue /= 10; // // if (scale == Integer.MIN_VALUE) { // throw new ArithmeticException(format("Scale underflow - can't set scale to less than '%d'", Integer.MIN_VALUE)); // } // scale--; // } // // return new LongDecimal(unscaledValue, scale); // } // // Path: src/test/java/javafixes/test/Random.java // @SafeVarargs // public static int randomInt(int from, int to, Function<Integer, Boolean>... validityConditions) { // return generateValidValue( // // typecast it to long as otherwise we could get int overflow // () -> (int) ((long) (Math.random() * ((long) to - (long) from + 1L)) + (long) from), // validityConditions // ); // } // Path: src/test/java/javafixes/math/DecimalPrecisionTest.java import org.junit.Test; import java.math.BigInteger; import static javafixes.math.Decimal.decimal; import static javafixes.test.Random.randomInt; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertThat; package javafixes.math; public class DecimalPrecisionTest { @Test public void shouldFindNumberOfLongDigits() {
assertThat(decimal(0, randomInt()).precision(), equalTo(1));
MatejTymes/JavaFixes
src/test/java/javafixes/math/DecimalPrecisionTest.java
// Path: src/main/java/javafixes/math/Decimal.java // public static Decimal decimal(long unscaledValue, int scale) throws ArithmeticException { // while (unscaledValue != 0 // && ((int) unscaledValue & 1) == 0 // && unscaledValue % 10 == 0) { // unscaledValue /= 10; // // if (scale == Integer.MIN_VALUE) { // throw new ArithmeticException(format("Scale underflow - can't set scale to less than '%d'", Integer.MIN_VALUE)); // } // scale--; // } // // return new LongDecimal(unscaledValue, scale); // } // // Path: src/test/java/javafixes/test/Random.java // @SafeVarargs // public static int randomInt(int from, int to, Function<Integer, Boolean>... validityConditions) { // return generateValidValue( // // typecast it to long as otherwise we could get int overflow // () -> (int) ((long) (Math.random() * ((long) to - (long) from + 1L)) + (long) from), // validityConditions // ); // }
import org.junit.Test; import java.math.BigInteger; import static javafixes.math.Decimal.decimal; import static javafixes.test.Random.randomInt; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertThat;
package javafixes.math; public class DecimalPrecisionTest { @Test public void shouldFindNumberOfLongDigits() {
// Path: src/main/java/javafixes/math/Decimal.java // public static Decimal decimal(long unscaledValue, int scale) throws ArithmeticException { // while (unscaledValue != 0 // && ((int) unscaledValue & 1) == 0 // && unscaledValue % 10 == 0) { // unscaledValue /= 10; // // if (scale == Integer.MIN_VALUE) { // throw new ArithmeticException(format("Scale underflow - can't set scale to less than '%d'", Integer.MIN_VALUE)); // } // scale--; // } // // return new LongDecimal(unscaledValue, scale); // } // // Path: src/test/java/javafixes/test/Random.java // @SafeVarargs // public static int randomInt(int from, int to, Function<Integer, Boolean>... validityConditions) { // return generateValidValue( // // typecast it to long as otherwise we could get int overflow // () -> (int) ((long) (Math.random() * ((long) to - (long) from + 1L)) + (long) from), // validityConditions // ); // } // Path: src/test/java/javafixes/math/DecimalPrecisionTest.java import org.junit.Test; import java.math.BigInteger; import static javafixes.math.Decimal.decimal; import static javafixes.test.Random.randomInt; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertThat; package javafixes.math; public class DecimalPrecisionTest { @Test public void shouldFindNumberOfLongDigits() {
assertThat(decimal(0, randomInt()).precision(), equalTo(1));
MatejTymes/JavaFixes
src/test/java/javafixes/test/CollectionUtil.java
// Path: src/main/java/javafixes/collection/CollectionUtil.java // @SafeVarargs // public static <T> ArrayList<T> newList(T... values) { // ArrayList<T> list = new ArrayList<T>(values.length); // Collections.addAll(list, values); // return list; // }
import java.util.Collection; import java.util.List; import static java.util.Arrays.asList; import static javafixes.collection.CollectionUtil.newList;
package javafixes.test; public class CollectionUtil { @SafeVarargs public static <T, CT extends Collection<T>> CT removeFrom(CT values, T... valuesToRemove) { values.removeAll(asList(valuesToRemove)); return values; } @SafeVarargs public static <T> List<T> removeFrom(T[] values, T... valuesToRemove) {
// Path: src/main/java/javafixes/collection/CollectionUtil.java // @SafeVarargs // public static <T> ArrayList<T> newList(T... values) { // ArrayList<T> list = new ArrayList<T>(values.length); // Collections.addAll(list, values); // return list; // } // Path: src/test/java/javafixes/test/CollectionUtil.java import java.util.Collection; import java.util.List; import static java.util.Arrays.asList; import static javafixes.collection.CollectionUtil.newList; package javafixes.test; public class CollectionUtil { @SafeVarargs public static <T, CT extends Collection<T>> CT removeFrom(CT values, T... valuesToRemove) { values.removeAll(asList(valuesToRemove)); return values; } @SafeVarargs public static <T> List<T> removeFrom(T[] values, T... valuesToRemove) {
return removeFrom(newList(values), valuesToRemove);
MatejTymes/JavaFixes
src/test/java/javafixes/concurrency/RunnerTest.java
// Path: src/main/java/javafixes/collection/CollectionUtil.java // @SafeVarargs // public static <T> ArrayList<T> newList(T... values) { // ArrayList<T> list = new ArrayList<T>(values.length); // Collections.addAll(list, values); // return list; // } // // Path: src/test/java/javafixes/test/Random.java // @SafeVarargs // public static long randomLong(long from, long to, Function<Long, Boolean>... validityConditions) { // return generateValidValue( // // () -> new RandomDataGenerator().nextLong(from, to), // () -> ThreadLocalRandom.current().nextLong(from, to) + (long) randomInt(0, 1), // validityConditions // ); // }
import org.junit.Test; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Consumer; import static javafixes.collection.CollectionUtil.newList; import static javafixes.test.Random.randomLong; import static org.hamcrest.Matchers.greaterThan; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat;
package javafixes.concurrency; public class RunnerTest extends BaseExecutorTest { protected Runner executor; @Override protected void initializeExecutor() { // create executor with 10 threads executor = Runner.runner(10); } @Override protected void shutdownExecutor() throws InterruptedException { executor.shutdownAndAwaitTermination(); } @Override protected MonitoringTaskSubmitter executor() { return executor; } @Test public void shouldNotDeadlockOnShutdownNow() { // fill the queue for (int i = 0; i < 10_000; i++) { executor.run(this::doSomethingThatTakesTime); } // When executor.shutdownNow(); // Then boolean done = executor.waitTillDone(3, TimeUnit.SECONDS); assertThat(done, is(true)); assertThat(executor.toBeCompletedCount(), is(0)); assertThat(executor.failedToStartCount(), greaterThan(0)); } @Test public void shouldInformShutdownAwareTasksThatShutdownHasBeenTriggered() throws InterruptedException {
// Path: src/main/java/javafixes/collection/CollectionUtil.java // @SafeVarargs // public static <T> ArrayList<T> newList(T... values) { // ArrayList<T> list = new ArrayList<T>(values.length); // Collections.addAll(list, values); // return list; // } // // Path: src/test/java/javafixes/test/Random.java // @SafeVarargs // public static long randomLong(long from, long to, Function<Long, Boolean>... validityConditions) { // return generateValidValue( // // () -> new RandomDataGenerator().nextLong(from, to), // () -> ThreadLocalRandom.current().nextLong(from, to) + (long) randomInt(0, 1), // validityConditions // ); // } // Path: src/test/java/javafixes/concurrency/RunnerTest.java import org.junit.Test; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Consumer; import static javafixes.collection.CollectionUtil.newList; import static javafixes.test.Random.randomLong; import static org.hamcrest.Matchers.greaterThan; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; package javafixes.concurrency; public class RunnerTest extends BaseExecutorTest { protected Runner executor; @Override protected void initializeExecutor() { // create executor with 10 threads executor = Runner.runner(10); } @Override protected void shutdownExecutor() throws InterruptedException { executor.shutdownAndAwaitTermination(); } @Override protected MonitoringTaskSubmitter executor() { return executor; } @Test public void shouldNotDeadlockOnShutdownNow() { // fill the queue for (int i = 0; i < 10_000; i++) { executor.run(this::doSomethingThatTakesTime); } // When executor.shutdownNow(); // Then boolean done = executor.waitTillDone(3, TimeUnit.SECONDS); assertThat(done, is(true)); assertThat(executor.toBeCompletedCount(), is(0)); assertThat(executor.failedToStartCount(), greaterThan(0)); } @Test public void shouldInformShutdownAwareTasksThatShutdownHasBeenTriggered() throws InterruptedException {
List<Consumer<Runner>> shutdownMethods = newList(
MatejTymes/JavaFixes
src/test/java/javafixes/concurrency/RunnerTest.java
// Path: src/main/java/javafixes/collection/CollectionUtil.java // @SafeVarargs // public static <T> ArrayList<T> newList(T... values) { // ArrayList<T> list = new ArrayList<T>(values.length); // Collections.addAll(list, values); // return list; // } // // Path: src/test/java/javafixes/test/Random.java // @SafeVarargs // public static long randomLong(long from, long to, Function<Long, Boolean>... validityConditions) { // return generateValidValue( // // () -> new RandomDataGenerator().nextLong(from, to), // () -> ThreadLocalRandom.current().nextLong(from, to) + (long) randomInt(0, 1), // validityConditions // ); // }
import org.junit.Test; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Consumer; import static javafixes.collection.CollectionUtil.newList; import static javafixes.test.Random.randomLong; import static org.hamcrest.Matchers.greaterThan; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat;
public void shouldInformShutdownAwareTasksThatShutdownHasBeenTriggered() throws InterruptedException { List<Consumer<Runner>> shutdownMethods = newList( Runner::shutdown, Runner::shutdownNow ); List<ShutdownAwareRunCheck> shutdownAwareRunChecks = newList( (runner, startCheck, endCheck, wasShutdownInfoReceived) -> runner.run(shutdownInfo -> { // startCheck.countDown(); while (!shutdownInfo.wasShutdownTriggered()) { doSomethingThatTakesTime(); } wasShutdownInfoReceived.set(shutdownInfo.wasShutdownTriggered()); endCheck.countDown(); return 0; }), (runner, startCheck, endCheck, wasShutdownInfoReceived) -> runner.run(shutdownInfo -> { startCheck.countDown(); while (!shutdownInfo.wasShutdownTriggered()) { doSomethingThatTakesTime(); } wasShutdownInfoReceived.set(shutdownInfo.wasShutdownTriggered()); endCheck.countDown(); }),
// Path: src/main/java/javafixes/collection/CollectionUtil.java // @SafeVarargs // public static <T> ArrayList<T> newList(T... values) { // ArrayList<T> list = new ArrayList<T>(values.length); // Collections.addAll(list, values); // return list; // } // // Path: src/test/java/javafixes/test/Random.java // @SafeVarargs // public static long randomLong(long from, long to, Function<Long, Boolean>... validityConditions) { // return generateValidValue( // // () -> new RandomDataGenerator().nextLong(from, to), // () -> ThreadLocalRandom.current().nextLong(from, to) + (long) randomInt(0, 1), // validityConditions // ); // } // Path: src/test/java/javafixes/concurrency/RunnerTest.java import org.junit.Test; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Consumer; import static javafixes.collection.CollectionUtil.newList; import static javafixes.test.Random.randomLong; import static org.hamcrest.Matchers.greaterThan; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; public void shouldInformShutdownAwareTasksThatShutdownHasBeenTriggered() throws InterruptedException { List<Consumer<Runner>> shutdownMethods = newList( Runner::shutdown, Runner::shutdownNow ); List<ShutdownAwareRunCheck> shutdownAwareRunChecks = newList( (runner, startCheck, endCheck, wasShutdownInfoReceived) -> runner.run(shutdownInfo -> { // startCheck.countDown(); while (!shutdownInfo.wasShutdownTriggered()) { doSomethingThatTakesTime(); } wasShutdownInfoReceived.set(shutdownInfo.wasShutdownTriggered()); endCheck.countDown(); return 0; }), (runner, startCheck, endCheck, wasShutdownInfoReceived) -> runner.run(shutdownInfo -> { startCheck.countDown(); while (!shutdownInfo.wasShutdownTriggered()) { doSomethingThatTakesTime(); } wasShutdownInfoReceived.set(shutdownInfo.wasShutdownTriggered()); endCheck.countDown(); }),
(runner, startCheck, endCheck, wasShutdownInfoReceived) -> runner.runIn(randomLong(100, 300), TimeUnit.MILLISECONDS, shutdownInfo -> { //
MatejTymes/JavaFixes
src/test/java/javafixes/math/DecimalDescaleTest.java
// Path: src/main/java/javafixes/collection/CollectionUtil.java // @SafeVarargs // public static <T> ArrayList<T> newList(T... values) { // ArrayList<T> list = new ArrayList<T>(values.length); // Collections.addAll(list, values); // return list; // } // // Path: src/main/java/javafixes/math/Decimal.java // public static Decimal d(long unscaledValue, int scale) throws ArithmeticException { // return decimal(unscaledValue, scale); // } // // Path: src/main/java/javafixes/math/Decimal.java // public static Decimal decimal(long unscaledValue, int scale) throws ArithmeticException { // while (unscaledValue != 0 // && ((int) unscaledValue & 1) == 0 // && unscaledValue % 10 == 0) { // unscaledValue /= 10; // // if (scale == Integer.MIN_VALUE) { // throw new ArithmeticException(format("Scale underflow - can't set scale to less than '%d'", Integer.MIN_VALUE)); // } // scale--; // } // // return new LongDecimal(unscaledValue, scale); // } // // Path: src/test/java/javafixes/test/Random.java // @SafeVarargs // public static int randomInt(int from, int to, Function<Integer, Boolean>... validityConditions) { // return generateValidValue( // // typecast it to long as otherwise we could get int overflow // () -> (int) ((long) (Math.random() * ((long) to - (long) from + 1L)) + (long) from), // validityConditions // ); // }
import org.junit.Test; import java.math.RoundingMode; import java.util.List; import static javafixes.collection.CollectionUtil.newList; import static javafixes.math.Decimal.d; import static javafixes.math.Decimal.decimal; import static javafixes.test.Random.randomInt; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail;
package javafixes.math; public class DecimalDescaleTest { @Test public void shouldDescaleAndRoundValueProperly() {
// Path: src/main/java/javafixes/collection/CollectionUtil.java // @SafeVarargs // public static <T> ArrayList<T> newList(T... values) { // ArrayList<T> list = new ArrayList<T>(values.length); // Collections.addAll(list, values); // return list; // } // // Path: src/main/java/javafixes/math/Decimal.java // public static Decimal d(long unscaledValue, int scale) throws ArithmeticException { // return decimal(unscaledValue, scale); // } // // Path: src/main/java/javafixes/math/Decimal.java // public static Decimal decimal(long unscaledValue, int scale) throws ArithmeticException { // while (unscaledValue != 0 // && ((int) unscaledValue & 1) == 0 // && unscaledValue % 10 == 0) { // unscaledValue /= 10; // // if (scale == Integer.MIN_VALUE) { // throw new ArithmeticException(format("Scale underflow - can't set scale to less than '%d'", Integer.MIN_VALUE)); // } // scale--; // } // // return new LongDecimal(unscaledValue, scale); // } // // Path: src/test/java/javafixes/test/Random.java // @SafeVarargs // public static int randomInt(int from, int to, Function<Integer, Boolean>... validityConditions) { // return generateValidValue( // // typecast it to long as otherwise we could get int overflow // () -> (int) ((long) (Math.random() * ((long) to - (long) from + 1L)) + (long) from), // validityConditions // ); // } // Path: src/test/java/javafixes/math/DecimalDescaleTest.java import org.junit.Test; import java.math.RoundingMode; import java.util.List; import static javafixes.collection.CollectionUtil.newList; import static javafixes.math.Decimal.d; import static javafixes.math.Decimal.decimal; import static javafixes.test.Random.randomInt; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; package javafixes.math; public class DecimalDescaleTest { @Test public void shouldDescaleAndRoundValueProperly() {
assertThat(decimal("5.5").descaleTo(0, RoundingMode.UP), equalTo(decimal("6")));
MatejTymes/JavaFixes
src/test/java/javafixes/math/DecimalDescaleTest.java
// Path: src/main/java/javafixes/collection/CollectionUtil.java // @SafeVarargs // public static <T> ArrayList<T> newList(T... values) { // ArrayList<T> list = new ArrayList<T>(values.length); // Collections.addAll(list, values); // return list; // } // // Path: src/main/java/javafixes/math/Decimal.java // public static Decimal d(long unscaledValue, int scale) throws ArithmeticException { // return decimal(unscaledValue, scale); // } // // Path: src/main/java/javafixes/math/Decimal.java // public static Decimal decimal(long unscaledValue, int scale) throws ArithmeticException { // while (unscaledValue != 0 // && ((int) unscaledValue & 1) == 0 // && unscaledValue % 10 == 0) { // unscaledValue /= 10; // // if (scale == Integer.MIN_VALUE) { // throw new ArithmeticException(format("Scale underflow - can't set scale to less than '%d'", Integer.MIN_VALUE)); // } // scale--; // } // // return new LongDecimal(unscaledValue, scale); // } // // Path: src/test/java/javafixes/test/Random.java // @SafeVarargs // public static int randomInt(int from, int to, Function<Integer, Boolean>... validityConditions) { // return generateValidValue( // // typecast it to long as otherwise we could get int overflow // () -> (int) ((long) (Math.random() * ((long) to - (long) from + 1L)) + (long) from), // validityConditions // ); // }
import org.junit.Test; import java.math.RoundingMode; import java.util.List; import static javafixes.collection.CollectionUtil.newList; import static javafixes.math.Decimal.d; import static javafixes.math.Decimal.decimal; import static javafixes.test.Random.randomInt; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail;
assertThat(decimal("1.001").descaleTo(0, RoundingMode.HALF_EVEN), equalTo(decimal("1"))); assertThat(decimal("0.001").descaleTo(0, RoundingMode.HALF_EVEN), equalTo(decimal("0"))); assertThat(decimal("-0.001").descaleTo(0, RoundingMode.HALF_EVEN), equalTo(decimal("0"))); assertThat(decimal("-1.001").descaleTo(0, RoundingMode.HALF_EVEN), equalTo(decimal("-1"))); assertThat(decimal("-2.501").descaleTo(0, RoundingMode.HALF_EVEN), equalTo(decimal("-3"))); assertThat(decimal("-5.501").descaleTo(0, RoundingMode.HALF_EVEN), equalTo(decimal("-6"))); try { decimal("5.5").descaleTo(0, RoundingMode.UNNECESSARY); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { } try { decimal("2.5").descaleTo(0, RoundingMode.UNNECESSARY); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { } try { decimal("1.6").descaleTo(0, RoundingMode.UNNECESSARY); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { } try { decimal("1.1").descaleTo(0, RoundingMode.UNNECESSARY); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { } assertThat(decimal("1.0").descaleTo(0, RoundingMode.UNNECESSARY), equalTo(decimal("1"))); assertThat(decimal("-1.0").descaleTo(0, RoundingMode.UNNECESSARY), equalTo(decimal("-1"))); try { decimal("-1.1").descaleTo(0, RoundingMode.UNNECESSARY); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { } try { decimal("-1.6").descaleTo(0, RoundingMode.UNNECESSARY); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { } try { decimal("-2.5").descaleTo(0, RoundingMode.UNNECESSARY); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { } try { decimal("-5.5").descaleTo(0, RoundingMode.UNNECESSARY); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { } try { decimal("5.501").descaleTo(0, RoundingMode.UNNECESSARY); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { } try { decimal("2.501").descaleTo(0, RoundingMode.UNNECESSARY); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { } try { decimal("1.001").descaleTo(0, RoundingMode.UNNECESSARY); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { } try { decimal("0.001").descaleTo(0, RoundingMode.UNNECESSARY); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { } try { decimal("-0.001").descaleTo(0, RoundingMode.UNNECESSARY); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { } try { decimal("-1.001").descaleTo(0, RoundingMode.UNNECESSARY); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { } try { decimal("-2.501").descaleTo(0, RoundingMode.UNNECESSARY); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { } try { decimal("-5.501").descaleTo(0, RoundingMode.UNNECESSARY); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { } } @Test public void shouldDoNothingWhenDescaleOfLongDecimalIsNotNeeded() {
// Path: src/main/java/javafixes/collection/CollectionUtil.java // @SafeVarargs // public static <T> ArrayList<T> newList(T... values) { // ArrayList<T> list = new ArrayList<T>(values.length); // Collections.addAll(list, values); // return list; // } // // Path: src/main/java/javafixes/math/Decimal.java // public static Decimal d(long unscaledValue, int scale) throws ArithmeticException { // return decimal(unscaledValue, scale); // } // // Path: src/main/java/javafixes/math/Decimal.java // public static Decimal decimal(long unscaledValue, int scale) throws ArithmeticException { // while (unscaledValue != 0 // && ((int) unscaledValue & 1) == 0 // && unscaledValue % 10 == 0) { // unscaledValue /= 10; // // if (scale == Integer.MIN_VALUE) { // throw new ArithmeticException(format("Scale underflow - can't set scale to less than '%d'", Integer.MIN_VALUE)); // } // scale--; // } // // return new LongDecimal(unscaledValue, scale); // } // // Path: src/test/java/javafixes/test/Random.java // @SafeVarargs // public static int randomInt(int from, int to, Function<Integer, Boolean>... validityConditions) { // return generateValidValue( // // typecast it to long as otherwise we could get int overflow // () -> (int) ((long) (Math.random() * ((long) to - (long) from + 1L)) + (long) from), // validityConditions // ); // } // Path: src/test/java/javafixes/math/DecimalDescaleTest.java import org.junit.Test; import java.math.RoundingMode; import java.util.List; import static javafixes.collection.CollectionUtil.newList; import static javafixes.math.Decimal.d; import static javafixes.math.Decimal.decimal; import static javafixes.test.Random.randomInt; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; assertThat(decimal("1.001").descaleTo(0, RoundingMode.HALF_EVEN), equalTo(decimal("1"))); assertThat(decimal("0.001").descaleTo(0, RoundingMode.HALF_EVEN), equalTo(decimal("0"))); assertThat(decimal("-0.001").descaleTo(0, RoundingMode.HALF_EVEN), equalTo(decimal("0"))); assertThat(decimal("-1.001").descaleTo(0, RoundingMode.HALF_EVEN), equalTo(decimal("-1"))); assertThat(decimal("-2.501").descaleTo(0, RoundingMode.HALF_EVEN), equalTo(decimal("-3"))); assertThat(decimal("-5.501").descaleTo(0, RoundingMode.HALF_EVEN), equalTo(decimal("-6"))); try { decimal("5.5").descaleTo(0, RoundingMode.UNNECESSARY); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { } try { decimal("2.5").descaleTo(0, RoundingMode.UNNECESSARY); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { } try { decimal("1.6").descaleTo(0, RoundingMode.UNNECESSARY); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { } try { decimal("1.1").descaleTo(0, RoundingMode.UNNECESSARY); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { } assertThat(decimal("1.0").descaleTo(0, RoundingMode.UNNECESSARY), equalTo(decimal("1"))); assertThat(decimal("-1.0").descaleTo(0, RoundingMode.UNNECESSARY), equalTo(decimal("-1"))); try { decimal("-1.1").descaleTo(0, RoundingMode.UNNECESSARY); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { } try { decimal("-1.6").descaleTo(0, RoundingMode.UNNECESSARY); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { } try { decimal("-2.5").descaleTo(0, RoundingMode.UNNECESSARY); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { } try { decimal("-5.5").descaleTo(0, RoundingMode.UNNECESSARY); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { } try { decimal("5.501").descaleTo(0, RoundingMode.UNNECESSARY); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { } try { decimal("2.501").descaleTo(0, RoundingMode.UNNECESSARY); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { } try { decimal("1.001").descaleTo(0, RoundingMode.UNNECESSARY); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { } try { decimal("0.001").descaleTo(0, RoundingMode.UNNECESSARY); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { } try { decimal("-0.001").descaleTo(0, RoundingMode.UNNECESSARY); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { } try { decimal("-1.001").descaleTo(0, RoundingMode.UNNECESSARY); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { } try { decimal("-2.501").descaleTo(0, RoundingMode.UNNECESSARY); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { } try { decimal("-5.501").descaleTo(0, RoundingMode.UNNECESSARY); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { } } @Test public void shouldDoNothingWhenDescaleOfLongDecimalIsNotNeeded() {
newList(
MatejTymes/JavaFixes
src/test/java/javafixes/math/DecimalDescaleTest.java
// Path: src/main/java/javafixes/collection/CollectionUtil.java // @SafeVarargs // public static <T> ArrayList<T> newList(T... values) { // ArrayList<T> list = new ArrayList<T>(values.length); // Collections.addAll(list, values); // return list; // } // // Path: src/main/java/javafixes/math/Decimal.java // public static Decimal d(long unscaledValue, int scale) throws ArithmeticException { // return decimal(unscaledValue, scale); // } // // Path: src/main/java/javafixes/math/Decimal.java // public static Decimal decimal(long unscaledValue, int scale) throws ArithmeticException { // while (unscaledValue != 0 // && ((int) unscaledValue & 1) == 0 // && unscaledValue % 10 == 0) { // unscaledValue /= 10; // // if (scale == Integer.MIN_VALUE) { // throw new ArithmeticException(format("Scale underflow - can't set scale to less than '%d'", Integer.MIN_VALUE)); // } // scale--; // } // // return new LongDecimal(unscaledValue, scale); // } // // Path: src/test/java/javafixes/test/Random.java // @SafeVarargs // public static int randomInt(int from, int to, Function<Integer, Boolean>... validityConditions) { // return generateValidValue( // // typecast it to long as otherwise we could get int overflow // () -> (int) ((long) (Math.random() * ((long) to - (long) from + 1L)) + (long) from), // validityConditions // ); // }
import org.junit.Test; import java.math.RoundingMode; import java.util.List; import static javafixes.collection.CollectionUtil.newList; import static javafixes.math.Decimal.d; import static javafixes.math.Decimal.decimal; import static javafixes.test.Random.randomInt; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail;
try { decimal("-2.5").descaleTo(0, RoundingMode.UNNECESSARY); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { } try { decimal("-5.5").descaleTo(0, RoundingMode.UNNECESSARY); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { } try { decimal("5.501").descaleTo(0, RoundingMode.UNNECESSARY); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { } try { decimal("2.501").descaleTo(0, RoundingMode.UNNECESSARY); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { } try { decimal("1.001").descaleTo(0, RoundingMode.UNNECESSARY); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { } try { decimal("0.001").descaleTo(0, RoundingMode.UNNECESSARY); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { } try { decimal("-0.001").descaleTo(0, RoundingMode.UNNECESSARY); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { } try { decimal("-1.001").descaleTo(0, RoundingMode.UNNECESSARY); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { } try { decimal("-2.501").descaleTo(0, RoundingMode.UNNECESSARY); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { } try { decimal("-5.501").descaleTo(0, RoundingMode.UNNECESSARY); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { } } @Test public void shouldDoNothingWhenDescaleOfLongDecimalIsNotNeeded() { newList( "5.5", "2.5", "1.6", "1.1", "1.0", "-1.0", "-1.1", "-1.6", "-2.5", "-5.5" ).forEach(value -> { for (RoundingMode roundingMode : RoundingMode.values()) { assertThat(decimal(value).descaleTo(1, roundingMode), equalTo(decimal(value))); assertThat(decimal(value).descaleTo(Integer.MAX_VALUE, roundingMode), equalTo(decimal(value)));
// Path: src/main/java/javafixes/collection/CollectionUtil.java // @SafeVarargs // public static <T> ArrayList<T> newList(T... values) { // ArrayList<T> list = new ArrayList<T>(values.length); // Collections.addAll(list, values); // return list; // } // // Path: src/main/java/javafixes/math/Decimal.java // public static Decimal d(long unscaledValue, int scale) throws ArithmeticException { // return decimal(unscaledValue, scale); // } // // Path: src/main/java/javafixes/math/Decimal.java // public static Decimal decimal(long unscaledValue, int scale) throws ArithmeticException { // while (unscaledValue != 0 // && ((int) unscaledValue & 1) == 0 // && unscaledValue % 10 == 0) { // unscaledValue /= 10; // // if (scale == Integer.MIN_VALUE) { // throw new ArithmeticException(format("Scale underflow - can't set scale to less than '%d'", Integer.MIN_VALUE)); // } // scale--; // } // // return new LongDecimal(unscaledValue, scale); // } // // Path: src/test/java/javafixes/test/Random.java // @SafeVarargs // public static int randomInt(int from, int to, Function<Integer, Boolean>... validityConditions) { // return generateValidValue( // // typecast it to long as otherwise we could get int overflow // () -> (int) ((long) (Math.random() * ((long) to - (long) from + 1L)) + (long) from), // validityConditions // ); // } // Path: src/test/java/javafixes/math/DecimalDescaleTest.java import org.junit.Test; import java.math.RoundingMode; import java.util.List; import static javafixes.collection.CollectionUtil.newList; import static javafixes.math.Decimal.d; import static javafixes.math.Decimal.decimal; import static javafixes.test.Random.randomInt; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; try { decimal("-2.5").descaleTo(0, RoundingMode.UNNECESSARY); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { } try { decimal("-5.5").descaleTo(0, RoundingMode.UNNECESSARY); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { } try { decimal("5.501").descaleTo(0, RoundingMode.UNNECESSARY); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { } try { decimal("2.501").descaleTo(0, RoundingMode.UNNECESSARY); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { } try { decimal("1.001").descaleTo(0, RoundingMode.UNNECESSARY); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { } try { decimal("0.001").descaleTo(0, RoundingMode.UNNECESSARY); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { } try { decimal("-0.001").descaleTo(0, RoundingMode.UNNECESSARY); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { } try { decimal("-1.001").descaleTo(0, RoundingMode.UNNECESSARY); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { } try { decimal("-2.501").descaleTo(0, RoundingMode.UNNECESSARY); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { } try { decimal("-5.501").descaleTo(0, RoundingMode.UNNECESSARY); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { } } @Test public void shouldDoNothingWhenDescaleOfLongDecimalIsNotNeeded() { newList( "5.5", "2.5", "1.6", "1.1", "1.0", "-1.0", "-1.1", "-1.6", "-2.5", "-5.5" ).forEach(value -> { for (RoundingMode roundingMode : RoundingMode.values()) { assertThat(decimal(value).descaleTo(1, roundingMode), equalTo(decimal(value))); assertThat(decimal(value).descaleTo(Integer.MAX_VALUE, roundingMode), equalTo(decimal(value)));
assertThat(decimal(value).descaleTo(randomInt(2, Integer.MAX_VALUE - 1), roundingMode), equalTo(decimal(value)));
MatejTymes/JavaFixes
src/test/java/javafixes/math/DecimalDescaleTest.java
// Path: src/main/java/javafixes/collection/CollectionUtil.java // @SafeVarargs // public static <T> ArrayList<T> newList(T... values) { // ArrayList<T> list = new ArrayList<T>(values.length); // Collections.addAll(list, values); // return list; // } // // Path: src/main/java/javafixes/math/Decimal.java // public static Decimal d(long unscaledValue, int scale) throws ArithmeticException { // return decimal(unscaledValue, scale); // } // // Path: src/main/java/javafixes/math/Decimal.java // public static Decimal decimal(long unscaledValue, int scale) throws ArithmeticException { // while (unscaledValue != 0 // && ((int) unscaledValue & 1) == 0 // && unscaledValue % 10 == 0) { // unscaledValue /= 10; // // if (scale == Integer.MIN_VALUE) { // throw new ArithmeticException(format("Scale underflow - can't set scale to less than '%d'", Integer.MIN_VALUE)); // } // scale--; // } // // return new LongDecimal(unscaledValue, scale); // } // // Path: src/test/java/javafixes/test/Random.java // @SafeVarargs // public static int randomInt(int from, int to, Function<Integer, Boolean>... validityConditions) { // return generateValidValue( // // typecast it to long as otherwise we could get int overflow // () -> (int) ((long) (Math.random() * ((long) to - (long) from + 1L)) + (long) from), // validityConditions // ); // }
import org.junit.Test; import java.math.RoundingMode; import java.util.List; import static javafixes.collection.CollectionUtil.newList; import static javafixes.math.Decimal.d; import static javafixes.math.Decimal.decimal; import static javafixes.test.Random.randomInt; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail;
"-100000000000000000000000005.5" ).forEach(value -> { for (RoundingMode roundingMode : RoundingMode.values()) { assertThat(decimal(value).descaleTo(1, roundingMode), equalTo(decimal(value))); assertThat(decimal(value).descaleTo(Integer.MAX_VALUE, roundingMode), equalTo(decimal(value))); assertThat(decimal(value).descaleTo(randomInt(2, Integer.MAX_VALUE - 1), roundingMode), equalTo(decimal(value))); } }); newList( "100000000000000000000000005.501", "100000000000000000000000002.501", "100000000000000000000000001.001", "100000000000000000000000000.001", "-100000000000000000000000000.001", "-100000000000000000000000001.001", "-100000000000000000000000002.501", "-100000000000000000000000005.501" ).forEach(value -> { for (RoundingMode roundingMode : RoundingMode.values()) { assertThat(decimal(value).descaleTo(3, roundingMode), equalTo(decimal(value))); assertThat(decimal(value).descaleTo(Integer.MAX_VALUE, roundingMode), equalTo(decimal(value))); assertThat(decimal(value).descaleTo(randomInt(4, Integer.MAX_VALUE - 1), roundingMode), equalTo(decimal(value))); } }); } @Test public void shouldWorkForDerivedMethods() { List<Decimal> numbers = newList(
// Path: src/main/java/javafixes/collection/CollectionUtil.java // @SafeVarargs // public static <T> ArrayList<T> newList(T... values) { // ArrayList<T> list = new ArrayList<T>(values.length); // Collections.addAll(list, values); // return list; // } // // Path: src/main/java/javafixes/math/Decimal.java // public static Decimal d(long unscaledValue, int scale) throws ArithmeticException { // return decimal(unscaledValue, scale); // } // // Path: src/main/java/javafixes/math/Decimal.java // public static Decimal decimal(long unscaledValue, int scale) throws ArithmeticException { // while (unscaledValue != 0 // && ((int) unscaledValue & 1) == 0 // && unscaledValue % 10 == 0) { // unscaledValue /= 10; // // if (scale == Integer.MIN_VALUE) { // throw new ArithmeticException(format("Scale underflow - can't set scale to less than '%d'", Integer.MIN_VALUE)); // } // scale--; // } // // return new LongDecimal(unscaledValue, scale); // } // // Path: src/test/java/javafixes/test/Random.java // @SafeVarargs // public static int randomInt(int from, int to, Function<Integer, Boolean>... validityConditions) { // return generateValidValue( // // typecast it to long as otherwise we could get int overflow // () -> (int) ((long) (Math.random() * ((long) to - (long) from + 1L)) + (long) from), // validityConditions // ); // } // Path: src/test/java/javafixes/math/DecimalDescaleTest.java import org.junit.Test; import java.math.RoundingMode; import java.util.List; import static javafixes.collection.CollectionUtil.newList; import static javafixes.math.Decimal.d; import static javafixes.math.Decimal.decimal; import static javafixes.test.Random.randomInt; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertThat; import static org.junit.Assert.fail; "-100000000000000000000000005.5" ).forEach(value -> { for (RoundingMode roundingMode : RoundingMode.values()) { assertThat(decimal(value).descaleTo(1, roundingMode), equalTo(decimal(value))); assertThat(decimal(value).descaleTo(Integer.MAX_VALUE, roundingMode), equalTo(decimal(value))); assertThat(decimal(value).descaleTo(randomInt(2, Integer.MAX_VALUE - 1), roundingMode), equalTo(decimal(value))); } }); newList( "100000000000000000000000005.501", "100000000000000000000000002.501", "100000000000000000000000001.001", "100000000000000000000000000.001", "-100000000000000000000000000.001", "-100000000000000000000000001.001", "-100000000000000000000000002.501", "-100000000000000000000000005.501" ).forEach(value -> { for (RoundingMode roundingMode : RoundingMode.values()) { assertThat(decimal(value).descaleTo(3, roundingMode), equalTo(decimal(value))); assertThat(decimal(value).descaleTo(Integer.MAX_VALUE, roundingMode), equalTo(decimal(value))); assertThat(decimal(value).descaleTo(randomInt(4, Integer.MAX_VALUE - 1), roundingMode), equalTo(decimal(value))); } }); } @Test public void shouldWorkForDerivedMethods() { List<Decimal> numbers = newList(
d("5.5"), d("2.5"), d("1.6"), d("1.1"), d("1.0"), d("-1.0"),
Devskiller/friendly-id
friendly-id-samples/friendly-id-spring-boot-hateos/src/main/java/com/devskiller/friendly_id/sample/hateos/FooController.java
// Path: friendly-id-samples/friendly-id-spring-boot-hateos/src/main/java/com/devskiller/friendly_id/sample/hateos/domain/Foo.java // @Data // @AllArgsConstructor // public class Foo { // // private UUID id; // private String name; // // }
import com.devskiller.friendly_id.sample.hateos.domain.Foo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.hateoas.server.ExposesResourceFor; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder; import java.lang.invoke.MethodHandles; import java.net.URI; import java.util.UUID; import static org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder.on;
package com.devskiller.friendly_id.sample.hateos; @RestController @ExposesResourceFor(FooResource.class) @RequestMapping("/foos") public class FooController { private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); private final FooResourceAssembler assembler; public FooController(FooResourceAssembler assembler) { this.assembler = assembler; } @GetMapping("/{id}") public HttpEntity<FooResource> get(@PathVariable UUID id) { log.info("Get {}", id);
// Path: friendly-id-samples/friendly-id-spring-boot-hateos/src/main/java/com/devskiller/friendly_id/sample/hateos/domain/Foo.java // @Data // @AllArgsConstructor // public class Foo { // // private UUID id; // private String name; // // } // Path: friendly-id-samples/friendly-id-spring-boot-hateos/src/main/java/com/devskiller/friendly_id/sample/hateos/FooController.java import com.devskiller.friendly_id.sample.hateos.domain.Foo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.hateoas.server.ExposesResourceFor; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder; import java.lang.invoke.MethodHandles; import java.net.URI; import java.util.UUID; import static org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder.on; package com.devskiller.friendly_id.sample.hateos; @RestController @ExposesResourceFor(FooResource.class) @RequestMapping("/foos") public class FooController { private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); private final FooResourceAssembler assembler; public FooController(FooResourceAssembler assembler) { this.assembler = assembler; } @GetMapping("/{id}") public HttpEntity<FooResource> get(@PathVariable UUID id) { log.info("Get {}", id);
Foo foo = new Foo(id, "Foo");
Devskiller/friendly-id
friendly-id-samples/friendly-id-spring-boot-customized/src/test/java/com/devskiller/friendly_id/sample/customized/ApplicationTest.java
// Path: friendly-id/src/main/java/com/devskiller/friendly_id/FriendlyId.java // public class FriendlyId { // // /** // * Create FriendlyId id // * // * @return Friendly Id encoded UUID // */ // public static String createFriendlyId() { // return Url62.encode(UUID.randomUUID()); // } // // /** // * Encode UUID to FriendlyId id // * // * @param uuid UUID to be encoded // * @return Friendly Id encoded UUID // */ // public static String toFriendlyId(UUID uuid) { // return Url62.encode(uuid); // } // // /** // * Decode Friendly Id to UUID // * // * @param friendlyId encoded UUID // * @return decoded UUID // */ // public static UUID toUuid(String friendlyId) { // return Url62.decode(friendlyId); // } // // } // // Path: friendly-id/src/main/java/com/devskiller/friendly_id/FriendlyId.java // public static UUID toUuid(String friendlyId) { // return Url62.decode(friendlyId); // }
import com.devskiller.friendly_id.FriendlyId; import com.devskiller.friendly_id.spring.EnableFriendlyId; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.http.MediaType; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import java.util.UUID; import static com.devskiller.friendly_id.FriendlyId.toUuid; import static org.hamcrest.CoreMatchers.is; import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.then; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
package com.devskiller.friendly_id.sample.customized; @RunWith(SpringRunner.class) @WebMvcTest(BarController.class) @EnableFriendlyId public class ApplicationTest { @Autowired MockMvc mockMvc; @MockBean FooService fooService; @Test public void shouldSerialize() throws Exception { // given UUID uuid = UUID.randomUUID(); given(fooService.find(uuid)).willReturn(new Bar(uuid, uuid)); // expect
// Path: friendly-id/src/main/java/com/devskiller/friendly_id/FriendlyId.java // public class FriendlyId { // // /** // * Create FriendlyId id // * // * @return Friendly Id encoded UUID // */ // public static String createFriendlyId() { // return Url62.encode(UUID.randomUUID()); // } // // /** // * Encode UUID to FriendlyId id // * // * @param uuid UUID to be encoded // * @return Friendly Id encoded UUID // */ // public static String toFriendlyId(UUID uuid) { // return Url62.encode(uuid); // } // // /** // * Decode Friendly Id to UUID // * // * @param friendlyId encoded UUID // * @return decoded UUID // */ // public static UUID toUuid(String friendlyId) { // return Url62.decode(friendlyId); // } // // } // // Path: friendly-id/src/main/java/com/devskiller/friendly_id/FriendlyId.java // public static UUID toUuid(String friendlyId) { // return Url62.decode(friendlyId); // } // Path: friendly-id-samples/friendly-id-spring-boot-customized/src/test/java/com/devskiller/friendly_id/sample/customized/ApplicationTest.java import com.devskiller.friendly_id.FriendlyId; import com.devskiller.friendly_id.spring.EnableFriendlyId; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.http.MediaType; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import java.util.UUID; import static com.devskiller.friendly_id.FriendlyId.toUuid; import static org.hamcrest.CoreMatchers.is; import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.then; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; package com.devskiller.friendly_id.sample.customized; @RunWith(SpringRunner.class) @WebMvcTest(BarController.class) @EnableFriendlyId public class ApplicationTest { @Autowired MockMvc mockMvc; @MockBean FooService fooService; @Test public void shouldSerialize() throws Exception { // given UUID uuid = UUID.randomUUID(); given(fooService.find(uuid)).willReturn(new Bar(uuid, uuid)); // expect
mockMvc.perform(get("/bars/{id}", FriendlyId.toFriendlyId(uuid)))
Devskiller/friendly-id
friendly-id-samples/friendly-id-spring-boot-customized/src/test/java/com/devskiller/friendly_id/sample/customized/ApplicationTest.java
// Path: friendly-id/src/main/java/com/devskiller/friendly_id/FriendlyId.java // public class FriendlyId { // // /** // * Create FriendlyId id // * // * @return Friendly Id encoded UUID // */ // public static String createFriendlyId() { // return Url62.encode(UUID.randomUUID()); // } // // /** // * Encode UUID to FriendlyId id // * // * @param uuid UUID to be encoded // * @return Friendly Id encoded UUID // */ // public static String toFriendlyId(UUID uuid) { // return Url62.encode(uuid); // } // // /** // * Decode Friendly Id to UUID // * // * @param friendlyId encoded UUID // * @return decoded UUID // */ // public static UUID toUuid(String friendlyId) { // return Url62.decode(friendlyId); // } // // } // // Path: friendly-id/src/main/java/com/devskiller/friendly_id/FriendlyId.java // public static UUID toUuid(String friendlyId) { // return Url62.decode(friendlyId); // }
import com.devskiller.friendly_id.FriendlyId; import com.devskiller.friendly_id.spring.EnableFriendlyId; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.http.MediaType; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import java.util.UUID; import static com.devskiller.friendly_id.FriendlyId.toUuid; import static org.hamcrest.CoreMatchers.is; import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.then; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
.andDo(print()) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andExpect(jsonPath("$.friendlyId", is(FriendlyId.toFriendlyId(uuid)))) .andExpect(jsonPath("$.uuid", is(uuid.toString()))); } @Test public void shouldDeserialize() throws Exception { // given UUID uuid = UUID.randomUUID(); String json = "{\"friendlyId\":\"" + FriendlyId.toFriendlyId(uuid) + "\",\"uuid\":\"" + uuid + "\"}"; // when mockMvc.perform(put("/bars/{id}", FriendlyId.toFriendlyId(uuid)) .content(json) .contentType(MediaType.APPLICATION_JSON)) .andDo(print()) .andExpect(status().isOk()); // then then(fooService) .should().update(uuid, new Bar(uuid, uuid)); } @Test public void sampleTestUsingPseudoUuid() throws Exception { // given
// Path: friendly-id/src/main/java/com/devskiller/friendly_id/FriendlyId.java // public class FriendlyId { // // /** // * Create FriendlyId id // * // * @return Friendly Id encoded UUID // */ // public static String createFriendlyId() { // return Url62.encode(UUID.randomUUID()); // } // // /** // * Encode UUID to FriendlyId id // * // * @param uuid UUID to be encoded // * @return Friendly Id encoded UUID // */ // public static String toFriendlyId(UUID uuid) { // return Url62.encode(uuid); // } // // /** // * Decode Friendly Id to UUID // * // * @param friendlyId encoded UUID // * @return decoded UUID // */ // public static UUID toUuid(String friendlyId) { // return Url62.decode(friendlyId); // } // // } // // Path: friendly-id/src/main/java/com/devskiller/friendly_id/FriendlyId.java // public static UUID toUuid(String friendlyId) { // return Url62.decode(friendlyId); // } // Path: friendly-id-samples/friendly-id-spring-boot-customized/src/test/java/com/devskiller/friendly_id/sample/customized/ApplicationTest.java import com.devskiller.friendly_id.FriendlyId; import com.devskiller.friendly_id.spring.EnableFriendlyId; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.http.MediaType; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import java.util.UUID; import static com.devskiller.friendly_id.FriendlyId.toUuid; import static org.hamcrest.CoreMatchers.is; import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.then; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; .andDo(print()) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andExpect(jsonPath("$.friendlyId", is(FriendlyId.toFriendlyId(uuid)))) .andExpect(jsonPath("$.uuid", is(uuid.toString()))); } @Test public void shouldDeserialize() throws Exception { // given UUID uuid = UUID.randomUUID(); String json = "{\"friendlyId\":\"" + FriendlyId.toFriendlyId(uuid) + "\",\"uuid\":\"" + uuid + "\"}"; // when mockMvc.perform(put("/bars/{id}", FriendlyId.toFriendlyId(uuid)) .content(json) .contentType(MediaType.APPLICATION_JSON)) .andDo(print()) .andExpect(status().isOk()); // then then(fooService) .should().update(uuid, new Bar(uuid, uuid)); } @Test public void sampleTestUsingPseudoUuid() throws Exception { // given
UUID barId = toUuid("barId");
Devskiller/friendly-id
friendly-id-jackson-datatype/src/test/java/com/devskiller/friendly_id/spring/ObjectMapperConfiguration.java
// Path: friendly-id-jackson-datatype/src/main/java/com/devskiller/friendly_id/jackson/FriendlyIdModule.java // public class FriendlyIdModule extends SimpleModule { // // private FriendlyIdAnnotationIntrospector introspector; // // public FriendlyIdModule() { // introspector = new FriendlyIdAnnotationIntrospector(); // addDeserializer(UUID.class, new FriendlyIdDeserializer()); // addSerializer(UUID.class, new FriendlyIdSerializer()); // } // // @Override // public void setupModule(SetupContext context) { // context.insertAnnotationIntrospector(introspector); // } // }
import com.fasterxml.jackson.databind.Module; import com.fasterxml.jackson.databind.ObjectMapper; import com.devskiller.friendly_id.jackson.FriendlyIdModule;
package com.devskiller.friendly_id.spring; public class ObjectMapperConfiguration { protected static ObjectMapper mapper(Module... modules) { ObjectMapper mapper = new ObjectMapper();
// Path: friendly-id-jackson-datatype/src/main/java/com/devskiller/friendly_id/jackson/FriendlyIdModule.java // public class FriendlyIdModule extends SimpleModule { // // private FriendlyIdAnnotationIntrospector introspector; // // public FriendlyIdModule() { // introspector = new FriendlyIdAnnotationIntrospector(); // addDeserializer(UUID.class, new FriendlyIdDeserializer()); // addSerializer(UUID.class, new FriendlyIdSerializer()); // } // // @Override // public void setupModule(SetupContext context) { // context.insertAnnotationIntrospector(introspector); // } // } // Path: friendly-id-jackson-datatype/src/test/java/com/devskiller/friendly_id/spring/ObjectMapperConfiguration.java import com.fasterxml.jackson.databind.Module; import com.fasterxml.jackson.databind.ObjectMapper; import com.devskiller.friendly_id.jackson.FriendlyIdModule; package com.devskiller.friendly_id.spring; public class ObjectMapperConfiguration { protected static ObjectMapper mapper(Module... modules) { ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new FriendlyIdModule());
Devskiller/friendly-id
friendly-id-samples/friendly-id-contracts/src/main/java/com/devskiller/friendly_id/sample/contracts/BarController.java
// Path: friendly-id-samples/friendly-id-contracts/src/main/java/com/devskiller/friendly_id/sample/contracts/domain/Bar.java // @Data // @AllArgsConstructor // public class Bar { // // private UUID id; // private String name; // // private Foo foo; // // } // // Path: friendly-id-samples/friendly-id-contracts/src/main/java/com/devskiller/friendly_id/sample/contracts/domain/Foo.java // @Data // @AllArgsConstructor // public class Foo { // // private UUID id; // private String name; // // }
import com.devskiller.friendly_id.sample.contracts.domain.Bar; import com.devskiller.friendly_id.sample.contracts.domain.Foo; import org.springframework.hateoas.server.ExposesResourceFor; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.UUID;
package com.devskiller.friendly_id.sample.contracts; @RestController @ExposesResourceFor(BarResource.class) @RequestMapping("/foos/{fooId}/bars") public class BarController { private final BarResourceAssembler assembler; public BarController(BarResourceAssembler assembler) { this.assembler = assembler; } @GetMapping("/{id}") public BarResource getBar(@PathVariable UUID fooId, @PathVariable UUID id) {
// Path: friendly-id-samples/friendly-id-contracts/src/main/java/com/devskiller/friendly_id/sample/contracts/domain/Bar.java // @Data // @AllArgsConstructor // public class Bar { // // private UUID id; // private String name; // // private Foo foo; // // } // // Path: friendly-id-samples/friendly-id-contracts/src/main/java/com/devskiller/friendly_id/sample/contracts/domain/Foo.java // @Data // @AllArgsConstructor // public class Foo { // // private UUID id; // private String name; // // } // Path: friendly-id-samples/friendly-id-contracts/src/main/java/com/devskiller/friendly_id/sample/contracts/BarController.java import com.devskiller.friendly_id.sample.contracts.domain.Bar; import com.devskiller.friendly_id.sample.contracts.domain.Foo; import org.springframework.hateoas.server.ExposesResourceFor; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.UUID; package com.devskiller.friendly_id.sample.contracts; @RestController @ExposesResourceFor(BarResource.class) @RequestMapping("/foos/{fooId}/bars") public class BarController { private final BarResourceAssembler assembler; public BarController(BarResourceAssembler assembler) { this.assembler = assembler; } @GetMapping("/{id}") public BarResource getBar(@PathVariable UUID fooId, @PathVariable UUID id) {
return assembler.toModel(new Bar(id, "Bar", new Foo(fooId, "Root Foo")));
Devskiller/friendly-id
friendly-id-samples/friendly-id-contracts/src/main/java/com/devskiller/friendly_id/sample/contracts/BarController.java
// Path: friendly-id-samples/friendly-id-contracts/src/main/java/com/devskiller/friendly_id/sample/contracts/domain/Bar.java // @Data // @AllArgsConstructor // public class Bar { // // private UUID id; // private String name; // // private Foo foo; // // } // // Path: friendly-id-samples/friendly-id-contracts/src/main/java/com/devskiller/friendly_id/sample/contracts/domain/Foo.java // @Data // @AllArgsConstructor // public class Foo { // // private UUID id; // private String name; // // }
import com.devskiller.friendly_id.sample.contracts.domain.Bar; import com.devskiller.friendly_id.sample.contracts.domain.Foo; import org.springframework.hateoas.server.ExposesResourceFor; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.UUID;
package com.devskiller.friendly_id.sample.contracts; @RestController @ExposesResourceFor(BarResource.class) @RequestMapping("/foos/{fooId}/bars") public class BarController { private final BarResourceAssembler assembler; public BarController(BarResourceAssembler assembler) { this.assembler = assembler; } @GetMapping("/{id}") public BarResource getBar(@PathVariable UUID fooId, @PathVariable UUID id) {
// Path: friendly-id-samples/friendly-id-contracts/src/main/java/com/devskiller/friendly_id/sample/contracts/domain/Bar.java // @Data // @AllArgsConstructor // public class Bar { // // private UUID id; // private String name; // // private Foo foo; // // } // // Path: friendly-id-samples/friendly-id-contracts/src/main/java/com/devskiller/friendly_id/sample/contracts/domain/Foo.java // @Data // @AllArgsConstructor // public class Foo { // // private UUID id; // private String name; // // } // Path: friendly-id-samples/friendly-id-contracts/src/main/java/com/devskiller/friendly_id/sample/contracts/BarController.java import com.devskiller.friendly_id.sample.contracts.domain.Bar; import com.devskiller.friendly_id.sample.contracts.domain.Foo; import org.springframework.hateoas.server.ExposesResourceFor; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.UUID; package com.devskiller.friendly_id.sample.contracts; @RestController @ExposesResourceFor(BarResource.class) @RequestMapping("/foos/{fooId}/bars") public class BarController { private final BarResourceAssembler assembler; public BarController(BarResourceAssembler assembler) { this.assembler = assembler; } @GetMapping("/{id}") public BarResource getBar(@PathVariable UUID fooId, @PathVariable UUID id) {
return assembler.toModel(new Bar(id, "Bar", new Foo(fooId, "Root Foo")));
Devskiller/friendly-id
friendly-id/src/test/java/com/devskiller/friendly_id/Base62Test.java
// Path: friendly-id/src/test/java/com/devskiller/friendly_id/IdUtil.java // static boolean areEqualIgnoringLeadingZeros(String code1, String code2) { // return areEqual(removeLeadingZeros(code1), removeLeadingZeros(code2)); // }
import org.junit.Test; import static com.devskiller.friendly_id.IdUtil.areEqualIgnoringLeadingZeros; import static io.vavr.test.Property.def; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.util.Objects.areEqual;
package com.devskiller.friendly_id; public class Base62Test { @Test public void decodingValuePrefixedWithZeros() { assertThat(Base62.encode(Base62.decode("00001"))).isEqualTo("1"); assertThat(Base62.encode(Base62.decode("01001"))).isEqualTo("1001"); assertThat(Base62.encode(Base62.decode("00abcd"))).isEqualTo("abcd"); } @Test public void shouldCheck128BitLimits() { assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> Base62.decode("1Vkp6axDWu5pI3q1xQO3oO0")); } @Test public void decodingIdShouldBeReversible() { def("areEqualIgnoringLeadingZeros(Base62.toFriendlyId(Base62.toUuid(id)), id)") .forAll(DataProvider.FRIENDLY_IDS)
// Path: friendly-id/src/test/java/com/devskiller/friendly_id/IdUtil.java // static boolean areEqualIgnoringLeadingZeros(String code1, String code2) { // return areEqual(removeLeadingZeros(code1), removeLeadingZeros(code2)); // } // Path: friendly-id/src/test/java/com/devskiller/friendly_id/Base62Test.java import org.junit.Test; import static com.devskiller.friendly_id.IdUtil.areEqualIgnoringLeadingZeros; import static io.vavr.test.Property.def; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.util.Objects.areEqual; package com.devskiller.friendly_id; public class Base62Test { @Test public void decodingValuePrefixedWithZeros() { assertThat(Base62.encode(Base62.decode("00001"))).isEqualTo("1"); assertThat(Base62.encode(Base62.decode("01001"))).isEqualTo("1001"); assertThat(Base62.encode(Base62.decode("00abcd"))).isEqualTo("abcd"); } @Test public void shouldCheck128BitLimits() { assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> Base62.decode("1Vkp6axDWu5pI3q1xQO3oO0")); } @Test public void decodingIdShouldBeReversible() { def("areEqualIgnoringLeadingZeros(Base62.toFriendlyId(Base62.toUuid(id)), id)") .forAll(DataProvider.FRIENDLY_IDS)
.suchThat(id -> areEqualIgnoringLeadingZeros(Base62.encode(Base62.decode(id)), id))